texts: Sheet display in function of date and time on open and save (2)

texts:
Since I had to almost start all of the code again with first refactor and an eye opening advice on a random Overflow question, here it is again:
This is a code that selects the right sheet according to the day of the week(date) and time(Now).
The code finds the day of the week (in French), determines if we are in night or day shift depending on time limits also depending of the days: it then concatenates the 2 ex: "Thursday" + "night" and finds the sheets name accordingly.
If it does not find a match (Friday night or weekend) it selects Friday sheet

The code is runned by workbook_open and beforeSave, so it need to be optimized as much as possible.
Here the whole code:
    Public Sub SelectionDeQuartAuto()
        Dim wsactivate As Boolean    ' Boolean turns true if ws is activated
        Dim joursemaine As String    ' Day of the week
        joursemaine = Application.WorksheetFunction.Text(Date, "[$-40c]DDDD")
        Dim shift As String
        shift = Shiftselect(IsDayShift(Now)) ' Returns "Day" or "Night" shifts

        Dim ws As Worksheet
        For Each ws In ThisWorkbook.Worksheets ' Loops trough all .visible ws to find a match w day+shift
            If ws.Visible Then
                If InStr(1, ws.Name, joursemaine & " " & shift, vbTextCompare) > 0 Then 'If ws.name contain day of the week + day or night shift
                    ws.Activate
                    wsactivate = True
                    Exit For
                End If
            End If
        Next
        If wsactivate = False Then           ' If no match
            Sheets("Vendredi jour").Activate ' Activate friday
        End If
    End Sub

    Public Function Shiftselect(Isday As Boolean) As String
    ' Returns "Day" or "Night" string depending on IsDay boolean
        If Isday Then
            Shiftselect = "jour"
        Else
            Shiftselect = "soir"
        End If
    End Function

    Public Function IsDayShift(ByVal DateTime As Date) As Boolean
    ' Return a true boolean if we are outside night shift boundaries, return false elseways
        If weekday(DateTime, vbSunday) = vbThursday Then ' If we are thursday night shift boundaries are different
            IsDayShift = TimeValue(DateTime) > TimeValue("03:00:00") And TimeValue(DateTime) < TimeValue("15:15:00") ' If Time is outside night shift limit assume its day shift
        Else ' Monday to wednesday + friday (no night shift on friday) use normal boundaries
            IsDayShift = TimeValue(DateTime) > TimeValue("03:00:00") And TimeValue(DateTime) < TimeValue("16:15:00")
        End If
End Function


texts: Method for sorting numbers from user input

texts:
I have an input with numbers 1, 2, 3, 4 and I want to change the order of this number dynamically according to users input. You can find my code below and also a running example here.

HTML

<input type="text" name="name1" id="1" value="1" class="order">
<input type="text" name="name2" id="2" value="2" class="order">
<input type="text" name="name3" id="3" value="3" class="order">
<input type="text" name="name4" id="4" value="4" class="order">

jQuery

var myArray = new Array();
        $(".order").each(function() {
            myArray[$(this).attr('id')] = $(this).val();

        });//array to use when id and value are equal

    $('.order').live('change', function(){
            previousVal = $(this).val();
            previousId = $(this).attr('id');
            });//on change get this value as static to use later

    $('input.order').on('blur', function() {
    var idofnewvalue = $(this).attr('id');
    var newvalue = $(this).val();
    $(".order").each(function(){
            if (newvalue == $(this).val()) {
                    if(idofnewvalue != $(this).attr('id')){
                    var duplicate = $(this).val();
                        if(+previousVal > +previousId){
                            var plus = +duplicate - 1;
                            $("#"+duplicate).val(plus);

                        }else if(+previousVal < +previousId){
                            var plus = +duplicate + 1;
                            $("#"+duplicate).val(plus);
                        }else if(+previousVal == +previousId){
                            for ( var key in myArray) {

                                if (myArray.hasOwnProperty(key)) {
                                    $("#"+key).val(key);

                                  }
                                }

                        }

                    }
                    $("#"+duplicate).trigger("blur");//triggers blur event untill done
            }
        });
    });

The above code changes the value of the input according to users input.

For example, if the input is 1 2 3 4 and the user changes 4 to be 2, then the result will be 1 3 4 2.  If the user changes 2 to be 4 then the result will be 1 4 2 3.

Please tell me what you think about the above code.


texts: Query to show each sites stock transfer history between all other sites

texts:
The below query is used to return a dataset for a SSRS report. It works fine and is quick enough but I am looking for any improvements that could be made.

The client has asked to see all transfers between sites and the report should look like:

Site1

Site 2
Site 3

Site2

Site 1
Site 3

Each row should also show the value of the transfer to that site and from that site. Duplicated data is expected I.E If Site 1 transferred goods to Site 2 then Site 2 should display the same value in the from column. If no transfer takes place the site should be visible but with a value of 0 in both To and from columns.

The Exists clause must remain as well as it is used to workout descendants of selected site.

WITH Transfers_CTE(FromSiteNo
                  ,ToSiteNo
                  ,Value)
     AS (
     SELECT Transfers.FromSiteNo
           ,Transfers.ToSiteNo
           ,SUM(Transfers.[Value]) AS Value
     FROM dbo.Transfers
     WHERE Transfers.MoveDate BETWEEN @SessionDateFrom AND @SessionDateTo
     GROUP BY Transfers.FromSiteNo
             ,Transfers.ToSiteNo)
     SELECT CS.No AS SiteNo
           ,CS.Name AS SiteName
           ,JoinedSites.No AS OtherSiteNo
           ,JoinedSites.Name AS OtherSiteName
           ,ISNULL(ToTable.[Value],0) AS ToValue
           ,ISNULL(FromTable.[Value],0) AS FromValue
     FROM dbo.CfgSites AS CS
          FULL OUTER JOIN dbo.CfgSites AS JoinedSites ON CS.No != JoinedSites.No
          LEFT JOIN Transfers_CTE AS ToTable ON ToTable.FromSiteNo = CS.No
                                                AND ToTable.ToSiteNo = JoinedSites.No
          LEFT JOIN Transfers_CTE AS FromTable ON FromTable.ToSiteNo = CS.No
                                                  AND FromTable.FromSiteNo = JoinedSites.No
     WHERE EXISTS
(
    SELECT DescendantSites.Descendant
    FROM dbo.DescendantSites
    WHERE DescendantSites.Parent IN(@SiteNo)
    AND DescendantSites.Descendant = CS.No
)
     ORDER BY CS.No;

Subset DDL for CfgSites and Transfer View that only includes required fields

/****** Object:  Table [dbo].[CfgSites]    Script Date: 13/04/2018 08:47:32 ******/

CREATE TABLE [dbo].[CfgSites](
    [No] [smallint] NOT NULL,
    [Name] [varchar](50) NULL)
GO
/****** Object:  View [dbo].[Transfers]    Script Date: 13/04/2018 08:47:32 ******/

CREATE VIEW [dbo].[Transfers]
AS
SELECT [SiteNo] AS FromSiteNo
    ,[Site2No] AS ToSiteNo
    ,[Date] AS MoveDate
    ,[Value]
FROM PluMovement
WHERE MoveType = 4
    AND Processed = 1


texts: Python script to download adult comics from 8muses

texts:
I made a simple python script using the BeautifulSoup and Selenium to automatically download adult comics from 8muses.  I've used selenium for the reason that the website uses javascript to load the images.

Enter the the gallery url and download location to start downloading.
Sample gallery urls:

https://www.8muses.com/comics/album/MilfToon-Comics/Milfage/Issue-1
https://www.8muses.com/comics/album/MilfToon-Comics/Lemonade/Lemonade-1

I would like to know improvements to the code or alternative methods to make it work faster. Thanks !

Code : app.py

import os
from multiprocessing.dummy import Pool
from queue import Queue
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from threading import Thread
import urllib.request
import requests
import shutil

options = Options()
options.headless = True
chrome_driver_path = r"C:\Users\NH\PycharmProjects\SeleniumTest\drivers\chromedriver.exe"
base_url = "https://www.8muses.com"

def fetch_image_url(url,filename,download_location):
    driver = webdriver.Chrome(chrome_driver_path, chrome_options=options)
    driver.get(url)
    page = driver.page_source
    soup = BeautifulSoup(page,"lxml")
    image_url = "http:"+soup.find("img",{"class":"image"})['src']
    download_image(image_url,filename,download_location)

def download_image(image_url,filename,download_location):
    r = requests.get(image_url,stream=True, headers={'User-agent': 'Mozilla/5.0'})
    if r.status_code == 200:
        with open(os.path.join(download_location,str(filename)+".png"), 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)
    print("Downloaded page {pagenumber}".format(pagenumber=filename))

if __name__=="__main__":
    print("Album Url : ")
    album_url = input()
    print("Download Location : ")
    download_location = input()
    driver = webdriver.Chrome(chrome_driver_path, chrome_options=options)
    print("Loading Comic...")
    driver.get(album_url)
    album_html = driver.page_source
    print("Comic successfully loaded")
    soup = BeautifulSoup(album_html,"lxml")
    comic_name = soup.find("title").text.split("|")[0].strip()
    download_location = os.path.join(download_location,comic_name)
    os.mkdir(download_location)
    print("Finding comic's pages")
    images = soup.find_all("a",{"class":"c-tile t-hover"})
    page_urls = []
    pages = []
    threads = []
    for image in images:
        page_urls.append(base_url + image['href'])
    print("Found {} pages".format(len(page_urls)))
    for i in  range(len(page_urls)):
            pages.append((page_urls[i],i,download_location))
    p = Pool(3)  # 3 threads in the pool
    p.starmap(fetch_image_url,pages)
    p.close()
    p.join()
    driver.quit()
    print ("DONE ! Happy Reading ")

Github for the project : https://github.com/ggrievous/8muser


texts: Setting a value of an iframe in the parent

texts:
This code works on Chrome 58 but it makes me feel dirty:

parent.parent.parent.document.F1.document.getElementById("txtNewDrugAction").value = "foobar"

F1 is the name of the iFrame where the text box resides.

I am setting the value of an input box from a modal popup window (via jQuery UI).  I've tried to use selectors etc, but to no avail.  I feel like there would be a hugely easier way to do this that would also be more resilient to changes in the DOM but I can't see it just yet...

I also wind up writing code like this (again, functional, but awful):

window.top.document.getElementById("F1").contentWindow.document.getElementById("txtRefresh") = "foobar"

I'm maintaining a legacy application. Please nobody think that something that uses frames is being created in 2017, especially not by me.


texts: Read/write a pipe-delimited file line by line with some simple text manipulation

texts:
This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion.

I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.

counter=1
for line in open(r"C:\Path\name.txt"):
    spline = line.split("|")
    if counter==1:
        with open(r"C:\PATH\2019.txt",'a') as NewFile:
            spline.insert(23,"Column A")
            spline.insert(23,"Column B")
            s="|"
            newline=s.join(spline)
            NewFile.write(newline)

    elif counter > 1 and not spline[22]=="0.00":
        spline.insert(23,"")
        spline.insert(23,"")
        gl=spline[0]
        gl=gl.strip()
        if gl[0]=="-": gl="000" + gl
        gl=gl.upper()
        spline[0]=gl

        if gl[:3]=="000": spline[24]="Incorrect"

        s="|"
        newline=s.join(spline)

        with open(r"C:\PATH\PythonWrittenData.txt",'a') as NewFile:
            NewFile.write(newline)

    counter+=1
    if counter%100000==0: print("Status Update: \n", "{:,}".format(counter))


texts: Greatest prime number smaller than N where N can be as large as 10^18

texts:
This is code for finding largest prime number smaller than \$N\$, where \$N\$ can be as large as \$10^{18}\$.  But, it takes 1 minute for \$10^{18}\$. I need to pass it in 2-3 sec.

What changes should I make to pass it?  My compiler used is g++ 4.3.2

The program here runs for multiple test cases.

#include <iostream>
#include <cmath>

#define c2 341550071728321
#define c1 4759123141

using namespace std;

unsigned long long int mul(unsigned long long int a, unsigned long long int b, unsigned      long long int mod)
{
    int i;
    unsigned long long int now = 0;
    for (i = 63; i >= 0; i--) if (((a >> i) & 1) == 1) break;
    for (; i >= 0; i--)
    {
        now <<= 1;
        while (now > mod) now -= mod;
        if (((a >> i) & 1) == 1) now += b;
        while (now > mod) now -= mod;
    }
    return now;
}

unsigned long long int pow(unsigned long long int a, unsigned long long int p, unsigned long long int mod)
{
    if (p == 0) return 1;
    if (p % 2 == 0) return pow(mul(a, a, mod), p / 2, mod);
    return mul(pow(a, p - 1, mod), a, mod);
}

bool MillerRabin(unsigned long long int n)
{
    int l;
     unsigned long long int ar[9] = { 2, 3, 5, 7, 11, 13, 17, 19, 23};
    if (n < c1) {

            l = 3;
    }
    else if (n < c2) {
            l = 7;
    }
    else {

            l = 9;
    }
    //l = 9;
    unsigned long long d = n - 1;
    int s = 0;
    while ((d & 1) == 0) { d >>= 1; s++; }
    int i, j;
    for (i = 0; i < l; i++)
    {
        unsigned long long int a  = min(n - 2, ar[i]);
        unsigned long long int now = pow(a, d, n);
        if (now == 1) continue;
        if (now == n - 1) continue;
        for (j = 1; j < s; j++)
        {
            now = mul(now, now, n);
            if (now == n - 1) break;
        }
        if (j == s) return false;
    }
    return true;
}

bool check_prime(unsigned long long int n) {

if(!MillerRabin(n)) return false;
return true;
if(n == 2) return true;
if(n % 2 == 0) return false;
for(unsigned long long int i = 3; i <= sqrt(n); i+=2) {
    if(n % i == 0) return false;
}
return true;
}

int main()
{
int t;

cin >> t;

while(t--) {
    unsigned long long int n;
    cin >> n;
    while(1) {
        if(check_prime(n)) {
            cout << n << endl;
            break;
        }
        else {
            n--;
        }
    }
}

}


texts:
I have a script running as an hourly cron job. It finds all screenshots on the Desktop and moves them to directories sorted by year/month/day.

On MacOS, screenshots are automatically saved to the desktop with the following filename structure:

"/Users/<USER>/Desktop/Screen Shot 2019-01-02 at 11.56.42 AM.png"

require 'fileutils'

class Screenshot
  attr_reader :filepath

  def initialize(filepath)
    @filepath = filepath
  end

  def dir_exists?
    File.exists?(destination) || FileUtils.mkdir_p(destination)
  end

  def date
    @date ||= filepath.match(screenshot_regex)
  end

  def move
    FileUtils.mv(filepath, destination) if dir_exists?
  end

  def base_path
    "/Users/home/Pictures/Screenshots"
  end

  def destination
    "#{base_path}/#{date[:year]}/#{date[:month]}/#{date[:day]}"
  end

  def screenshot_regex
    /Shot (?<year>(.*))-(?<month>(.*))-(?<day>(.*)) at/
  end
end

class Screenshots
  attr_reader :directory
  def initialize(directory)
    @directory = directory
  end

  def filepaths
    Dir.glob("#{directory}/Screen Shot*.png")
  end

  def files
    filepaths.map{|i| Screenshot.new(i)}
  end

  def move_all
    files.each(&:move)
  end
end

Screenshots.new("/Users/home/Desktop").move_all

I'm sure there's a less messy approach here and I'd love to hear any criticism.


texts:
I need to call this function over a big dataset. I need it to be as efficient as possible but still be readable. Can I make it anymore efficient by using a different function for capitalize or blank check?

public static String nameFormat(String title, String firstname, String lastName) {

    if (StringUtils.isBlank(firstname) && StringUtils.isBlank(lastName)) {
        return "Unknown";
    }

    StringBuilder fullNameSB = new StringBuilder(lastName.trim().toUpperCase());
    fullNameSB.append(", ");
    fullNameSB.append(WordUtils.capitalizeFully(firstname.trim()));
    if (title != null) {
        fullNameSB.append(" ");
        // replace (mr.) with mr
        title = title.trim().replaceAll("\\.|\\)|\\(", "");
        fullNameSB.append("(");
        fullNameSB.append(WordUtils.capitalize(title));
        fullNameSB.append(")");
    }
    //Remove any double spaces that might be in a multipart first or surname
    return fullNameSB.toString().replaceAll("  ", "");

}


texts: Creating a webtrend function to remove duplication using js apply and call

texts:
How can I re-factor the code to remove duplication and create a common method ?

(function(){

    $("#a", "#main").bind("mouseover", function(){
              var id1 = $("#one").text(),
                  args = ["DCSext.common1","common1","DCSext.common2","DCSext.title","one", "DCSext.ti", id1];

              dcsMultitrack.apply(this, args);
     });

    $("#b", "#cool").bind("click", function(){
           var id2 = $("#two").text(),
               args = ["DCSext.common1","common1","DCSext.common2","DCSext.title", "two", "DCSext.some", id2];
               dcsMultitrack.apply(this, args);
    });

    $("body").delegate("a", "click", function(){
         var id3 = $("#three").text(),
               args = ["DCSext.common1","common1","DCSext.common2","DCSext.new", "what", "DCSext.where", "us"];
               dcsMultitrack.apply(this, args);
    });

    }());

I have some common logs which are almost repeated in all callbacks. I can use a variable like

var commonlogs = ["DCSext.common1","common1","DCSext.common2","common2", "DCSext.common3", "common3" ];

i can use commonlogs.push("DCSext.title","one","DCSext.ti", "two"). But not finding a proper way to re-factoring repeating the DCSext stuff again and again since its very granular level .

Thanks for any advice or suggestions.


texts: MVC binding list of values to checkboxlist in an efficient way

texts:
I have this code which generates and shows list of selectable items that user can post to controller in order to save into database.

Model looks like this:

public class DeliveryAddressSelectionModel()
{
public List<DeliveryAddress> DeliveryAddresses { get; set; }
public List<int> SelectedAddressIDs { get; set; }
}
public class DeliveryAddress()
{
public int ID { get; set; }
public string Location { get; set; }
}

Controller looks like

[HttpGet]
public ActionResult Edit()
{
    var model = new DeliveryAddressSelectionModel();
    model.DeliveryAddresses = AddressDetails.GetAvailable(); //Get from  EF
    model.SelectedAddressIDs = new List<int>(); //Populate this list with Address IDs for pre-selection
    return View(model);
}

[HttpPost]
public ActionResult Edit(DeliveryAddressSelectionModel model)
{
    //save the model.SelectedAddressIDs in DB
    return RedirectToAction("Index");
}

And finally view looks like this:

<form method="post">

        @foreach(var address in DeliveryAddresses)
        {

            <input id="address@(address.ID)" type="checkbox"
                name="SelectedAddressIDs"
                value="@address.ID"
                @(Model.SelectedAddressIDs.Contains(address.ID) ? "checked" : "")
                />
            @address.Location

        }

    <input type="submit" value="Save Address"/>
</form>

This code works, but as I am learning  MVC, and I would like to have suggestions. What areas in this code could have been done better, or what is best practice in regards with this kind of model population and posting? Could I use a @Html.CheckBoxFor() helper or this is ok?


texts: Find k pairs with smallest sums in Python

texts:
I'm trying to improve my Python, so I'm trying to do coding challenges and getting them reviewed. I would really appreciate if someone can point out how I can make my code cleaner/more pythonic. My min_heap with a 3-value tuple seems a bit messy, but I couldn't think of a better way to do it.

Problem:

https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/

  You are given two integer arrays nums1 and nums2 sorted in ascending
  order and an integer k.

  Define a pair (u,v) which consists of one element from the first array and one element from the second array.

  Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.

Example 1:

  Given nums1 = [1,7,11], nums2 = [2,4,6],  k = 3

  Return: [1,2],[1,4],[1,6]

  The first 3 pairs are returned from the sequence:
      [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Solution:

from heapq import heappop, heappush

class Solution:
    def kSmallestPairs(self, nums1, nums2, k):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type k: int
        :rtype: List[List[int]]
        """
        solution = []
        min_heap = []

        # if nums1 or nums2 is empty or k is 0, we're done
        if not nums1 or not nums2 or not k:
            return solution

        # first initialize min_heap with all
        # (nums1[0..n], nums2[0]) pairs with
        # (sum of pair, (nums1[0..n], nums2[0]), index of nums2)
        for value in nums1:
            heappush(min_heap, (value+nums2[0], (value, nums2[0]), 0))

        while k and min_heap:
            curr_pair = heappop(min_heap)
            solution.append(curr_pair[1])
            nums2_idx = curr_pair[2]
            k -= 1
            # if we haven't exhausted all (nums1[curr], nums2[0..n])
            # pairs, offer pair (nums1[curr], nums2[curr+1]) to min_heap
            if curr_pair[2] == len(nums2)-1: continue

            heappush(min_heap, (curr_pair[1][0]+nums2[nums2_idx+1], (curr_pair[1][0],
                nums2[nums2_idx+1]), nums2_idx+1))

        return solution


texts: Recursive Implementation of Merge Sort C++

texts:
I am currently reading an algorithms book and I read on the insertion and merge sorts. I implemented the merge sort in C++, The first function MERGE is responsible for the merging of the two subarrays part and the function MERGE_SORT is the actual algorithm. I am interested to know whether or not my code has a good readability factor and if It can be optimized further or not?

#include <iostream>
#include <vector>
#include <limits>

using namespace std;

#define itr vector<int>::iterator
void MERGE(vector<int>& vec,itr left, itr mid, itr right){
    //Make vector left with elements from left to mid inclusive
    vector<int> left_vec;
    for (itr i=left; i!=vec.end()&&i<=mid;i++){
        left_vec.push_back(*i);
    }
    left_vec.push_back(numeric_limits<int>::max());//sentinel card
    //make vector right with elements from mid+1 to right inclusive
    vector<int> right_vec;
    for (itr i=mid+1; i!=vec.end() && i<=right; i++){
        right_vec.push_back(*i);
    }
    right_vec.push_back(numeric_limits<int>::max());//sentinel card
    //Now add them in a sorted manner to vector from left to right

    itr l=left_vec.begin(); itr r=right_vec.begin();
    for (itr vec_itr=left;vec_itr!=vec.end()&&vec_itr<=right;vec_itr++){
        if (*l<=*r){
            *vec_itr=*l;
            l++;
        }
        else{
            *vec_itr = *r;
            r++;
        }
    }
}
void MERGE_SORT(vector<int>& vec, itr left, itr right){
    if(left<right){
        itr mid = left + (right-left)/2;
        MERGE_SORT(vec,left,mid);
        MERGE_SORT(vec,mid+1,right);
        MERGE(vec, left,mid,right);
    }
    return;
}
int main() {
    int a[] = {10,8,9,7,6,3,3,9,15,4,3,2,1};
    vector<int> vec(a,a+13);
    MERGE_SORT(vec,vec.begin(),vec.end());
    for (itr i=vec.begin();i!=vec.end();i++)cout << *i << " ";
    return 0;
}


texts: Method and class method debugging decorator

texts:
A little while ago in The 2nd Monitor, me and @Phrancis were talking about Python and debugging, and the topic of function decorators came up with this message:

  Ethan Bierlein: You could even build a debug decorator. Give me a sec.

So, I built a small, simple debugging decorator, which would just print out the arguments of any method it was applied to.

I decided to go a little further though, and build two separate decorators. One for regular methods, and one built specifically for class methods. Essentially, the regular method decorator takes a function, and will print out it's arguments, and keyword arguments if debug=True. The class method decorator does the same, except it also prints out the attributes of the class it's contained in as well.

I'm wondering a couple of things though:

Is this a "pythonic" way to debug the arguments of a function?
Is there any additional data that should be debugged, that I missed?
Is the extra ClassMethodDecorator really needed? Or is there a simpler way to support both with one decorator?
I've built this to be Python 3, and Python 2.7 compatible. Did I do this correctly?

debug.py

from pprint import pprint

class MethodDebug(object):
    """Debug a normal method.

    This decorator is used for debugging a normal method,
    with normal arguments, i.e, not printing out the data
    of the class it's contained in.

    Keyword arguments:
    debug -- Whether or not you want to debug the method.
    """
    def __init__(self, debug):
        self.debug = debug

    def __call__(self, function):
        def wrapper(*args, **kwargs):
            if self.debug:
                pprint(args)
                pprint(kwargs)
            return function(*args, **kwargs)
        return wrapper

class ClassMethodDebug(object):
    """Debug a class method.

    This decorator is used for debugging a class method,
    with normal arguments, and self. When using this
    decorator, the method will print out it's arguments
    and the attributes of the class it's contained in.

    Keyword arguments:
    debug -- Whether or not you want to debug the method.
    """
    def __init__(self, debug):
        self.debug = debug

    def __call__(self, function):
        def wrapper(function_self, *args, **kwargs):
            if self.debug:
                pprint(function_self.__dict__)
                pprint(args)
                pprint(kwargs)
            return function(function_self, *args, **kwargs)
        return wrapper

test.py

from debug import MethodDebug, ClassMethodDebug

@MethodDebug(debug=True)
def normal_method(a, b):
    return a * b

print(normal_method(10, 10))

class TestClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @ClassMethodDebug(debug=True)
    def class_method(self, c):
        return self.a * self.b * c

a = TestClass(10, 10)
print(a.class_method(10))


texts:
It's my implementation.  Can I get some opinions on it?

import random
import os
import time

class Game:

 def __init__(self, turns, w, h):
    self.board = []

    for x in range(0, h):
        self.board.append([])
        for y in range(0, w):
            self.board[x].append(random.random())

    self.turns = turns

 def next_gen(self):
    self.board_next = []

    for x in range(0, len(self.board)):
        self.board_next.append([])

    for x in range(0, len(self.board)):
        for y in range(0, len(self.board[x])):
            n = 0

            for dx in range(-1, 2):
                for dy in range(-1, 2):
                    if (dx == 0 and dy == 0):
                        pass
                    else:
                        try:
                            if (x + dx >= 0 and y + dy >= 0):
                                if (self.board[x + dx][y + dy]):
                                    n += 1
                        except IndexError:
                            pass

            c = self.board[x][y]

            if (n == 1 or n == 0):
                c = 0
            elif (n == 3):
                c = 1
            elif (n == 2):
                pass
            else:
                c = 0

            self.board_next[x].append(c)

    self.board = self.board_next[:]

 def show(self):
    for x in range(0, len(self.board)):
        l = ""
        for y in range(0, len(self.board[x])):
            if (self.board[x][y]):
                l += "X"
            else:
                l += "#"
        print(l)
    time.sleep(0.5)

 def start(self):
    for x in range(0, self.turns):
        print("\n+Gen {0}".format(x + 1))
        self.show()
        if (x + 1 != self.turns):
            os.system('clear')
        self.next_gen()

os.system('clear')
game = Game(3, 3, 3)
game.board = [
      [0, 0, 0],
      [1, 1, 1],
      [0, 0, 0]]
game.start()

And output:

+Gen 1
###
XXX
###

+Gen 2
#X#
#X#
#X#

+Gen 3
###
XXX
###


texts:
How would you merge these two functions into a single more generic function?

// concatStringsFromObject :: Object, Array, String -> Strings
const concatStringsFromObject = (o = {}, a = [], j = ' ') => {
    return a.filter( x => o.hasOwnProperty(x) )
            .map( x => o[x] )
            .join(j);
};

// concatStringsFromArrayOfObject :: Array, String, String -> Strings
const concatStringsFromArrayOfObject = (a = [], s = '', j = ', ') => {
    return a.filter( x => x.hasOwnProperty(s) )
            .map( x => x[s] )
            .join(j);
};


texts: Which of these two paren-matching functions is better?

texts:
I am currently trying to learn Haskell (after taking a Scala course on Coursera); but while I can write functions that do what I want, I worry that I am not learning to write idomatic/clean/performant code. I am hoping that this is an acceptable place to receive feedback on how I am progressing. Please let me know if my examples are too small/'toy'/not appropriate for this area of the site.

Which of these two parenthesis matching functions is better - or how best should it be written? The function takes a String, and returns True if the parentheses are balanced, otherwise False.

"(hello)()" = True
")(test()" = False
"())" = False

Explicitly written:

balance :: String -> Bool
balance xs = bal 0 xs == 0
  where bal c [] = c
        bal c (x:xs)
          | c < 0     = c
          | x == '('  = bal (c + 1) xs
          | x == ')'  = bal (c - 1) xs
          | otherwise = bal c xs

Using foldl:

balance' :: String -> Bool
balance' xs = foldl bal 0 xs == 0
  where bal count char
          | count < 0   = count
          | char == '(' = count + 1
          | char == ')' = count - 1
          | otherwise   = count

I think that the explicitly-recursing one is better since it will terminate early if it detects the String is flawed, but the other one might be 'clearer' since it uses foldl. Both of them happen to be tail-recursive. How would I improve either?

How important is writing tail-recursive functions in Haskell? I have read somewhere that Haskell is very smart about making things tail recursive, but I do not understand enough to understand quite how.

Any help and suggestions would be greatly appreciated, thank you!


texts:
I've written my own implementation of strcat in C.

char* my_strcat(char *str1, char *str2)
{
   int len_str1 = 0, len_str2 = 0, len_str3;

   for (int i = 0; str1[i] !='\0'; i++)
   {
      len_str1++;
   }

   for (int i = 0; str2[i] != '\0'; i++)
   {
      len_str2++;
   }

   len_str3 = len_str1 + len_str2;
   char* str3 = malloc(len_str3*sizeof(char));

   for (int i = 0; i < len_str1; i++)
   {
      *(str3+i) = *(str1+i);
   }

   for (int i = 0; i < len_str2; i++)
   {
      *(str3+i+len_str1) = *(str2+i);
   }

   return str3;
}

I'm looking for anything that could be improved: readability, efficiency, code cleanup, bugs, ...


texts:
I'm trying to respect the Ruby principle of keeping my code dry; however, in my conditional, I have different constants set to different days. But that's the only thing different. They're pretty much the same code minus the evaluation of days from_now.

if term_type == TERM_MONTH
  subscription.suspended_at && subscription.suspended_at < MONTHLY_WARNING_1.from_now && suspended_email_1_sent_at.nil? && subscription.suspended_at >= Date.today && is_system == true && paid_at.nil?
else
  subscription.suspended_at && subscription.suspended_at < ANNUAL_WARNING_1.from_now && suspended_email_1_sent_at.nil? && subscription.suspended_at >= Date.today && is_system == true && paid_at.nil?
end

I tried using the ternary operator; however, it didn't produce the results I was expecting as it was only setting the days based on term_type yet not sending the mail based on it.

days = term_type == TERM_MONTH ? MONTHLY_WARNING_1 : ANNUAL_WARNING_1
subscription.suspended_at && subscription.suspended_at < days.from_now && suspended_email_1_sent_at.nil? && subscription.suspended_at >= Date.today && is_system == true && paid_at.nil?

Should I stick with the if block?


texts:
Please, review my implementation of the F# pipeline operator in Scala

class PipelineContainer[F](value: F) {
  def |>[G] (f: F => G) = f(value)
}

implicit def pipelineEnrichment[T](xs: T) = new PipelineContainer(xs)

  test("Find the last but one element in the list") {
    // example: penultimate(List(1,2,3,3,4,5))
    // result: 4

    def reverse[T](list: List[T]) = list.reverse

    def head[T](list: List[T]) = list.head

    def tail[T](list: List[T]) = list.tail

    def lastButOne[T](list: List[T]) = list |> reverse |> tail |> head
  }


texts: Extension method to return a default value for any null value

texts:
I'm creating an extension method that can be used on any type.  The idea is that if this method is called, it checks if value is null.  If null, it needs to return a default instance of the specified type.

public static dynamic CreateDefaultIfNull<T>(this object item)
    {
        if(item == null)
        {
            var type = typeof(T);

            if(type.IsArray)
            {
                return Array.CreateInstance(type.GetElementType(), 0);
            }

            if(type.GetConstructor(Type.EmptyTypes) == null)
            {
                var paramCount =  type.GetConstructors().First().GetParameters().Count();

                var paramNullList = new List<object>();

                for(int i = 0; i < paramCount; i++)
                {
                    paramNullList.Add(null);
                }

                return Activator.CreateInstance(type, paramNullList.ToArray());
            }

            return Activator.CreateInstance(type);
        }

        return (T)item;
    }

I'm looking for a review of my code, and any pitfalls that I may encounter or may have missed.

The idea is that this method should be used anytime that a null value cannot be used and a default must be returned.

I'm not worried about null values being passed into parameterized constructors, as this is doing.  The constructor of those objects should be handling if null values are passed into their constructors.

EDIT: Based on the information provided, I've updated my code.  The current version is below:

public static dynamic CreateDefaultIfNull<T>(this T item)
    {
        if (item != null)
            return item;

        var type = typeof(T);

        if (type.IsArray)
        {
            return Array.CreateInstance(type.GetElementType(), 0);
        }

        if (type.GetConstructor(Type.EmptyTypes) == null)
        {
            var paramCount = type.GetConstructors().Min(construct => construct.GetParameters().Count());
            var constructorToUse = type.GetConstructors().Where(construct => construct.GetParameters().Count() == paramCount).First();

            var paramNullList = new object[paramCount];

            var parameters = constructorToUse.GetParameters();
            for (int i = 0; i < paramCount; i++)
            {
                paramNullList[i] = parameters[i].ParameterType.IsValueType ? Activator.CreateInstance(parameters[i].ParameterType) : null;
            }

            return Activator.CreateInstance(type, paramNullList);
        }

        return Activator.CreateInstance(type);
    }


texts:
I am new to programming, and I wanted to ask, is my code inefficient / poorly written?

Here is my code below for an exercise I just did. The point is for the user to guess the number 0, but it also:

Calculates the average number
Calculates the number of attempts
Gives the sum of attempts

Are there ways of improving this code? If so, how do you know where to look? Am I overusing if/while statements?

#User must guess a number: until they reach value of 0
#Must calculate average sum of guesses, track sum of numbers entered, keep count of attempts

guess = ''
count = 0
total_sum = 0

while guess != 0:
    print("Guess the number: ")
    guess = int(input())

#Count no. of attempts
    count += 1

#Total Sum of guesses
    total_sum += guess

    if guess == 0:
        print("Congratulations!, you guessed the correct number")

    #Average number of guesses
        try:
            average = (total_sum / (count - 1))
            print("Average number:", average)
        except ZeroDivisionError:
            print("No average")

    print("Attempts: ", count)
    print("Total sum of guesses: ", total_sum)


texts:
I wrote this function which does the following from scratch w/o looking for ways that it is typically done:

Accepts a char c to search for.
Accepts a char* str to search within.
Accepts a buffer pointer, and stores all indices of c that are in str inside the provided buffer.
Returns the # of times that c was found in str.

Please critique and also - Are there better alternatives to export the indices other than using a buffer ptr?

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int str_contains(const char c, const char* str, int* output_buffer){
    int i, str_len;
    str_len = strlen(str);
    int *holder = malloc(str_len*sizeof(int));
    int holder_iteration = 0;
    for(i = 0; i < str_len; i++){
        if(str[i] == c){
            holder[holder_iteration++] = i;
        }
    }
    memcpy(output_buffer,holder,holder_iteration*sizeof(int));
    free(holder);
    return holder_iteration;
}

int main(){
    char* myString = "Welcome to the jungle, baby. Do you like to juggle or jump around?";
    int* output = malloc(500*sizeof(int));
    int number = str_contains('a',myString,output);

    printf("# of times: %d\nIndices: \n",number);
    int i;
    for(i = 0; i < number; i++){
        printf("%d\n",output[i]);
}

free(output);
    return(EXIT_SUCCESS);
}


texts:
So, I have decided to make a little "guessing game" where the user tries to decode what the encoded piece of text prompted. I'm sure it works. However, I know that there are places where I can improve. I am open to any constructive criticism about this. This program was done in HTML + JavaScript.

<!DOCTYPE HTML>

  <META CHARSET="UTF-8" />
  <TITLE>Decryption Guessing Game</TITLE>

Text:

  <form name="game" action="#" onsubmit="return validateForm()">
    Decrypt: <input type="text" name="text">
    <input type="submit" value="Check!">
  </form>


texts: Pretty way of keeping sensitive info out of a logged command string in Ruby?

texts:
I have a long command that I am building with shovels (<<), with the intention of eventually running system(command). I'd like to log the command string, to make sure it is built properly, right before I execute the command. However, the command has to contain account credentials that I don't want to log. I'm looking for an elegant way to satisfy both requirements (1. log the meat of the command string, 2. don't log the auth credentials it contains).

This is what I have now:

command = ""
public = ""

[command, public].each {|str| str << "command_name"}
[command, public].each {|str| str << " -a a"}
[command, public].each {|str| str << " -b b"}
[command, public].each {|str| str << " -c c"}
command << " -d d"
command << " -e e"
[command, public].each {|str| str << " -f f"}
command << " -g g"
[command, public].each {|str| str << " -h h"}
[command, public].each {|str| str << " -i i"}

puts command
=> command_name -a a -b b -c c -d d -e e -f f -g g -h h -i i
puts public
=> command_name -a a -b b -c c -f f -h h -i i

system(command)

Original question from Stack Overflow


texts:
I wrote some JS to power an HTML/CSS "set theory" clock, and I'd like to share what I have so far and ask if anyone can suggest improvements.

Specifically, I'm wondering:

Should I bother checking to see if a variable is greater than zero before running the for loop?
Is there a better way to handle togging the classes? Setting all elements to "off" and then turning "on" the correct lamps seems a little heavy handed.
Should the tick() function be broken up?

For added context, you can view the code in context on GitHub and here is a live demo.

$(document).ready(function () {
    startClock();
});

function startClock() {
    'use strict';
    var delay = 1000;

    function tick() {
        var clockDate = new Date(),
            clockHours = clockDate.getHours(),
            clockMinutes = clockDate.getMinutes(),
            clockSeconds = clockDate.getSeconds(),
            fiveHours = Math.floor(clockHours / 5),
            fiveMinutes = Math.floor(clockMinutes / 5),
            singleHours = Math.floor(clockHours - (fiveHours * 5)),
            singleMinutes = Math.floor(clockMinutes - (fiveMinutes * 5));

        $(".circle").toggleClass("off");
        $("#display").text(clockHours + ":" + ((clockMinutes < 10) ? "0" + clockMinutes : clockMinutes) + ":" + ((clockSeconds < 10) ? "0" + clockSeconds : clockSeconds));

        $("[id^=h]").addClass("off");
        $("[id^=m]").addClass("off");

        // First row of lamps
        if (fiveHours > 0) {
            for (var i = 1; i <= fiveHours; i++) {
                $("#h5-" + i).removeClass("off");
            }
        }

        // Second row of lamps
        if (singleHours > 0) {
            for (var i = 1; i <= singleHours; i++) {
                $("#h1-" + i).removeClass("off");
            }
        }

        // Third row of lamps
        if (fiveMinutes > 0) {
            for (var i = 1; i <= fiveMinutes; i++) {
                if (i % 3 == 0) {
                    $("#m5-" + i).removeClass("off");
                } else {
                    $("#m5-" + i).removeClass("off");
                }
            }
        }

        // Fourth row of lamps
        if (singleMinutes > 0) {
            for (var i = 1; i <= singleMinutes; i++) {
                $("#m1-" + i).removeClass("off");
            }
        }

        setTimeout(tick, delay);
    }

    tick();
}


texts:
Please review my implementation of Fermat's Factorization.

fermat :: Int -> Maybe (Int, Int)
fermat n = odd' n >> (go $ ceiling $ sqrt (fromIntegral n))
   where go a = case (try n a) of j @ (Just _) -> j
                                  Nothing      -> go (a + 1)

odd' :: Int -> Maybe Int
odd' x = if (odd x) then Just x else Nothing

try :: Int -> Int -> Maybe (Int, Int)
try n a = fmap (\b -> ((a + b), (a - b))) result
  where result = get_perfect_sq (a^2 - n)

get_perfect_sq :: Int -> Maybe Int
get_perfect_sq x = if (sq * sq == x) then Just sq else Nothing
  where sq = floor $ sqrt (fromIntegral x :: Float)

examples

ghci> fermat 5995
Just (109,55)

-- prime per http://www.bigprimes.net/cruncher/1300633/
ghci> fermat 1300633
Just (1300633,1)


texts:
I'm currently writing a small asset tracking system.

The implementation should meet the following requirements:

  The system; scans the transfers every 15 minutes. If the transfer is
  accepted by the receiver by the specified transfer time, realizes the
  transfer. When a transfer is realized, assets are assigned to the
  receiver as of transfer time; if the transfer is permanent, actual
  owner is changed also.

  The system; If the transfer operation is not accepted by the receiver
  by the specified transfer time; cancels the transfer.

Above requirement is dependent on this straight-forward requirement (UI related parts omitted):

  Transferring user; When a new transfer is started,
  [...]
  and specifies

  the time when the transfer will be realized
  whether the transfer is temporary or permanent
  assets to be transferred
  the receiver
  [... and saves ....]

The implementation:

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class TransferServiceImpl implements TransferService {

    private Repository<Transfer, Long> repository;
    private Repository<Asset, Long> assetRepository;

    @Override
    public void informTransferTimeIsUp(long transferId) {
        Transfer transfer = repository.get(transferId);
        transfer.informTransferTimeIsUp();

        if (transfer.isRealized()) {
            Set<Asset> transferredAssets = assetRepository.getAll(transfer.getTransferredAssets());
            for (Asset asset : transferredAssets) {
                if (TransferType.TEMPORARY.equals(transfer.getTransferType())) {
                    asset.transferTemporarily(transfer.getReceiver());
                } else {
                    asset.transferPermanently(transfer.getReceiver());
                }
                assetRepository.update(asset);
            }
        }

        repository.update(transfer);
    }

}

class Transfer {
    long receiver;
    Date transferTime;
    TransferType transferType;
    Set<Long> transferredAssets = new HashSet<Long>();

    boolean accepted;
    boolean timeIsUp;
    boolean realized;
    boolean cancelled;

    public void informTransferTimeIsUp() {
        this.timeIsUp = true;

        if (accepted) {
            this.realized = true;
        } else {
            this.cancelled = true;
        }
    }

    public long getReceiver() {
        return this.receiver;
    }

    public Set<Long> getTransferredAssets() {
        return Collections.unmodifiableSet(transferredAssets);
    }

    public TransferType getTransferType() {
        return transferType;
    }

    public boolean isRealized() {
        return realized;
    }

}

class Asset {
    Long actualOwnerId;
    Long currentOwnerId;

    boolean blocked;

    public void transferTemporarily(long receiverId) {
        this.currentOwnerId = receiverId;
        this.unblockIfBlocked();
    }

    public void transferPermanently(long receiverId) {
        this.actualOwnerId = receiverId;
        this.currentOwnerId = receiverId;
        this.unblockIfBlocked();
    }

    private void unblockIfBlocked() {
        this.blocked = false;
    }

}

Dependencies to get the above code to compile:

interface TransferService {
    void informTransferTimeIsUp(long transferId);
}

interface Repository<TEntity, TKey> {

    TEntity get(TKey key);

    Set<TEntity> getAll(Set<TKey> keys);

    void update(TEntity asset);

}

enum TransferType {TEMPORARY, PERMANENT}

Is there too much business logic in the service layer?


texts: c++17 compatible std::bind_front alternative

texts:
One of the things that has been really exciting me in c++20 is std::bind_front. Using placeholders with std::bind and boost::bind has really bothered me and the code looked messier and messier with each call to bind. It was bad enough for me to decide to enable -std=c++2a and pray that I wouldn't have to fix the code in the future if something gets changed.

I was messing around with parameter pack recursion when I realized I could make a std::bind_front alternative that would work in c++17. If I removed the std::invoke it would even work in c++11.

It even seems to compile faster than my standard library's implementation.

//#include <utility>
//#include <functional>

//of course this would go into some kind of namespace

template <class F, class A>
struct _bind_obj {
    F originalFunc;
    A arg;
    template <class... Args>
    inline auto operator()(Args&&... a){
        return std::invoke(originalFunc, arg, std::forward<Args>(a)...);
    }
    _bind_obj(F &&_originalFunc, A &&_arg) :
        originalFunc(std::forward<F>(_originalFunc)),
        arg(std::forward<A>(_arg)){

    }
};

template <class F, class A>
auto bind_front(F &&func, A &&arg){
    return _bind_obj<F, A>(
        std::forward<F>(func),
        std::forward<A>(arg)
    );
}

template <class F, class FirstA, class... A>
auto bind_front(F &&func, FirstA &&firstA, A&&... a){
    return bind_front(
        bind_front(
            std::forward<F>(func),
            std::forward<FirstA>(firstA)
        ),
        std::forward<A>(a)...
    );
}

So what do you think? Are there some cases in std::bind_front that I missed? Are there any optimizations I should make?


texts:
I would like to show an XML tree as a tree using GraphViz Dot tool. Then I must convert it to a DOT file.

It is what I have tried

    string dot = "digraph G {" + Environment.NewLine;
    XML2DOT(XmlRoot, "r");
    dot += Environment.NewLine + "}";
    ....
    private void XML2DOT(XmlNode n, string id)
    {
        if (n == null)
            return;
        string NodeName = n.Name.Replace("-", "_");
        if (n.HasChildNodes)
        {
            dot += Environment.NewLine + NodeName
                + id + "[label=\"" + NodeName + "\"];";
        }
        else
        {
            dot += Environment.NewLine
                + "leaf" + id + "[label=\"" + n.InnerText + "\"];";
        }
        int i = 0;
        foreach (XmlNode item in n.ChildNodes)
        {
            string cid = id + i;
            dot += Environment.NewLine + NodeName + id + " -> "
            + (item.HasChildNodes ? item.Name.Replace("-", "_") : "leaf")
            + cid + ";";
            XML2DOT(item, cid);
            i++;
        }
   }

The input xml is:

<?xml version="1.0" encoding="UTF-8"?>
<S>
<MN clitic="empty" ne_sort="pers">
   <PUNC clitic="empty">
      <w clitic="empty" gc="Ox" lc="Ox" lemma="#">#</w>
   </PUNC>
   <MN clitic="empty" ne_sort="pers">
      <N clitic="ezafe">
         <w clitic="ezafe" gc="Apsz ; Nasp--- ; Nasp--z ; Ncsp--z" lc="Nasp--z" lemma="مسعود" n_type="prop" ne_sort="pers">مسعود</w>
      </N>
      <N clitic="ezafe">
         <w clitic="ezafe" gc="Apsy ; Nasp--- ; Nasp--z ; Ncsp--y" lc="Nasp--z" lemma="شجاعی" n_type="prop" ne_sort="pers">شجاعی</w>
      </N>
      <N clitic="empty">
         <w clitic="empty" gc="Nasp--- ; Nasp--z" lc="Nasp---" lemma="طباطبایی" n_type="prop" ne_sort="pers">طباطبایی</w>
      </N>
   </MN>
   <PUNC clitic="empty">
      <w clitic="empty" gc="Ox" lc="Ox" lemma="#">#</w>
   </PUNC>
</MN>
</S>

And it is what I get:

It works as expected, just would like to know a more general and efficient way to do that.


texts:
I decided to try making some simple clones of the various user-space Unix utilities in an effort to learn the system-specific headers and improve my C skills. The code that follows is a clone of sleep and I'm curious as to whether there are any pitfalls I'm overlooking (including security vulnerabilities). It compiles and seems to behave fine so there's no issue there.

The program attempts to comply with the Open Group spec for sleep.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_TIME_DIGITS (11)

int main(int argc, char *argv[]) {
    if(argc != 2) {
        fprintf(stderr, "sleep: too %s operands\n",
                argc < 2 ? "few" : "many");
        return 1;
    }

    if(strnlen(argv[1], MAX_TIME_DIGITS + 1) > MAX_TIME_DIGITS) {
        fprintf(stderr, "sleep: operand too long\n");
        return 1;
    }

    int i = 0;
    while(argv[1][i] && i < MAX_TIME_DIGITS) {
        if(!isdigit((int)argv[1][i])) {
            fprintf(stderr, "sleep: invalid operand\n");
            return 1;
        }
        ++i;
    }

    unsigned long int time = strtoul(argv[1], NULL, 10);
    sleep(time);
    return 0;
}


texts:
This is a TalentBuddy Challenge

  Your task is to
  write a function that prints to the standard output (stdout) the highest number of tweets recorded between each second in the array and the past windowSize seconds before it

  Note that your function will receive the following arguments:

  TweetsPerSecond
  which is an array of integers representing the number of tweets recorded every second

  WindowSize
  which is the integer number mentioned above

I've ran my code on talentbuddy, and I think their back-end is broken, because it says my test case fails from missing data (far down the line), and when I run the test on my machine with the same inputs it prints out the right amount and correct data, in 30-80 Milliseconds. SO IT WORKS.

I am looking for a general review of my code and practices. Keep in mind that efficiency is key here.

I've added useful comments to document the flow of the program (even though they make it look ugly)

class Node
{
    public Node Next;
    public int Value;
}

public static void TweetsPerSecond(int[] tweetsPerSecond, int windowSize)
{
    Node head  = null; // Front of the window (where values fall out)
    Node max   = null; // Node with max value in the window
    Node check = null; // Starting node of list of Nodes to be checked against the max
    Node back  = null; // End of the window (where new values are put in)

    int count = 0; // Count of numbers in the window
    string[] maxes = new string[tweetsPerSecond.Length]; // Max values to be printed to the console.
    for (int i = 0; i < tweetsPerSecond.Length; i++)
    {
        // If this is our very first number being added, create new head node
        // Else append a new node to the back of the list, and set it to be the next checked node against the max
        if (head == null) max = back = head = new Node() { Value = tweetsPerSecond[i] };
        else check = back = back.Next = new Node() { Value = tweetsPerSecond[i] };

        // If we have filled up the window with values
        if (count + 1 > windowSize)
        {
            // If the maximum value is falling out of the window
            if (head == max)
            {
                // Maximum value is defaultly set to the first value in the window
                max = head.Next;
                // And we set the next nodes to be tested against this new max to be all nodes in the window after the max
                check = max.Next;
            }
            head = head.Next;
        }
        else count++;

        // Start our checking with the set CHECK node, which is typically just the most recently added node, unless our max fell out of the window
        Node next = check;
        while (next != null)
        {
            // If this node being checked is higher than our highest found value, then set this node to be the highest (MAX), and check the next.
            if (next.Value > max.Value) max = next;
            next = next.Next;
        }

        // Store our found max node in an array.
        maxes[i] = max.Value.ToString();
    }
    File.WriteAllLines("out.txt", maxes);
    //Console.WriteLine(string.Join(Environment.NewLine, maxes));
}


texts:
I have a class 'M249' it is initiated with 'ammo'
The class has one responsibility(I hope) to expend ammo.
Does there exist a way to increment without accessor or writer?

I am shaky on when I should be using mixins, or inheritance. I think module is best here?

module MG_tools
  Rof = {:sustained => rand(3..9), :rapid => rand(5..9), :cyclic =>
rand(1..200), :cease => 0}
end

class M249
include MG_tools
  attr_accessor :ammo
  def initialize( ammo )
    @ammo = ammo
  end

  def fire(command)
    self.ammo -= Rof[command]
    raise ArgumentError.new("Out of Ammo!") if self.ammo < 1
  end
end
command = :sustained
gunner = M249.new(200)

loop do
case gunner::ammo
  when (200..1000)
   command = :cyclic
  when (100..199)
   command = :rapid
  when (6..99)
   command = :sustained
  when (1..5)
   command = :cease
end
    puts "#{command.upcase} FIRE"
    break if command == :cease
    gunner.fire(command)
    puts "*MACHINE GUN NOISES*"
    puts "SAW: #{gunner::ammo} rounds left!"

end


texts:
As I'm learning Ruby I wrote this little program to generate a "nice" number randomly (like 4747, 6969, etc.).
As I'm currently breaking the "do not repeat yourself" rule, how would you refactor the following?

def nice_numbers
    a = rand(9)
    b = rand(9)
    c = rand(9)
    d = rand(9)
    while a != c || b != d
        a = rand(9)
        b = rand(9)
        c = rand(9)
        d = rand(9)
    end
    nice = [a,b,c,d].join
end

puts nice_numbers


texts: Expose only desired functions to 3rd party plugins in JavaScript

texts:
I tried to build a solution to dynamically load JS code, but to only expose predefined functions. Is this the correct approach? Is there any Method to execute arbitrary code if I put all my code inside of (function($$) { ... }).call({}, $$) statements?

// scope.js
// $$ holds all global variables, and is not accessible
// inside an plugin (unless there is a helper method in the API, which exposes the variable)

$$ = {};

    // (function($$) { ... }).call({}, $$) is used to set this to an empty object.
    // This prevents getting values from this, which should be in another scope
    // "use strict"; is used to prevent the creation of global variables

    // initialize the global variables
    (function($$) {
        "use strict";

        // read-only property
        $$.DEBUG = {
                get: function() {
                    return true;
                }
            };
            Object.defineProperty($$, 'DEBUG', $$.DEBUG);

        // execute the plugin code
        $$.exec = function (code) {
                return (function($$) {
                    /**/
                    // get the exposed API Methods
                    var API = new $$.API(),
                    $$ = {}; // Hide the global $$ object

                // prepare code for execution
                code = code.trim();
                if (code[code.length - 1] !== ';') {
                    code += ';';
                }
                var _code = "(function() { var document = {}, window = {}; " + code + " return this; }).call({})";

                // call with eval
                try {
                    // everything set with this will be returned after the eval
                    return eval(_code);
                } catch(e) {
                    console.error(e);
                }
                /**/
            }).call({}, $$);
            };
        }).call({}, $$);

    // $$.API() returns an object, which holds all exposed API methods
    // because $$.API() is an class, every plugin gets an local API oject.
    // If the elements of this object are overwritten, it does not interfere with other API objects
    (function($$) {
            $$.API = function() {
            // Default API values
            this.ApiVar = 3;

            // Expose global variables to the API
            this.setGlobalVar = function(value) {
                $$.globalVar = value;
                };
                this.getGlobalVar = function() {
                    return $$.globalVar;
                };
                return this;
            };
        }).call({}, $$);

    // setting a global variable
    "use strict";
    $$.globalVar = 15;

Usage ($$.globalVar inside the exec should return undefined):

// load the scopes
require('./scope.js');

"use strict";
(function($$) {
     /**/
     // restricted execution of code (only API is accessible)
     var ret = $$.exec("this.test = 'test' + ' API.ApiVar: ' + API.ApiVar + '\\n' + '$$.globalVar: ' + $$.globalVar + '\\n' + 'API.getGlobalVar(): ' + API.getGlobalVar(); API.setGlobalVar('test'); API.ApiVar = 16;");
     console.log(ret.test);
     console.log();
     // API Values are only changed locally
     console.log('API.ApiVar: ' + $$.API().ApiVar);
     // normal usage of $$ variables
     console.log('$$.globalVar: ' + $$.globalVar);
     /**/
    }).call({}, $$);

I used Node.js for testing but it shouldn't matter where it runs.

We are developing a desktop application, which uses HTML and JS as frontend. So it's almost a browser.

The wrapping with (function($$) { ... }).call({}, $$) is to get our code in its own local scope. that way, we can not expose function, which shouldn't be outside of the file they were used. ($$ is used to expose functions for our code)

The functions which are usable for 3rd party developers, are exposed through API(). So every "Plugin" (if you like to call it that) has its own local copy of API functions and cannot mess with global objects.


texts: Private contexts and their parents in CoreData

texts:
I find myself following this pattern a lot in my core data code, which works, but I'm wondering if it is needed...

let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateContext.parent = mainThreadContext

/// Do some stuff on the private context

privateContext.save()
/// Save parent on parent's queue
if let parent = privateContext.parent {
 parent.performAndWait{
  do {
   try parent.save()
  } catch {}
 }
}

I know that saving the private context after I make changes to it is needed, but I'm wondering if I have to explicitly save the parent context back on it's own queue.

I've been profiling my app and I was spending a lot of extra time doing uneeded saves other places, so I'm trying to trim the coredata code as much as possible.


texts: Efficiency of looping though a text map to draw objects

texts:
I am making a game that uses a text map to draw obstacles and courses for the player to navigate. However, I am concerned that my method of looping through the text map to draw objects on the screen isn't as efficient as it could be.

View the playable project on Khan Academy.

Here is my code dealing with the text map:

var platforms = [];
platforms.add = function(xPosition, yPosition, width, height, colour) {
    platforms.push( new Block(xPosition, yPosition, width, height, colour) );
};

platforms.display = function() {
    for (var i = 0; i < platforms.length; i++) {
        platforms[i].display();
    }
};
var levelOne = [
    // each symbol is equivalent to 40 pixels
    ["##########"], // # - block
    ["#        #"], // S - starting position
    ["#        #"],
    ["#        #"],
    ["#        #"],
    ["#  #     #"],
    ["#       ##"],
    ["#     #  #"],
    ["#S  #    #"],
    ["##########"],
];
var symbol;
var playerX;
var playerY;
for(var i = 0; i < levelOne.length; i++) {

    for(var j = 0; j < levelOne[i].length; j++) {
        for(var v = 0; v < levelOne[i][j].length; v++) {
            var symbol = levelOne[i][j][v];
            if(symbol === "#") {
            // Platform arguments: X, Y, Width, Height, Color
                platforms.add(v*width/10, i*height/10, width/10, height/10, color(0, 174, 255));
            } else if (symbol === "S") {
                playerX = v*width/10;
                playerY = i*height/10;
            }
        }
    }
}

How can I make this code more efficient?


texts: Get Elapsed Time as Human Friendly String

texts:
In lieu with several other Facebook-esque concepts I am trying to replicate, this working code will take the span of time from a given date to now, and try to convert it into the most convenient English-friendly word. For example, if I post a comment on an article or status, and I want to show when it was posted to a user who views it, it would indicate something like "5 minutes ago", versus a date itself.

Concerns: Does this cover all possible use cases? Is it done optimally in the least lines of code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Schloss.Text
{
    public static class Date
    {
        public static string GetElapsedTime(DateTimeOffset datetime)
        {
            TimeSpan ts = DateTimeOffset.Now.Subtract(datetime);

            int years = ts.Days / 365;
            int months = ts.Days / 30;
            int weeks = ts.Days / 52;

            if (years == 1) // one year ago
                return "A year ago";

            if (years > 1) // greater than one year
            {
                if (ts.Days % 365 == 0) // even year
                    return (int)(ts.TotalDays / 365) + " years ago";
                else // not really entire years
                    return "About " + (int)(ts.TotalDays / 365) + " years ago";
            }

            if (months == 1) // one month
                return "About a month ago";

            if (months > 1) // more than one month
                return "About " + months + " months ago";

            if (weeks == 1) // a week ago
                return "About a week ago";

            if (weeks > 1) // more than a week ago, but less than a month ago
                return "About " + weeks + " weeks ago";

            if (ts.Days == 1) // one day ago
                return "Yesterday";

            if (ts.Days > 1) //  more than one day ago, but less than one week ago
                return ts.Days + " days ago";

            if (ts.Hours == 1) // An hour ago
                return "About an hour ago";

            if (ts.Hours > 1 && ts.Hours <= 24) // More than an hour ago, but less than a day ago
                return "About " + ts.Hours + " hours ago";

            if (ts.Minutes == 1)
                return "About a minute ago";

            if (ts.Minutes == 0)
                return ts.Seconds + " seconds ago";

            return ts.Minutes + " minutes ago";
        }
    }
}


texts:
I've just taken the leap over to RTK instead of 'vanilla' redux and am blown away by how much less code I need to write. I'm not entirely sure how to structure my slices, however, and figured I'd ask for a small code review so I do not accidentally start breaking conventions from the start. This is how one of my slices is currently looking:
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import bundle from '../../bundler';
import {BundleStartAction, BundleCompleteAction, BundlesState } from './bundleSliceInterface.ts'

export const createBundle = createAsyncThunk(
  'bundle',
  async (data: { cellId: string; input: string }, thunkAPI) => {
    const { cellId, input } = data;

    thunkAPI.dispatch(bundleStart({ cellId }));
    const result = await bundle(input);
    thunkAPI.dispatch(
      bundleComplete({ cellId, bundle: { code: result.code, err: result.err } })
    );
  }
);

const initialState: BundlesState = {};
const bundleSlice = createSlice({
  name: 'bundle',
  initialState,
  reducers: {
    bundleStart: (state, action: PayloadAction<BundleStartAction>) => {
      state[action.payload.cellId] = { loading: true, code: '', err: '' };
    },
    bundleComplete: (state, action: PayloadAction<BundleCompleteAction>) => {
      state[action.payload.cellId] = {
        loading: false,
        code: action.payload.bundle.code,
        err: action.payload.bundle.err,
      };
    },
  },
  extraReducers: {},
});

export const { bundleStart, bundleComplete } = bundleSlice.actions;
export default bundleSlice.reducer;

Any feedback or tips on how to structure slices properly is greatly appreciated.
Thanks in advance!


texts: Readability of array_* vs foreach in PHP for filtering and extracting

texts:
With functional programming all the rage, I feel I should be using PHP's array_* functions more.  But when I compare these two identical implementations, I can't help but think foreach is more readable.  Am I just being a dinosaur?

(The foreach implementation takes 1/4 the time, but performance is not of interest for me here, now).

Which do you like better and why?

// Create $attendeeNames from $allPeople who are in the $selectedPeople array
foreach ($allPeople as $person) {
    $id = $person['id'];
    $name = $person['name'];
    if (in_array($id, $selectedPeople)) {
        $attendeeNames[] = $name;
    }
}

// Same, but with array functions
$attendees = array_filter($allPeople,
    function($item) use ($selectedPeople) {
        $id = $item['id'];
        return in_array($id, $selectedPeople);
    });

$attendeeNames = array_map(
    function($attendee) {
        return $attendee['name'];
    }, $attendees);


texts:
My first attempt at a user registration code.

Login.php defines database log in variables (e.g. Database name, Table name, etc)
Header.php connects to the database.

I used ctype_alum for security of inputs. I also know that I shouldn't use mysql_error() for security issues but I've used the function as a placeholder.

Would love some feedback on possible improvements:

<?php
    require_once 'login.php';
    include 'header.php';

    echo <<<_REGFORM
    <form action="registration.php" method ="post">

    Register an account:
    Usernames and passwords must be at least 6 letters in length comprising of only alphanumeric characters.

    Username          <input type="text" name="regusername"/>
    Password          <input type="password" name="regpassword"/>
    Retype Password   <input type="password" name ="checkregpassword"/>
               <input type="submit" value="Register"/>
               <input type="hidden" name="clicked" value=yes/>

</form>
    _REGFORM;

    if ($_POST['clicked']){
        if ($_POST['regusername'] && $_POST['regpassword']){
            if (ctype_alnum($_POST['regpassword']) && ctype_alnum($_POST['regusername']) && (strlen($_POST['regusername']) > 5) && (strlen($_POST['regpassword']) > 5)){
                if ($_POST['regpassword'] === $_POST['checkregpassword']) {
                    // Insert code to check if the username exists
                    // Insert code to finally create the account!

                    $username = $_POST['regusername'];
                    $password = md5($_POST['regpassword']);

                    mysql_select_db($db_database) or die("Unable to select database: ".mysql_error());

                    $query = "SELECT * FROM userlogin WHERE username='$username'";
                    $result = mysql_query($query) or die("Database access failed: ".mysql_error);

                    if (!mysql_num_rows($result)) {
                        $query = "INSERT INTO userlogin VALUES('','$username','$password')";
                        $result = mysql_query($query) or die("Unable to create account: ".mysql_error());

                        echo "Thanks ".$username.", your account has been created!";
                    }
                    else echo"Username Unavailable, please try another username";

                }
                else echo "Your passwords do not match";
            }

            else echo "Username and password must be atleast 6 letters in length and letters a-z, A-Z and numbers 0-9 are accepted
";
        }
        else echo "Please fill in a valid username and password";
    }

    ?>


texts: CSS Optimization? How can I clean my code

texts:
My CSS feels dirty and I have no idea how to improve it.

Suggestions are greatly appreciated!

html, body { border:0; margin:0; padding:0; }
body { font: normal 12px helvetica,sans-serif; }
.header {
    background-color:#242424;
    height:40px; }
.header h1, h2 { text-transform:uppercase; }
.header h1 {
    color:#FFF;
    display:inline;
    font-size:12px; }
.header h2 {
    color:#B4B4B4;
    display:inline;
    font-size:12px; }
.header #title, .sub #nav, #content {
    margin:0 auto;
    width:797px; }
.header #title {
    padding-top:12px; }
.header #version {
    color:#FFF;
    float:right;
    font-size:10px;
    margin:-13px 10px 0 0; }
.sub {
    background-color:#E4F2FD;
    border-bottom:#D1E5EE solid 1px;
    height:30px; }
.sub ul, li { margin:0; padding:0; list-style:none; }
.sub li {
    float:left;
    padding-left:10px;
    margin:8px 20px 0 -18px; }
.sub li a {
    color:#21759B;
    padding:8px;
    text-decoration:none; }
.sub li a:hover { background-color:#FFF; }
#content { margin-top:15px; }
h1 { font-size:13px; }
hr {
    border:0;
    height:1px;
    background-color:#E9E9E9; }
.quick-add {
    background-color:#E9E9E9;
    color:#575757;
    font-size:12px;
    margin-top:10px;
    padding:2px; }
.quick-add td { padding-left:8px; }
#data { margin-top:15px; }
#member { width:100.5%; margin-left:-1px;}
#even {
    background-color:#EFF8FF;
    color:#21759B; }
#odd {
    background-color:#FFF; }
#data td { padding:3px; }
#a { width:5%; text-align:center;}
#b { width:40%; }
#c { width:10%; }
#d { width:20%; }
#e { width:15%; }

Also, I have two different tables on two different pages (one for members and another for information) what's the best way to independently style them?

Thanks!


texts: Input validation for text boxes in a Form

texts:
In a Win Form I'm doing initial validation in the Form. So before saving data, I want to validate whether all the required fields are filled (Text Boxes) by the user. There are about 18 such Text Boxes in the Form. Currently I'm doing it as follows. To make the code short only three fields are shown in the code.

     private void cmbSave_Click(object sender, EventArgs e)
     {
         if(IsFilled (txtApplicationNumber.Text))
         {
             if(IsFilled (txtEmployeeID.Text))
             {
                 if (IsFilled(txtNIC.Text))
                 Save(sender, e);
             }
         }
    }

    private bool IsFilled(string s)
    {
        if (s != "")
        { return true; }
        else
        { return false; }
    }

Another option would be to use the logic inside the cmbSave_Click straightaway as follows,

    private void cmbSave_Click(object sender, EventArgs e)
    {
        If (txtApplicationNumber.Text!="" & txtEmployeeID.Text!="" & txtNIC.Text="")
        Save(sender, e)
    }

Basically the code should be readable, consistent and should perform the validation properly.

Which option could be considered better? If both are not good please propose a way to do this?


texts: Code A Primitive Calculator ( x3,x2,+1) Using Dynamic programming

texts:
Question -You are given a primitive calculator that can perform the following three operations with the current number : multiply  by 2, multiply  by 3, or add 1 to . Your goal is given apositive integer , find the minimum number of operations needed to obtain the number
starting from the number 1.
ll n;
cin>>n;

vector<ll>vec;
vec.pb(n);

if(n==1)
{
    cout<<0<<endl<<1;
}

else
{
    while(n!=1)
    {
        if(n%3==0)
        n=n/3;
        else if(n%2==0)
        n=n/2;
        else
        n=n-1;

        vec.pb(n);
    }

    cout<<vec.size()-1<<endl;

    for(int i=(vec.size()-1);i>=0;i--)
    cout<<vec[i]<<" ";
}
return 0;

}
for input 96234 iam getting
15
1 2 4 5 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234
but the optimal soln is
14
1 3 9 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234
i know i am going wrong at the step when 10 is converted into 5 in my code but it should convert it in to 9, Please help me,


texts: William Fractal technical indicator implementation

texts:
I'm really new to both Python, data analysis and Panda and for gathering a bit of familiarity with this components and trying to replicate a trading strategy I'm creating a function that give me the Wiliam Fractal technical indicator, which by nature is a lagging indicator to apply at the currently analysed row of the dataframe, rather than where it actually happen, but without look ahead bias to not have unrealistic backtesting results ( but also avoiding to go back and always looking for the signal 2 rows before when it actually occurs )
the indicator is defined with this constrains
source
\begin{aligned} \text{Bearish Fractal} =\ &\text{High} ( N ) > \text{High} ( N - 2 ) \text{ and} \\ &\text{High} ( N ) > \text{High} ( N - 1 ) \text{ and} \\ &\text{High} ( N ) > \text{High} ( N + 1 ) \text{ and} \\ &\text{High} ( N ) > \text{High} ( N + 2 ) \\ \end{aligned}
\begin{aligned} \text{Bullish Fractal} =\ &\text{Low} ( N ) < \text{Low} ( N - 2 ) \text{ and} \\ &\text{Low} ( N ) < \text{Low} ( N - 1 ) \text{ and} \\ &\text{Low} ( N ) < \text{Low} ( N + 1 ) \text{ and} \\ &\text{Low} ( N ) < \text{Low} ( N + 2 ) \\ \end{aligned}

which I implemented with the following code:
def wilFractal(dataframe):
        df = dataframe.copy()
        df['bear_fractal'] = (
                dataframe['high'].shift(4).lt(dataframe['high'].shift(2)) &
                dataframe['high'].shift(3).lt(dataframe['high'].shift(2)) &
                dataframe['high'].shift(1).lt(dataframe['high'].shift(2)) &
                dataframe['high'].lt(dataframe['high'].shift(2))
        )

        df['bull_fractal'] = (
                dataframe['low'].shift(4).gt(dataframe['low'].shift(2)) &
                dataframe['low'].shift(3).gt(dataframe['low'].shift(2)) &
                dataframe['low'].shift(1).gt(dataframe['low'].shift(2)) &
                dataframe['low'].gt(dataframe['high'].shift(2))
        )

        return df['bear_fractal'], df['bull_fractal']

any suggestions?
usage edit:
The code in this case is used to signal buy signal for a crypto trading bot in this manner:
def populate_buy_trend(self, dataframe, metadata)
    dataframe.loc[
        dataframe['bull_fractal'],
        'buy'] = 1

    return dataframe


texts:
Working through Learn You a Haskell, I made a Reverse Polish Notation calculator.

Please critique it.

-- LYAH uses `(Num a) => String -> a` as the signature
solveRPN :: String -> Double
solveRPN xs = head $ foldl (\acc x -> foldingFunction acc x) [] $ words xs

foldingFunction :: [Double] -> String -> [Double]
foldingFunction acc elem
 | isOp elem  = calculate (take 2 acc) elem : (drop 2 acc)
 | otherwise  = (read elem :: Double) : acc

calculate :: [Double] -> String -> Double
calculate (y:x:_) op
 | op == "+" =  x + y
 | op == "-" =  x - y
 | op == "*" =  x * y
 | op == "/" =  x / y

isOp :: String -> Bool
isOp x = x `elem` ["+", "-", "*", "/"]


texts: Given a binary tree, find the maximum path sum

texts:
This is a leetcode.com problem.

  For this problem, a path is defined as any sequence of nodes from some
  starting node to any node in the tree along the parent-child
  connections. The path must contain at least one node and does not need
  to go through the root.

  For example: Given the below binary tree,

   1
  / \
 2   3 Return 6.

Following is my solution that is accepted.

As you can see I have used a magic number in place of -inf. This is not only inelegant, it will actually produce wrong answer if the input node has values in that range. I can think of a few ways to solve it, but I am open to suggestions about how you would do it. I can perhaps use special value like None but that introduces extra if logic that's not that beautiful. Are there better ideas?
Do you have suggestions for better names for variables and methods? Please ignore the name of class (and the fact that it does use class) since this is due to how Leetcode's wants it to be written.

To better understand the code, the intuition is, for any given subtree rooted at node n, I calculate the maximum path that includes n as one endpoint and ends within that subtree. I also calculate the maximum path that is between any two node in that subtree (to do that I take the max of few things). The global solution is then computed at the root of the whole tree.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxPathSum(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        _, max_path = self.max_path(root)
        return max_path

    def max_path(self, node):
        if node == None:
            return 0, -9999999

        max_path_from_left, max_path_in_left = self.max_path(node.left)
        max_path_from_right, max_path_in_right = self.max_path(node.right)

        max_path_from_current = max(\
            max_path_from_left + node.val,\
            node.val, \
            max_path_from_right + node.val)

        max_path = max(max_path_in_left, max_path_in_right, \
                  max_path_from_left + node.val + max_path_from_right, \
                  max_path_from_current)
        return max_path_from_current, max_path


texts: Reading bytes between two quotes from a stream and decoding it to its appropriate character set

texts:
This is a component for a lexer which operates on a byte input stream that handles reading and decoding the contents of a string contained within double-quotes. The validity of the encoding is handled by CharsetDecoder#decode() which will throw an exception on an invalid buffer.

The charset argument defines the encoding of the string contents not the encoding of the quotation marks themselves (which is defined by the lexer). This allows the contents of the string to be defined as a character set other than the parent document. However, it must be a valid subset of Unicode such that its contents do not erroneously contain a byte value to match code point 34. Some form of readHeredoc() could provide an alternative for this specific use case.

String readString(
   Reader r,
   Charset charset)
   throws IOException
{
   ByteArrayOutputStream ostream = new ByteArrayOutputStream();

   int cp;

   while ((cp = r.read()) > 0) {
      if (cp == '"')
         break;

      ostream.write(cp);
   }

   return charset.newDecoder().decode(ByteBuffer.wrap(ostream.toByteArray()))
      .toString();
}

Reaching the end the buffer before a matching quotation is not handled; I haven't decided on the defined behavior for this and its absence is known.


texts:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

class Complex {
private:
    double Rez, Imz, ro, fi;

public:
    Complex() {
        Rez = 0.;
        Imz = 0.;
        ro = 0.;
    fi = 0.;
}

Complex(double x, double y) {
    Rez = x;
    Imz = y;
    ro = sqrt(pow(x,2)+pow(y,2));
    fi = atan(y/x);
 }

~Complex() {}

double get_Rez() {return Rez;}
double get_Imz() {return Imz;}
double get_ro() {return ro;}
double get_fi() {return fi;}

void set_Rez(double a) {Rez = a; ro = sqrt(pow(Rez,2)+pow(Imz,2)); fi = acos(Rez/ro);}
void set_Imz(double a) {Imz = a; ro = sqrt(pow(Rez,2)+pow(Imz,2)); fi = acos(Rez/ro);}
void set_ro(double a) {ro = a; Rez = ro*cos(fi); Imz = ro*sin(fi);}
void set_fi(double a) {fi = a; Rez = ro*cos(fi); Imz = ro*sin(fi);}

Complex & inverso() {
    this->set_Rez(this->get_Rez()/pow(this->get_ro(),2));
    this->set_Imz(-this->get_Imz()/pow(this->get_ro(),2));
    return *this;
}

};

These two are the functions to work with my complex numbers. Is it possible to change them in order to make them accept also doubles as input? In that case, would it be possible to make them give a double as an output? Is it correct to say that my functions haven't got side effects? Would it be better to put the functions in the class as data members?

Complex somma(Complex a, Complex b) {
    Complex c;
    c.set_Rez(a.get_Rez()+b.get_Rez());
    c.set_Imz(a.get_Imz()+b.get_Imz());
    return c;
}

Complex prodotto(Complex a, Complex b) {
    Complex c;
    c.set_ro(a.get_ro()*b.get_ro());
    c.set_fi(a.get_fi()+b.get_fi());
    return c;
}


texts: Is this Josephus problem solution bad or really bad?

texts:
I tried to make a python code that would answer the Joseph problem. I really had a hard time with this and the try blocks was the only thing I could come up with. Can anyone tell me if the way I did it is valid or I have to rewrite the code because its too bad?

The problem is:

  People are standing in a circle waiting to be executed. Counting begins at a specified point in the circle and proceeds around the circle in a specified direction. After a specified number of people are skipped, the next person is executed. The procedure is repeated with the remaining people, starting with the next person, going in the same direction and skipping the same number of people, until only one person remains, and is freed.

  The problem — given the number of people, starting point, direction, and number to be skipped — is to choose the position in the initial circle to avoid execution.

My solution:

class Game:
    def __init__(self, n):
        self.n = n
        self.ppl = []
        self.has_gun = 1

    def creating_list(self):
        for i in range(1, self.n+1):
            self.ppl.append(i)

    def kill(self):
            number = self.ppl.index(self.has_gun)
            try:
                print("{} shoots {}".format(self.has_gun, self.ppl[number + 1]))
                del self.ppl[number + 1]
            except IndexError:
                print("{} shoots {}".format(self.has_gun, self.ppl[0]))
                del self.ppl[0]
            try:
                print("{} gives his gun to {}".format(self.has_gun, self.ppl[number+1]))
                self.has_gun = self.ppl[number + 1]
            except IndexError:
                if len(self.ppl) > 1:
                    print("{} gives his gun to {}".format(self.has_gun, self.ppl[0]))
                else:

                    print("{} is the only one remaining person in the circle".format(self.ppl[0]))
                self.has_gun = self.ppl[0]
            print("*" * 40)

    def run(self):
        self.creating_list()
        while True:
            self.kill()
            if len(self.ppl) == 1:
                print("{} survives".format(self.ppl[0]))
                break

while True:
    try:
        question = int(input("How many people in the circle do you want to be?\n"))
        break
    except:
        print("Type a number\n")
cos = Game(question)
cos.run()


texts: Find perfect squares between two numbers

texts:
The following problem is from codechef.com:

  Recently Chef become very much interested in perfect squares. We all
  know Chef and his weird interests. Anyways Chef will be soon writing
  his masters thesis on perfect squares revealing what-not-known
  properties of perfect squares. While doing his research, he happened
  to be confronted with some interesting perfect squares. These prefect
  squares consists only of digits which are themselves perfect squares.
  0, 1, 4 and 9 are such digits. These are called perfect digits.

  As we all know Chef also has habit of asking too many questions, he is
  asking- given two numbers a and b, how many perfect squares exists
  between these two numbers inclusive, that contains only perfect
  digits.

  Input:

  First line of input will contains T, number of test cases. Then T
  lines follows, each containing two positive integers a and b.

  Constraints:

  \$T \le 500\$
  \$1 \le a \le b \le 10000000000\$

  Output:

  For each input, output number of perfect digit squares between given
  numbers.

  Sample:

  Input:

2
1 10
100 10000
 Output:

3
9

How can I decrease the running time of my solution?

#include<stdio.h>
int main()
{
    int test;
    long long int num1,num2,start,stop,i,j,square,rem;
    scanf("%d",&test);
    while(test--)
    {
        long long int count=0;
        scanf("%lld%lld",&num1,&num2);
        start=sqrt(num1);
        stop=sqrt(num2);
        for(i=start;i<=stop;i++)
        {
            square = i*i;

            if(square<num1)
            {
                continue;
            }
            else
            {
                while(1)
                {

                    rem=square%10;
                    if(rem!=1 && rem!= 4 && rem!=9 && rem!=0 )
                    {
                        break;
                    }
                    if(square>=10)
                    {
                        square=square/10;

                    }
                    else
                    {
                        if(square!=1 && square!= 4 && square!=9 &&square!=0 )
                        {
                                break;
                        }
                        else
                        {
                            count+=1;
                        }
                        break;
                    }
                }
            }
        }
        printf("%lld\n",count);
    }
    return 0;
}


texts: Global appIncluder function to include sub-applications dynamically

texts:
I have implemented a global appIncluder function which is imported as includeme with the init.py of the package to be included.

includeme (ApplicationIncluder) receives the config object, so it is then easy to use config.package and its variables/methods/classes (present in the same init.py and submodules.

I would really appreciate getting some feedback on this and see what can be improved.

project: 'foo'

Apps to be deployed in foo.foo.apps directory.

Structure:

foo
|-foo
  |- __init__.py
  |- appincluder.py
  |-apps
    |-test
      |- __init__.py
      |- views.py
      |- templates
         |- test.jinja2

foo/foo/init.py

config.include('foo.apps.test')

foo/foo/appincluder.py

def appIncluder(config):
    app    = config.package
    prefix = app.prefix
    routes = app.routes

    for route,url in routes.items():
        config.add_route(route,prefix + url)

    config.scan(app)

    log.info('app: %s included' % app.__name__)

foo/foo/apps/test/init.py

from foo.appincluder import appIncluder as includeme

prefix = '/test'

routes = {
    'test': '/home'
}

foo/foo/apps/test/views.py

from pyramid.view import view_config

@view_config(route_name='test', renderer='templates/test.jinja2')
def test(request):
    return {}

Info: I prefer each app to come along with its config, hence the choice of putting the prefix in the app init.py file instead of specifying it in config.include(app,prefix).


texts:
I made a Three Monte Card game using Java
Problem:

This is the original "ball and cups" game where you try to find out which cup has the ball under it. You may play with three cups and a ball, three cards (two jacks and an ace), or three doors and a car. Basically, randomly select a cup to hide the "ball". Let the player guess which cup hides the ball. The player wins if they guess correctly.

Problem taken from:

https://programmingbydoing.com/a/three-card-monte.html

My code:
/*
 * Code by CLint
 */

import java.util.Random;
import java.util.Scanner;

public class ThreeCardMonte {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner input = new Scanner(System.in);
        int userInput;

        int randomN = random.nextInt(3)+1;

        System.out.println("You slide up to Fast Eddie's card table and plop down your cash.\n" +
                "He glances at you out of the corner of his eye and starts shuffling.\n" +
                "He lays down three cards.\n");
        System.out.println("Which one is the ace?\n" +
                "\t##\t##\t##\n" +
                "\t##\t##\t##\n" +
                "\t1\t2\t3");
        System.out.print("\n> ");
        userInput = input.nextInt();

        if (userInput == randomN) {
            if (randomN == 1) {
                System.out.println("\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\n" +
                        "\tAA\t##\t##\n" +
                        "\tAA\t##\t##\n" +
                        "\t1\t2\t3");
            } else if (randomN == 2) {
                System.out.println("\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\n" +
                        "\t##\tAA\t##\n" +
                        "\t##\tAA\t##\n" +
                        "\t1\t2\t3");
            } else if (randomN == 3) {
                System.out.println("\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\n" +
                        "\t##\t##\tAA\n" +
                        "\t##\t##\tAA\n" +
                        "\t1\t2\t3");
            }
        }

        if (userInput != randomN) {
            if (randomN == 1) {
                System.out.println("\nHa! Fast Eddie wins again! The ace was card number 1.\n" +
                        "\tAA\t##\t##\n" +
                        "\tAA\t##\t##\n" +
                        "\t1\t2\t3");
            } else if (randomN == 2) {
                System.out.println("\nHa! Fast Eddie wins again! The ace was card number 2.\n" +
                        "\t##\tAA\t##\n" +
                        "\t##\tAA\t##\n" +
                        "\t1\t2\t3");
            } else if (randomN == 3) {
                System.out.println("\nHa! Fast Eddie wins again! The ace was card number 3.\n" +
                        "\t##\t##\tAA\n" +
                        "\t##\t##\tAA\n" +
                        "\t1\t2\t3");
            }
        }

    }
}

The output:

PS: I am open for corrections to make my code for efficient and clean.


texts:
I'm writing code to compute a single value answer to a given numbers in integer array such that step sum is calculated till only 1 number is left.

For example:

Input:

3,5,2,6,7

Output is computed as:

(3+5)+(5+2)+(2+6)+(6+7)

It remains like this till I only have a single number left.

3   5   2   6   7
  8   7   8  13
   15  15  21
     30  36
       66

int inputarray={3,5,2,6,7};
int inputlength=inputarray.length;
   while(inputlength!=0)
   {
   for(int i=0;i<inputlength-1;i++)
   {
      inputarray[i]=inputarray[i+1]+inputarray[i];
   }
   inputlength--;
   }
    System.out.println(inputarray[0]);

It computes the result in quadratic growth.  Is there any way to compute my result more efficiently? What else can I do to improve it?


texts: Lock free consumer producer using memory barrier

texts:
I am looking for "complete" producer-consumer sample using C++11 memory barrier.

(I have derived following example from Jeff's article and added a line to make it complete.)

void SendTestMessage(void* param)
{
    // Copy to shared memory using non-atomic stores.
    g_payload.tick  = clock();
    g_payload.str   = "TestMessage";
    g_payload.param = param;

    // Release fence.
    std::atomic_thread_fence(std::memory_order_release);

    // Perform an atomic write to indicate that the message is ready.
    g_guard.store(1, std::memory_order_relaxed);
}

bool TryReceiveMessage(Message& result)
{
    // Perform an atomic read to check whether the message is ready.
    int ready = g_guard.load(std::memory_order_relaxed);

    if (ready != 0)
    {
        g_guard.store(0, std::memory_order_relaxed);

        // Acquire fence.
        std::atomic_thread_fence(std::memory_order_acquire);

        // Yes. Copy from shared memory using non-atomic loads.
        result.tick  = g_payload.tick;
        result.str   = g_payload.str;
        result.param = g_payload.param;

        return true;
    }

    // No.
    return false;
}

if you notice, i have added g_guard.store(0, std::memory_order_relaxed); just before acquire.

This will help following ways

It would avoid TryReciveMessage to cosnume same message if called multiple times before new message is written
It would not add explicit memory fence and hence won't affect performance
since std::memory_order_relaxed guarantees the ordering, it would get overwritten by SendTestMessage value if new load added after the std::memory_order_acquire is called. So, we will not miss any load.

Please provide your comments and/or suggestions.


texts: Assign values to answers from a questionnaire, input into a formula and calculate score

texts:
I was wondering if anyone could make any suggestions to how I could write the following more concisely and reduce the number of IF statements? If possible, I would also like to simultaneously assign values to variables and calculate the score.

I will eventually have multiple rule sets and formula scores for other question sets.

# q001 is multiple choice with three choices - q001_a01, q001_a02 & q001_a03 - only one selection can be made
# q002 is the first part of a two part question. It has two options = q002_a01 & q002_a02 - again, only one selection can be made
# q003 is only answered if q002_a01 is selected in q002 and also has two choices - q003_a01 & q003_a02
# q004 is a multiple choice question with 5 options - q004_a01, q004_a02, q004_a03, q004_a04 & q004_a05 - multiple selections can be made, q004_a05 answer is 'none of the above'
# q005 is a simple Yes/No (True/False) question
# q006 is multiple choice with three choices - q006_a01, q006_a02, q006_a03 & q006_a004 - only one selection can be made
# q007 is multiple choice with three choices - q007_a01, q007_a02 & q007_a03 - only one selection can be made
# q008 requires an input of an integer from 1-5
# all questions require a response (except q003)

# dictionary containing question and answer codes for a single individuals response
data = {'q001': 'q001_a01',
        'q002': 'q002_a01',
        'q003': 'q003_a02',
        'q004': ['q004_a01', 'q004_a02', 'q004_a04'],
        'q005': False,
        'q006': 'q006_a03',
        'q007': 'q007_a01',
        'q008': 3}

# rules which define the values of the different variables
var1 = 2 if 'q001_a01' in data['q001'] else 0
var1 = 5 if 'q001_a02' in data['q001'] or 'q001_a03' in data['q001'] else var1

var2 = -2 if 'q002_a01' in data['q002'] and 'q003_a01' in data['q003'] else 0
var2 = 2 if 'q002_a01' in data['q002'] and 'q003_a02' in data['q003'] else var2

var3 = 2 if 'q004_a01' in data['q004'] else 0
var3 = var3 + 2 if 'q004_a02' in data['q004'] else var3
var3 = var3 - 1 if 'q004_a03' in data['q004'] else var3
var3 = var3 + 1 if 'q004_a04' in data['q004'] else var3
var3 = 5 if 'q004_a05' in data['q004'] else var3

var4 = 4 if True is data['q005'] else 0

var5 = 1 if 'q006_a01' in data['q006'] else 0
var5 = 2 if 'q006_a02' in data['q006'] else var5
var5 = -10 if 'q006_a03' in data['q006'] else var5
var5 = -2 if 'q006_a04' in data['q006'] else var5

var6 = 2 if 'q007_a01' in data['q007'] else 0
var6 = 1 if 'q007_a02' in data['q007'] or 'q007_a03' in data['q007'] else var6

var7 = data['q008']

# formula to calculate score from variables
score = var1 + var2 + var3 + var4 + ((var5 + var6) * var7)

I would like to make the code as neat and fast as possible.
Also, could someone point me towards some python literature which would help me improve this myself?