texts: Efficiently determine every factor of a given natural number

texts:
It's not hard to find all of the factors of a given natural number. Below is a pretty fast python function that can do just that:
(Modified version of Steinar Lima's function, https://stackoverflow.com/a/19578818/5946921)

import itertools as it

def factor(n):
    step = 2 if n % 2 else 1
    factors = ([i, n//i] for i in range(1, int(sqrt(n))+1, step) if not n % i)
    return sorted(set(it.chain.from_iterable(factors)))

I am looking to make a function that can do this more efficiently for very large numbers. I have come up with the following function that does just that:

import itertools as it

def large_factor(n):
    primes = []
    ranges = []
    for prime, factors in it.groupby(primeFactor(n), lambda x: x):
        primes.append(prime)
        ranges.append(range(len(tuple(factors)) + 1))
    primes = primes[::-1]
    ranges = ranges[::-1]
    z = it.product(*(x for x in ranges))
    return sorted(product(a ** b for a, b in zip(primes, q)) for q in z)

I am looking for ways to improve this function. I want it to return the factors in ascending order, without duplicates. Originally, I was hoping I'd be able to have the entire thing be a lazy function (no eager evaluation at all). Unfortunately, I haven't been able to figure out a good way to do this. My approach right now is to get the prime factors from n, and a list of ranges [0, #primes factors + 1). These lists are then reversed, as this makes sorting easier later. The list of ranges is used to generate tuples that contain the powers that are applied to the prime numbers in the last line.

The following two functions are used in the large_factor() function:

import math

def primeFactor(n):
    ''' Generates prime factors of n'''
    if n <= 1: return
    prime = next((x for x in range(2, math.ceil(math.sqrt(n))+1) if n%x == 0), n)
    yield prime
    yield from primeFactor(n//prime)

from functools import reduce
from operator import mul

def product(iterable):
    ''' The product of the items in n '''
    return reduce(mul, iterable)

I've tested these functions with timeit, and found that factor() was significantly faster on small values on n, but on large values of n, large_factor() was significantly faster. I'm looking for any kind of optimization that can make large_factor() faster on smaller, or (especially) larger numbers, as well as any other suggestions you might have.


texts: Method to remove comments from a string line

texts:
There is some language where the following are considered comments:

[str] // comment
[str] /* comment */ [str]
[str] # comment
[str] /* comment1
comment2 */ [str]

where [str] is 0 or more occurrences of some string.

I'm reading a file line by line, and need to remove the comments from the whole file (the file is large so I cannot keep the whole content in memory).

I have written a method that receives each line, removes the comments from it, and returns the remaining string.

(Here s_bInComment is a static variable in Parser class with initial value of false)

void Parser::removeComments(std::string &str)
{
    // see if we're still in comment lines, i.e. not reached */
    auto commentEnd = str.find("*/");
    if (s_bInComment && commentEnd == std::string::npos)
    {
        str.clear();
        return;
    }

    std::string result;

    const auto iStrLen = str.length();
    for (std::size_t idx = 0; idx < iStrLen; ++idx)
    {
        if (str[idx] == '/')
        {
            if (idx + 1 < iStrLen)
            {
                if (str[idx + 1] == '/')
                {
                    // we found //
                    // take the part of the string before the comment, if any
                    str = str.substr(0, idx);
                    break;
                }

                if (str[idx + 1] == '*')
                {
                    // see if */ is in the same line
                    commentEnd = str.find("*/");
                    if (commentEnd == std::string::npos)
                    {
                        // multiline comment
                        s_bInComment = true;
                        str = str.substr(0, idx);
                    }
                    else
                    {
                        // remove the comment
                        str = result + str.substr(commentEnd + 2);

                        // recurse on the remaining string
                        removeComments(str);
                    }

                    break;
                }
            }
        }
        else if (str[idx] == '*')
        {
            if (idx + 1 < iStrLen)
            {
                if (str[idx + 1] == '/')
                {
                    // we have found */, comment ended
                    s_bInComment = false;

                    // take the part of the string after the comment, if any
                    str = str.substr(idx + 2);

                    // recurse on the remaining string
                    removeComments(str);

                    break;
                }
            }
        }
        else if (str[idx] == '#')
        {
            // if there's a text before #, it should be accumulated in result
            str = result.size() ? result : std::string();
            break;
        }
        else if (!s_bInComment)
            result += str[idx];
    }
}

I have tested my code with the following input lines:

a /* b */ c
a /* b */
a // b
a /* b
c
*/
// a
a /* b
*/ c
# a
a # b
a /* a */ b /* b */ c

Please let me know if there's room for improvement in one or other part.


texts: Optimize/ refactor program that highlights differences between two text collections

texts:
I made a simple comparison window in WPF that has two RichTextBoxes highlighting the differences (in red) of two StringCollections.

I knocked the code up in about 5 minutes and having gone back to look at it it appears pretty shoddy. I've included comments to show my intentions.

private static void DifferentiateText(RichTextBox richTextBox1, RichTextBox richTextBox2, StringCollection text1,
    StringCollection text2, SolidColorBrush brushColour)
{
    var text1Length = text1.Count;
    var text2Length = text2.Count;

    //Loop through text1 array
    for (var i = 0; i < text1Length; i++)
    {
        var text1Line = text1[i] + "\r\n";

        //If we're within text1 and text2 array boundaries, then compare their values
        if (i < text2Length)
        {
            var text2Line = text2[i] + "\r\n";

            //If lines aren't the same, apply brush
            if (text1Line != text2Line)
            {
                AssignTextToTextBox(richTextBox1, text1Line, brushColour);
                AssignTextToTextBox(richTextBox2, text2Line, brushColour);
            }
            else //Output with default brush
            {
                AssignTextToTextBox(richTextBox1, text1Line);
                AssignTextToTextBox(richTextBox2, text2Line);
            }
        }
        else //At the end of text2 array, so just output the rest of text1
        {
            AssignTextToTextBox(richTextBox1, text1Line, brushColour);
        }

        //If we're at the end of text1 array but not at the end of text2 array, then just output the rest of text2
        if (i == text1Length - 1 && text1Length < text2Length)
        {
            for (; i < text2Length; i++)
            {
                var text2Line = text2[i] + "\r\n";
                AssignTextToTextBox(richTextBox2, text2Line, brushColour);
            }
        }
    }
}

private static void AssignTextToTextBox(RichTextBox richTextBox, string text, SolidColorBrush brushColour = null)
{
    var textRange = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd)
    {
        Text = text
    };

    if(brushColour != null)
        textRange.ApplyPropertyValue(TextElement.ForegroundProperty, brushColour);
}

I don't particularly like how AssignToTextBox is used 6 times in the first for loop when really it will only be called a maximum of two times.

Is there any way to optimize/ refactor/ make-less-shoddy this code?


texts: C# Parser of strings with list of assignments

texts:
I have implemented class which manages communication with measuring device, which sends list of assignments, like variableName=value. These assignments are always separated by space. There are two options, the first is simple assignment variableName=value (without space around equal sign), the second is "array assignment", like variableName[num]= value_1 ... value_num (here is space after equal sign and between single values).
Here is my code for parser:

    /// <summary>
    /// Parse variable value "y" from assignment pair "x=y"
    /// </summary>
    /// <param name="s">string where "x=y" pairs are separated by space</param>
    /// <param name="varName">left side of assignment</param>
    /// <returns>right side of assignment</returns>
    private static string ParseEqualValue(string s, string varName)
    {
        int startPos = s.IndexOf("=", s.IndexOf(varName)) + 1;
        int endPos = s.IndexOf(" ", startPos);
        return s.Substring(startPos, endPos - startPos);
    }

    /// <summary>
    /// Parse variable values after "=" from string
    /// </summary>
    /// <param name="s">string in format: varName[num]= x1 .. xnum</param>
    /// <param name="varName">left side of assignment</param>
    /// <returns>right side of assignment in the list</returns>
    private static List<string> ParseEqualValues(string s, string varName)
    {
        List<string> list = new List<string>();

        // position of ShapeX..
        int varPos = s.IndexOf(varName);

        // parsing of numPts value in []
        int numStartPos = s.IndexOf("[", varPos) + 1;
        int numEndPos = s.IndexOf("]", numStartPos);
        int num = 0;
        int.TryParse(s.Substring(numStartPos, numEndPos - numStartPos), out num);

        int startPos = s.IndexOf("=", varPos) + 2;

        for (int i = 0; i < num; i++)
        {
            int endPos = s.IndexOf(" ", startPos);
            if (endPos < 0)
                endPos = s.Length;

            list.Add(s.Substring(startPos, endPos - startPos));
            startPos = endPos + 1;
        }

        return list;
    }

And here how I use it:

    /// <summary>
    /// Create ColdTest cut from ProfRoll answer
    /// </summary>
    /// <param name="s">Answer from ProfRoll</param>
    /// <returns></returns>
    public static Cut CreateColdTestCut(string s)
    {
        Cut cut = new Cut();
        cut.pts = new List<PointF>();

        int numShapes;

        double.TryParse(ParseEqualValue(s, "AvgTemp"), out cut.pyroTemp);
        double.TryParse(ParseEqualValue(s, "MinTemp"), out cut.tempMin);
        double.TryParse(ParseEqualValue(s, "MaxTemp"), out cut.tempMax);

        int.TryParse(ParseEqualValue(s, "NumShapes"), out numShapes);

        List<int> numPts = new List<int>();

        for (int i = 0; i < numShapes; i++)
        {
            List<string> xPts = ParseEqualValues(s, string.Format("ShapeX{{0}}", i));
            List<string> yPts = ParseEqualValues(s, string.Format("ShapeY{{0}}", i));

            if (xPts.Count != yPts.Count)
                break;

            numPts.Add(xPts.Count);

            for (int j = 0; j < xPts.Count; j++)
            {
                try
                {
                    cut.pts.Add(new PointF(float.Parse(xPts[j]), float.Parse(yPts[j])));
                }
                catch { }
            }
        }

        cut.isColdTest = true;
        cut.time = DateTime.Now;
        cut.numCurves = cut.numPts.Length;

        return cut;
    }

I will be glad for any critical comments.


texts: Find the missing number and repeated number

texts:
I am practising interview questions from here.

  Problem : You are given a read only array of n integers from 1 to n.
  Each integer appears exactly once except A which appears twice and B
  which is missing. Return A and B such that output A should precede B.

My approach :

Sum(Natural numbers) = Sum(given numbers) - A + B
Sum_squares(Natural numbers) = Sum_squares(given numbers) - A*A + B*B

where  :

Sum of n Natural numbers is given by : n(n+1)/2
Sum of squares of n Natural numbers is given by : n((n+1)/2)((2n+1)/3)

The above two equations can be simplified to :

(B-A)  = Sum(Natural numbers) - Sum(given numbers)
(B-A)*(B+A) = Sum_squares(Natural numbers) - Sum_squares(given numbers)

Solution:

def repeat_num_and_missing_num(array):
    """ returns the value of repeated number and missing number in the given array
    using the standard formulaes of Sum of n Natural numbers and sum of squares of n Natural Numbers"""
    missing_num = 0
    repeated_num = 0
    x = len(array)
    sum_of_num = 0
    sum_of_squares = 0
    sum_of_num_actual = (x*(x+1))/2
    sum_of_squares_actual = ((x)*(x+1)*(2*x+1) ) / 6

    for num in array:
        sum_of_num += num
        sum_of_squares += num*num

    missing_num = (((sum_of_squares_actual - sum_of_squares) /(sum_of_num_actual - sum_of_num))
                    +(sum_of_num_actual - sum_of_num))/2
    repeated_num = (((sum_of_squares_actual - sum_of_squares) /(sum_of_num_actual - sum_of_num))
                     -(sum_of_num_actual - sum_of_num))/2
    return repeated_num, missing_num

#Test Cases
print repeat_num_and_missing_num([5,3,2,1,1]) == (1,4)

print repeat_num_and_missing_num([1,2,3,4,5,16,6,8,9,10,11,12,13,14,15,16]) == (16,7)

print repeat_num_and_missing_num([1,1]) == (1,2)

How can I make this code better?


texts:
I have a program which finds, well, a magic square of squares. The problem is, it's quite slow - it processes around 50 numbers in half a second when the number range is above 40,000.

Is there any way to improve this code?

from math import floor

# checksquare checks for the possibility of a set being a magic square.
# One example of an incoming list (split for readability) is:
# [[1634],
# [15, 25, 28], [11, 27, 28], [8, 27, 29],
# [3, 28, 29], [12, 23, 31], [13, 21, 32],
# [9, 23, 32], [4, 23, 33], [3, 20, 35]]
# The square of each number in the lists of length 3
# add up to the single number in the list of length 1.
# (e.g. 15^2 + 25^2 + 28^2 = 1634)
# This function checks for this possibility by doing so:
# If all of the numbers in the sets of 3 are repeated at least once,
# Then it outputs it to a separate file.
def checksquare(listin):
    # listcheck only contains the lists of length 3.
    listcheck = listin[1:]
    # dictofnos is used to check the amount of each number in listcheck.
    dictofnos = {}
    # setof0s is used to remove numbers which are not repeated.
    setof0s = []
    # The first loop checks the amount of each number in listcheck.
    for e in range(len(listcheck)):
        for f in range(3):
            try:
                dictofnos[(listcheck[e])[f]] += 1
            except KeyError:
                dictofnos[(listcheck[e])[f]] = 1
    # The second loop removes any value that is not repeated.
    for g in dictofnos:
        if dictofnos[g] == 1:
            for h in range(len(listcheck)):
                if g in listcheck[h]:
                    for j in range(3):
                        if dictofnos[(listcheck[h])[j]] == 0:
                            pass
                        dictofnos[(listcheck[h])[j]] -= 1
                    listcheck.remove(listcheck[h])
                    listcheck.append([])
            for i in range(len(listcheck)):
                if len(listcheck[i]) != 3:
                    listcheck.remove(listcheck[i])
    # This if/elif is used to catch any lists that passed the two loops
    # while having non-repeating numbers.
    if 0 in dictofnos.values():
        [setof0s.append(k) for k in dictofnos if dictofnos[k] == 0]
    elif 1 in dictofnos.values():
        listcheck = listin[:1] + listcheck
        checksquare(listcheck)
        return None
    # The final loop is deleting entries in the dict which are removed
    # (hence the use of setof0s).
    for l in setof0s:
        del dictofnos[l]
    # Outputs to output.txt.
    if len(listcheck) != 0:
        output = open("output.txt", "a+")
        output.write("\n" + str(listin[0]) + "\n" + str(dictofnos) + "\n" + str(listcheck) + "\n")
        output.close()

# powers checks if 3 squares add up to a number.
def powers(limit):
    numberrange = 3 * ((limit + 1) ** 2)
    for a in range(numberrange):
        # Everything here is for efficiency.
        temp = 0
        templist = [[a]]
        check = 1
        b = 0
        c = int(floor((a / 4.0) ** 0.5))
        d = int(floor((a / 2.0) ** 0.5))

        while b <= c <= d <= limit and d ** 2 < a:
            b += check
            if b == c or (b * 2) ** 2 > a:
                c += 1
                b = 1
                continue
            if c == d:
                d += 1
                c = int(floor((a / 4.0) ** 0.5))
                b = 1
                continue
            if (b + c + d) % 2 != a % 2:
                check = 2
                b -= 1
                continue
            if b ** 2 + c ** 2 + d ** 2 == a:
                templist.append([b, c, d])
                temp += 1
        # If 8 solutions for b^2 + c^2 + d^2 = a are found
        # for any a, then it is sent to checksquare.
        if temp >= 8:
            checksquare(templist)

# The usage of these functions would be to put
# powers(whatever the upper bound of d is).
powers(100)

EDIT: Added explanation (sorry if it's really long), and improved some minor things.


texts: Merge K sorted Arrays (JavaScript using generators)

texts:
Question: Merge k sorted Arrays

My main concerns about my code are:

Performance: is it optimized and is my description of the time and complexity correct. How should I annotate the space and time complexity at every step of the code?
What effect do generators have on the time and space complexity?
Is my code self-documenting, modular, and readable and how can it be written better?

Solution:

convert the sorted arrays into a Set data structures O(N)
create a generator function which takes in the iterative values, converts them into the values type, while removing the first value as an argument to be passed to the resulting iterations.
I iterate over the remaining sets O(N)
I Use another generator function to merge the values O(N*N)-> O(N^2)
In the merge generator, I set three-pointers and iterate them over the
combined lengths of the two target arrays, the accumulated array setA with the next sequential array setB. I then iterate the ri pointer over the space of both arrays
In the merge generator, I check if setA pointer is > than the length of all possible setA, this leaves setB at its current pointer as the only viable solution set. I yeld its value inside the generator space. I also default to the pointer at SetB if the value at SetA is larger than that at SetB. Otherwise, the value at SetA is at a higher priority and I yield setA's value to the solution space of the generator at ri.
in the merge generator space setA is the accumulation placeholder
as I yield the pass in the mergeSortedSets generator I have to lazy load the yielded values

because of that, I think the run-time complexity is at worst O(N^3) (I think this might be wrong)

function* mergeSortedSets(iterative, sets = iterative.values(), pass = sets.next().value) {
  for (let set of sets) {
    yield pass = [...merge(pass, set)]
  }
}

function* merge(setA, setB) {
  for (let ri = 0, ai = 0, bi = 0; ri < setA.length + setB.length; ri++) {
    if (ai >= setA.length || setA[ai] > setB[bi]) yield setB[bi++];
    else yield setA[ai++];
  }
}

let reduce = mergeSortedSets(new Set([
  [1, 4, 5],
  [1, 3, 4],
  [2, 6],
  [2, 3, 4]
].map(iterative => iterative)))

for (let result of reduce) {
  console.log(result)
}


texts: Making a dynamic query based on a cookie change

texts:
I have a PHP function which sets/unsets something (category and tags) in the cookie and then makes a dynamic query based on it:

public function tagged(){

    $this->specific_tag  =  true;

    function unset_cookie($cookie_name) {
        setcookie($cookie_name, "", time() - 3600, '/');
        unset($_COOKIE[$cookie_name]);
    }

    function set_cookie($cookie_name, $cookie_value) {
        setcookie($cookie_name, $cookie_value, 2147483647, '/');
        $_COOKIE[$cookie_name] = $cookie_value;
    }

    if ( isset($_GET['c']) ) {
        if ( empty($_GET['c']) ) {
            unset_cookie('qanda_questions_category');
        } else {
            set_cookie('qanda_questions_category', $_GET['c']);
        }
    }

    if ( isset($_GET['t']) ) {
        if ( empty($_GET['t']) ) {
            unset_cookie('qanda_questions_tag');
        } else {
            set_cookie('qanda_questions_tag', $_GET['t']);
        }
    }

    $this->consider_category_tag_cookies();

    if ( $this->category_cookie || $this->tag_cookie ) {

        $query_where = $query_join = '';

        if ( $this->category_cookie ) {
            $query_where .= "AND qa.category = :c";
            $this->parameters[":c"] = $_COOKIE['qanda_questions_category'];
        }

        if ( $this->tag_cookie ) {
            $query_join  .= " INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
                              INNER JOIN tags ON tags.id = qt.tag_id";
            $query_where .= " AND tags.name = :t";
            $this->parameters[":t"] = $_COOKIE['qanda_questions_tag'];
        }

        return $this->index($query_where, $query_join, __FUNCTION__);
    } else {
        return header("Location: /myweb/questions".make_url_query($_GET, [],['c','t']));
    }
}

I've tried so much to write it clean and functional, but it contains lots of if statements. It bothers me and I think it should be possible to reduce some of them. Do you have any idea?

Do I need to add more function to the code? Or should I chop the code into multiple separated functions? Anyway, how can I write it more cleanly?


texts: File manager project (creates and prints file)

texts:
I just finished my very simple and beginner-friendly C project and wanted to hear your thoughts and opinions about ways to improve it or something.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void getFile();
void createFile();

int main()
{
    createFile();
    getFile();
    return 0;
}

void createFile()
{
    char userfilename[40];
    char filecontent[1000];
    FILE *filePointer;

    printf("How do you want to name your file? ");
    scanf("%s", userfilename);
    filePointer = fopen(userfilename, "w");

    printf("Enter file content: ");
    scanf ("%999[^\n]", filecontent);
    getchar();
    fgets (&filecontent, 1000, stdin);
    fputs(filecontent, filePointer);

    fclose(filePointer);
    printf("Written file successful.\n");
}

void getFile()
{
    int c;
    char fileName[100];
    FILE *filePointer;

    printf("\nEnter filename: ");
    gets(fileName);
    printf("\n");

    filePointer = fopen(fileName, "r");
    if(filePointer == NULL)
    {
        printf("File not found.\n");
    }
    else
    {
        int count = 0;
        printf("File contents:\n");
        while ((c = getc(filePointer)) != EOF)
        {
            putchar(c);
            if(c == ' ')
            {
                count++;
            }
        }
        printf("\n");
        printf("Number of words: %d", count + 1);
        fclose(filePointer);
    }
}


texts:
I have started working on the projects listed here.  I want to practice my C++ coding skills.  I would love any constructive criticism I can get!

This is for the very first problem, #1 "Grading Program"

#include <iostream>
using std::cout;
using std::cin;

int main()
{
    int UserNumber;
    char Grade;

    cout << "Enter the grade you got on that test: ";
    cin >> UserNumber;
    cout << "\n\n\n";

    if (UserNumber > 89 && UserNumber < 101)
    {
        Grade = 'A';
    }

    else if (UserNumber > 79 && UserNumber < 91)
    {
        Grade = 'B';
    }

    else if (UserNumber > 69 && UserNumber < 81)
    {
        Grade = 'C';
    }

    else if (UserNumber > 59 && UserNumber < 71)
    {
        Grade = 'D';
    }

    else if (UserNumber > -1 && UserNumber < 61)
    {
        Grade = 'F';
    }
    else
    {
        Grade = 'Z';
    }

    switch (Grade)
    {
    case 'A':
        cout << "Perfect! You got a: " << Grade;
        break;
    case 'B':
        cout << "Could've been worse. You got a: " << Grade;
        break;
    case 'C':
        cout << "It's okay I guess, you got a: " << Grade;
        break;
    case 'D':
        cout << "Uggh.. You got a: " << Grade;
        break;
    case 'F':
        cout << "Better luck next time! You got a: " << Grade;
        break;
    case 'Z':
        cout << "Undefined value! Make sure it's a value from 0-100!";
        break;

    }
    cout << "\n\n\n\t\t\t";
    return 0;
}


texts:
I have the following task:

  The Shallow Alto city council has organized a special committee to
  review the traffic situation in the city. Despite the fact that there
  is nothing whatsoever to do in the city, citizens still write
  complaints about the amount of time it takes them to get from one
  unexciting location to the next. The committee has been asked to
  figure out how long it takes someone to travel down the streets of
  Shallow Alto given the current traffic light programming. To do this,
  they want you to write an algorithm which, given the speed a car
  travels down a road and the timing of the traffic lights, returns the
  amount of time it takes the car to travel down the street. The traffic
  lights will be in an int[], with each element representing the amount
  of time in seconds between signal changes. Initially, all traffic
  lights have just turned green, and are at the beginning of their
  cycle. The order of the traffic lights in the int[] will be the order
  in which a car encounters them. The speed you will be given is in
  meters per second. Assume that the car starts 150 meters before the
  first traffic light, that there are 150 meters between each traffic
  light, and that the car stops 150 meters after the last traffic light.
  Disregard all acceleration and deceleration; a car is either at its
  given speed or entirely stopped, and it takes no time to go from one
  state to the other. If a car reaches a traffic light just as it turns
  red, it immediately stops and waits for it to turn green again (at
  which point it starts moving immediately). If the light just turned
  green, there is no wait and the car drives on through. Return the
  time, in seconds, that it takes the car to travel the entire distance.
  Round down any fractional parts, (for example 55.5 becomes 55 and 44.9
  becomes 44), but do not do this until returning.

This is my first draft:

public class Car
{
    public double Speed { get;set; }

}

public class Light
{
    public int Number { get; set; }

    public double SwitchTime { get; set; }
    public bool IsGreen(double time)
    {
        double num = Math.Floor(time / SwitchTime);

            return num % 2 == 0;
    }
    public double TimeToWait(double time)
    {
        if (!IsGreen(time))
        {
            return ((time % SwitchTime) < 0.01) ? SwitchTime : (time % SwitchTime);
        }
        else
        {
            return 0;
        }
    }

}

class Traffic
{
    public Car mycar;
    public IList<Light> LightList;
    public static double lengthbetweenLights { get; set; }

    public double getTravelTime()
    {
        double currenttime = lengthbetweenLights / mycar.Speed;

        foreach (Light light in LightList)
        {
            currenttime += lengthbetweenLights / mycar.Speed + light.TimeToWait(currenttime);
        }

        return currenttime;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var car1 = new Car
        {
            Speed = 20
        };
        List<Light> lights1 = getLightList();

        var mytraffic = new Traffic
        {
            mycar = car1,
            LightList = lights1

        };

        Traffic.lengthbetweenLights = 150;

        var traveltime = mytraffic.getTravelTime();

        Console.WriteLine(string.Format("Time for car: {0}", traveltime));
        Console.ReadLine();
    }

    private static List<Light> getLightList()
    {
        List<Light> lstProducts = new List<Light>();
        //input 1
        lstProducts.Add(new Light { Number = 0, SwitchTime = 10 });
        lstProducts.Add(new Light { Number = 1, SwitchTime = 20 });
        lstProducts.Add(new Light { Number = 2, SwitchTime = 30 });
        return lstProducts;
    }

}

You can also see my code on GitHub.

I need to improve my code, make it more OOP and use Design Patterns.

Question is: which design patterns I can use here?


texts: Lookup map for converting Strings into Android `R.raw` integers

texts:
I'm currently working on an Android app and I need to translate keys of type String to Integers which are determined at compile time of R.raw.
Right now I have found two ways of creating such a Map that holds all (needed) values of R.raw:

private static final Map<String, Integer> map = ImmutableMap.<String, Integer>builder()
                                                .put("...", R.raw.id)
                                                 ...
                                                .build();

and

private static final Map<String, Integer> map = new ArrayMap<>();
static {
    map.put("...", R.raw.id);
    ...
}

My questions are:

Are there better ways of creating a Map to lookup keys and return values that are determined at compile time? I don't want to use reflection.
and
Which one of those ways would you prefer?


texts:
I'm trying to return unique items in a Go slice. I've landed on the following, but it seems rather sub-optimal. I'm new to golang (first project in it) and wondering if there's a better way to approach this?

//
// Returns unique items in a slice
//
func Unique(strSlice []string) []string {
    keys := make(map[string]bool)
    list := []string{}
    for _, entry := range strSlice {
        if _, value := keys[entry]; !value {
            keys[entry] = true
            list = append(list, entry)
        }
    }
    return list
}


texts:
I've created a console server which is supposed to update 30 times per second, I'd like you to review it and also I'm curious about the accuracy of the server's loop.

using System;
using System.Diagnostics;
using System.Threading;

namespace ZGServer
{
    class Program
    {
        //------------------Variables------------------------
        double frameInterval = 1000/30;
        Stopwatch msstopwatch = new Stopwatch();
        Stopwatch tpsstopwatch = new Stopwatch();
        int tpscount = 0;
        //---------------------------------------------------
        static void Main(string[] args)
        {
            Program program = new Program();
            program.Server();
        }
        void Server()
        {
            while (true)
            {
                msstopwatch.Start();
                tpsstopwatch.Start();
                if (msstopwatch.ElapsedMilliseconds > frameInterval)
                {
                    tpscount++;
                    //Console.WriteLine(msstopwatch.ElapsedMilliseconds - frameInterval);
                    //Thread.Sleep((int)(msstopwatch.ElapsedMilliseconds - frameInterval));
                    //Console.WriteLine(msstopwatch.ElapsedMilliseconds);
                    msstopwatch.Reset();
                }
                else
                    Thread.Sleep(1);
                if (tpscount == 30)
                {
                    Console.WriteLine(tpsstopwatch.ElapsedMilliseconds);
                    tpscount = 0;
                    tpsstopwatch.Reset();
                }
            }
        }
    }
}

This is the output (It's random every time):

1037, 1038, 1039, 1034, 1037, 1033, 1033, 1034.

This is the amount of time it takes for it to perform 30 loops.

Is this accurate enough for a real-time server over the internet serving multiple clients?


texts: Interp1 linear extrap from Matlab to C++

texts:
I'm trying to implement what I think
griddedInterpolant(X,V,method) is doing inside Interp1.

I get the same results. Please review the extrapolation part as I'm not quite sure about it and comment about the algorithm correctness.

double Model::Interp1(const std::vector<double>& alpha, const std::vector<double>& varSurf, double detail_sensativity)
{
    //in case the interoplation point alraedy exists in the array
    //just return it
    std::vector<double>::const_iterator it = std::find(alpha.begin(), alpha.end(), detail_sensativity);
    if (it != alpha.end())
    {
        int index = it - alpha.begin();
        return varSurf[index];
    }
    else // we need linear interpolation/extrapolation.
    {
        double max = *std::max_element(alpha.begin(), alpha.end());
        double min = *std::min_element(alpha.begin(), alpha.end());
        if (detail_sensativity >= min && detail_sensativity <= max) //interpolate
        {
            for (size_t i = 0; i < alpha.size(); ++i)
            {
                if (detail_sensativity >= alpha[i] && detail_sensativity <= alpha[i + 1])
                {
                    //y = y0 + (y1-y0)*(x-x0)/(x1-x0);
                    double y0 = varSurf[i];
                    double y1 = varSurf[i + 1];
                    double x = detail_sensativity;
                    double x0 = alpha[i];
                    double x1 = alpha[i + 1];
                    double res = y0 + (y1 - y0)*(x - x0) / (x1 - x0);
                    return res;
                }
            }
        }
        else //extrapolate
        {
            //y = y0 + ((x - x0) / (x1 - x0)) * (y1 - y0)
            int i;
            if (detail_sensativity >= alpha.end)
            {
                i = varSurf.end() - varSurf.begin() - 1;
            }
            else
            {
                i = 0;
            }
            double y0 = varSurf[i];
            double y1 = varSurf[i + 1];
            double x = detail_sensativity;
            double x0 = alpha[i];
            double x1 = alpha[i + 1];
            double res = y0 + ((x - x0) / (x1 - x0)) * (y1 - y0);
            return res;
        }
    }
}


texts: Pomodoro countdown timer synced to the clock

texts:
This countdown timer is supposed to:

be synced to the user's clock
at every hour and half hour, will start a 25 minute countdown followed by a 5 minute break

The code works but I question its efficiency.

function startTime() {
    var today = new Date();
    var minutes = today.getMinutes();
    var seconds = today.getSeconds();

    //makes the clock count DOWN instead of up
    if (minutes<25 && seconds<60) {
        document.getElementById("message").innerHTML = "WORK TIME";
        minutes=24-minutes;
        seconds=60-seconds;
    } else if (minutes<30 && seconds<60){
        document.getElementById("message").innerHTML = "BREAK TIME";
        minutes=29-minutes;
        seconds=60-seconds;
    } else if (minutes<55 && seconds<60){
        document.getElementById("message").innerHTML = "WORK TIME";
        minutes=54-minutes;
        seconds=60-seconds;
    } else {
        document.getElementById("message").innerHTML = "BREAK TIME";
        minutes=59-minutes;
        seconds=60-seconds;
    }

    //to make clock show correct format, e.g., 2:59 instead of 03:60
    if (seconds == 60){
      seconds=0;
      minutes=minutes+1;
    }

    document.getElementById('txt').innerHTML=
        minutes+" min and "+seconds+" sec remaining";

}

setInterval(startTime, 1000);
<!DOCTYPE html>


texts:
I'm trying to code Python in an object-oriented style, but it just seems very forced.  Can anyone give me tips on this exercise of calculating the third leg of a right triangle from the other two?

I'm not looking for input santitization help!  I'm aware the project doesn't check if the input is a positive integer (or if the hypotenuse is the longest side, etc), but would much rather improve the general flow of how an OO project should look than the security/sanity checks on user input.

#!/usr/bin/python

import math

#Triangle has three sides; two can be defined and the third is calculated
class Triangle:

    def __init__(self):
        self.side={"adjacent":0,"opposite":0,"hypotenuse":0}

    def define_sides(self):
        for i in self.side:
            self.side[i]=self.get_side(i)

    def print_sides(self):
        for i in self.side:
            print "side",i,"equals",self.side[i]

    #return user integer or None if they enter nothing
    def get_side(self,one_side):
        prompt = "Enter length of "+one_side+": "
        try:
            return input(prompt)
        except SyntaxError:
            return None

    def count_nones(self):
        nones=0
        for side, length in self.side.iteritems():
            if self.side[side] == None:
                nones+=1
        return nones

    def validate_input(self):
        nNones=self.count_nones()

        if nNones < 1:
            print "You must leave one side blank."
            quit()
        if nNones > 1:
            print "Only one side can be left blank."

    def calculate_missing_length(self):
        h=self.side["hypotenuse"]
        a=self.side["adjacent"]
        o=self.side["opposite"]

        #hypotenuse is missing
        if h == None:
            self.side["hypotenuse"] = math.sqrt(a*a+o*o)

        #adjacent is missing
        if a == None:
            self.side["adjacent"] = math.sqrt(h*h-o*o)

        #opposite is missing
        if o == None:
            self.side["opposite"] = math.sqrt(h*h-a*a)

#begin program
triangle=Triangle()
triangle.define_sides()
triangle.print_sides()
triangle.validate_input()
triangle.calculate_missing_length()
triangle.print_sides()


texts:
I have never used std::shared_ptr before and I don't really know how this smart pointer actually works but I decided to create one to verify my knowledge. Here is my code :

namespace myStd
{
    template<class T>
    class shared_ptr
    {
        public :

        shared_ptr() : refCount(nullptr), t(nullptr) {}
        shared_ptr(T *p) : refCount(new int(1)), t(p) {}

        ~shared_ptr()
        {
            this->destroy();
        }

        shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)
        {
            if(p.isvalid())
            {
                refCount = p.refCount;
                t = p.t;

                if(isvalid())
                (*this->refCount)++;
            }
        }

        void destroy()
        {
            if(isvalid())
            {
                --(*refCount);
                if((*refCount) <= 0)
                {
                    delete refCount;
                    delete t;
                }

                refCount = nullptr;
                t = nullptr;
            }
        }

        shared_ptr& operator =(const shared_ptr &p)
        {
            if(this != &p)
            {
                if(!p.isvalid())
                {
                    this->destroy();
                    this->refCount = p.refCount;
                    this->t = p.t;

                    if(isvalid())
                    (*this->refCount)++;

                    return (*this);
                }

                if(!isvalid())
                {
                    this->refCount = p.refCount;
                    this->t = p.t;

                    if(isvalid())
                    (*this->refCount)++;

                    return (*this);
                }
                else
                {
                    this->destroy();
                    this->refCount = p.refCount;
                    this->t = p.t;

                    if(isvalid())
                    (*this->refCount)++;
                }
            }
            return (*this);
        }

        bool isvalid() const {return (t != nullptr && refCount != nullptr);}
        int getCount() const {if(refCount != nullptr) return (*refCount); else return 0;}

        T* operator ->() {return t;}
        T& operator *() {return *t;}

        private :
        int *refCount;
        T *t;
    };
}

What am I missing? Did I implement this smart pointer right?
Your suggestions would be appreciated.


texts:
I would like to get some feed back on my code; the goal is to get all agencies address of banks. I wrote a pretty simple brute force algorithm.
I was wondering if you would have any advice to improve the code, design it differently (do I need an OOP approach here) etc .
import requests
from lxml import html

groupe = "credit-agricole"
dep = '21'
groupes =["credit-agricole"]
deps = ['53', '44', '56', '35', '22', '49', '72', '29', '85']

def get_nb_pages(groupe,dep):
    """ Return nb_pages ([int]): number of pages containing banks information .
    Args:
        groupe ([string]): bank groupe ("credit-agricole",...)
        dep ([string]): departement ("01",...)
    """
    url ="https://www.moneyvox.fr/pratique/agences/{groupe}/{dep}".format(groupe=groupe,dep=dep)
    req = requests.get(url)
    raw_html = req.text
    xpath = "/html/body/div[2]/article/div/div/div[3]/div[2]/nav/a"
    tree = html.fromstring(raw_html)
    nb_pages = len(tree.xpath(xpath)) +1

    return nb_pages

def get_agencies(groupe,dep,page_num):
    """ Return agencies ([List]): description of agencies scrapped on website target page.
    Args:
        groupe ([string]): bank groupe ("credit-agricole",...)
        dep ([string]): departement ("01",...)
        page_num ([int]): target page
    """
    url ="https://www.moneyvox.fr/pratique/agences/{groupe}/{dep}/{page_num}".format(groupe=groupe,dep=dep,page_num=page_num)
    req = requests.get(url)
    raw_html = req.text
    xpath = '//div[@class="lh-bloc-agence like-text"]'
    tree = html.fromstring(raw_html)
    blocs_agencies = tree.xpath(xpath)
    agencies = []
    for bloc in  blocs_agencies:
        agence = bloc.xpath("div/div[1]/h4")[0].text
        rue = bloc.xpath("div/div[1]/p[1]")[0].text
        code_postale = bloc.xpath("div/div[1]/p[2]")[0].text
        agencies.append((agence,rue,code_postale))
    return agencies

def get_all(groupes,deps):
    """Return all_agencies ([List]): description of agencies scrapped.
    Args:
        groupes ([List]): target groups
        deps ([List]): target departments
    """
    all_agencies = []
    for groupe in groupes:
        for dep in deps:
            nb_pages = get_nb_pages(groupe,dep)
            for p in range(1,nb_pages+1):
                agencies = get_agencies(groupe,dep,p)
                all_agencies.extend(agencies)
    df_agencies = pd.DataFrame(all_agencies,columns=['agence','rue','code_postale'])
    return df_agencies

get_nb_pages(groupe,dep)
get_agencies(groupe,dep,1)
df_agencies = get_all(groupes,deps)

```


texts:
I just got into Node.JS and am loving it but I am wondering if I am learning it the right way or using it. This is basically a simple server in Flash but I want to see if am doing it right with handling client connections. This makes a new CurrentPlayer after it gets a login packet and sets the ID and username once they connect.

const net = require('net');

const server = net.createServer((c) => {

    c.on('end', () => {
        console.log('client disconnected');
    });

    c.on('data', function(data) {
        console.log('DATA ' + c.remoteAddress + ': ' + data);
        CheckPacket(data.toString(), c);
    });

    c.on('close', function(data) {
        console.log('CLOSED: ' + c.remoteAddress +' '+ c.remotePort);
    });
});

server.on('connection', function (c) {
    console.log('client connected > ' + c.remoteAddress);
});

server.on('error', (err) => {
    throw err;
});
server.listen(888, () => {
    console.log('Server listening on 888');
});

function CheckPacket(packet, client) {
    if (packet.startsWith("<")) {
        client.write("<cross-domain-policy><allow-access-from domain='*' to-ports='888'/></cross-domain-policy>\0");
    } else {
        var re = /\0/g;
        packet = packet.toString().replace(re, "");
        var json = JSON.parse(packet);
        JsonPacket(json, client);
    }
}

function JsonPacket(json, client) {
    switch (json.type) {
        case 'login':

            client.name = new CurrentPlayer();
            client.name.id = json.id;

            console.log(client.name);

            break;

        default:
            console.log('Unknown json: ' + json);
            break;
    }
}

function CurrentPlayer() {
    this.id = 0;
}


texts: Returning maximum number of consecutive 1s in list of binary numbers

texts:
This is what I implemented in Rust to get the maximum number of consecutive 1s in list of binary numbers.
impl Solution {
    pub fn print_values(nums: Vec<i32>) -> i32{
        let mut result = 0;
        let mut count = 0;
        // let mut end = 0;
        // NotE: Change the if so that it check
         // if 0 else have body for 1 condition

        if nums.len() < 10000 {
            for (index,num) in nums.iter().enumerate() {
                // println!("{}:{}", index, num);
                if *num == 1 && index != nums.len() {
                    count+=1;
                    // println!("count updated to {}", count);
                }else{

                    if count > result {
                        result = count;

                    }
                    count = 0;
                    // println!("count reset to {} from {}", count, result);
                }
                if index == nums.len()-1 && count > 0 {
                    // println!("Last if checked count {} result {}", count, result);
                    if count > result{
                        result = count;
                        count =0;
                    }
                }
            }
            // println!("afeter leaving for loop ending result :{} ", result);
            result

        }else{
            // what's the difference if  we put semicolon here at end or what if not
            panic!("List is too much larger!! Kindly reduce your list.")

        }
    }
}

Though I've accomplished the desired resutl, I guess as long I tested. Kindly review strictly.
How can I improve the speed and memory usage here?


texts: Merge both sql queries into one to get the performance

texts:
Currently i am using 2 queries - one for reattemptdate & one for holddate.... if we  merge both queries & get the results in single query , than will it give better performance? if so how to merge ?

1st query :

$sql = "SELECT employeename, DATE(reattemptdate) as date,
COUNT(*) as count FROM orders
WHERE DATE(reattemptdate)  = CURDATE()
GROUP BY employeename, date";
$results = $db_handle->runSelectQuery($sql);
$numrowsresult =$results[0]['count'];

foreach ($results as $result)
{
    echo $result['employeename'].'|'.$result['date'].'|'.$result['count']."
";
}

echo "
";

2nd query :

$sqla = "SELECT employeename, DATE(holddate) as date,
COUNT(*) as count FROM orders
WHERE DATE(holddate)  = CURDATE()
GROUP BY employeename, date";
$resultsa = $db_handle->runSelectQuery($sqla);
$numrowsresulta =$resultsa[0]['count'];

foreach ($resultsa as $resulta)
{
    echo $resulta['employeename'].'|'.$resulta['date'].'|'.$resulta['count']."
";
}

echo "
";


texts: Wrapper class for adding elements to HashSet

texts:
I have many object of class Test. I want to be sure that among them, there are no two objects o1 and o2 where o1==o2. In order to achieve that, I want to add them all to a HashSet and check if hashSet.size() == numberOfInitialObjects .

In order to ensure that the potential future changes in equals method of the  Test class will not affect my implementation, I wrote a simple wrapper so that instead of adding Test objects to the HashSet, the wrapper objects will be used. The code as such:

private class HashSetWrapper {

        private final Test component;

        public HashSetWrapper(Test component) {
            this.component = component;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 89 * hash + Objects.hashCode(this.component);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final HashSetWrapper other = (HashSetWrapper) obj;
            return this.component == other.component;
        }
    }

Is my approach OK, or are there more suitable ways to achieve my goal?


texts: Replace $number with $number+1 in std::string

texts:
I want to detect $number substring in std::string and then replace it with $number + 1.

For example, the string Hello$9World$1 should become Hello$10World$2.

Here's my code:

#include <iostream>
#include <string>

void modifyDollarNumber(std::string &str)
{
    for (size_t i = str.length(); i --> 0 ;)
    {
        if (str[i] == '$')
        {
            size_t j = i + 1;
            while (j < str.length() && isdigit(str[j]))
            {
                ++j;
            }
            size_t len = j - (i + 1);
            if (len)
            {
                std::string sub = str.substr(i + 1, len);
                int num = std::stoi(sub) + 1;
                str.erase(i + 1, len);
                sub = std::to_string(num);
                str.insert(i + 1, sub);
            }
        }
    }
}

int main()
{
    std::string str = "!$@#$34$1%^&$5*$1$!%$91$12@$3";
    modifyDollarNumber(str);
    std::cout << "Result : " << str << '\n';
}

And I can get the result I want which is

Result : !$@#$35$2%^&$6*$2$!%$92$13@$4
Program ended with exit code: 0

But I want to improve my code so it can be as fast as possible.

How can I simplify modifyDollarNumber() function?


texts:
I've built a fairly simple tip calculator. What I have so far is a bunch of functions to calculate each tip amount and calling each with eventListener.

It works however trying to see if there's a better approach that would modularize the code. I'm thinking possibilities include passing functions as arguments or functions calling other functions but can't figure it out yet.

Here's the code:

var tenPerBtn = document.querySelector('.tenPercent');
var fifteenPerBtn = document.querySelector('.fifteenPercent');
var twentyPerBtn = document.querySelector('.twentyPercent');
var customPerBtn = document.querySelector('.customTipBtn');
var bill = document.getElementById('billInput');
var tipSuggestion = document.getElementById('tipAmount');

function calcTen() {
  var billInput = bill.value;
  var tipAmount = billInput * .1;
  tipSuggestion.innerHTML = 'A ten percent tip would equal $' + tipAmount;
}

function calcFifteen() {
  var billInput = bill.value;
  var tipAmount = billInput * .15;
  tipSuggestion.innerHTML = 'A fifteen percent tip would equal $' + tipAmount;
}

function calcTwenty() {
  var billInput = bill.value;
  var tipAmount = billInput * .2;
  tipSuggestion.innerHTML = 'A twenty percent tip would equal $' + tipAmount;
}

function calcCustom() {
  var billInput = bill.value;
  var customTipAmount = document.querySelector('#customTip').value;
  var tipAmount = billInput * customTipAmount;
  tipSuggestion.innerHTML = 'A ' + customTipAmount + ' percent tip would equal $' + tipAmount;
}

tenPerBtn.addEventListener('click', calcTen)
fifteenPerBtn.addEventListener('click', calcFifteen)
twentyPerBtn.addEventListener('click', calcTwenty)
customPerBtn.addEventListener('click', calcCustom)
Bill Amount: <input type="text" id="billInput">

<button class="tenPercent">Tip 10%</button>

<button class="fifteenPercent">Tip 15%</button>

<button class="twentyPercent">Tip 20%</button>

Custom Tip Percentage: <input type="text" id="customTip"> <button class="customTipBtn">Tip Custom Amount</button>


texts: Discord Bot Python. Selenium screenshots

texts:
I wrote my own Discord Bot which is taking screenshot of a specific website. This scrip is very simple and thought it should work fast, but it isn't. I read a lot, and I think I'm not able to improve it. Today my driver.get(URL) not working fast- i think the website is a little broken. But yesterday I get a result of 10 seconds waiting to get one screenshot. Is there possibility to make it faster?

def taking_screenshot_clearoutsite(new_folder_path, folder, city_coordinates, driver, day=None):
    (latitude, longitude), city_name = city_coordinates
    url = f'https://clearoutside.com/forecast/{latitude}/{longitude}'

    driver.get(url)
    # driver.set_window_position(0, 0)
    # driver.set_window_size(1500, 2000)

    day_now = datetime.datetime.now().date().strftime("%d/%m/%Y")
    day_now_obj = datetime.datetime.strptime(day_now, '%d/%m/%Y')

    """testing window size"""
    # size = driver.get_window_size()
    # print("Window size: width = {}px, height = {}px".format(size["width"], size["height"]))

    try:
        driver.find_element_by_xpath("//*[@aria-label='dismiss cookie message']").click()
        # time.sleep(2)
    except WebDriverException:
        pass

    if day:
        if isinstance(day, int) and int(day) == datetime.datetime.now().day:
            pass
        elif isinstance(day, int) and int(day) != datetime.datetime.now().day:
            searching_day_index = int(day) - day_now_obj.day

            try:
                driver.find_element_by_xpath \
                    (f"//div[@id='day_{searching_day_index}']//div[@class='fc_day_date'][contains(text(),"
                     f"'{day}')]").click()
            except WebDriverException:
                driver.find_element_by_xpath(f"// div[contains(text(),'{day}')]").click()

            """pause 1 second to let page loads"""
            time.sleep(1)
            """save screenshot and return name of it to crop"""
            screen_file_name = screenshot(driver, folder)
            file = Image.open(screen_file_name)
            top_add = searching_day_index * 100
            bottom_add = searching_day_index * 100
            final_photo = cropping_file(file, new_folder_path, CLEAROUTSITE_CROP_PARAM,
                                        city_day=(city_name, int(day)), top_add=top_add, bottom_add=bottom_add)
            os.remove(screen_file_name)
            return final_photo
        else:

            try:
                driver.find_element_by_xpath(f"//div[@id='day_{0}']//div[@class='fc_day_date'][contains(text(),"
                                             f"'{datetime.datetime.now().day}')]").click()
            except WebDriverException:
                pass

    """pause 1 second to let page loads"""
    time.sleep(1)
    """save screenshot and return name of it to crop"""
    screen_file_name = screenshot(driver, folder)
    file = Image.open(screen_file_name)
    final_photo = cropping_file(file, new_folder_path, CLEAROUTSITE_CROP_PARAM, city_day=(city_name, day))
    os.remove(screen_file_name)
    return final_photo

driver = start_driver()
(city_coordinates), country = find_city_coordinates('elblag')
taking_screen_shot_clearoutsite('Z:\Python\Rozne_programy\Discord\saving_to_disc_task\clear\elblag',
                                'Z:\Python\Rozne_programy\Discord\saving_to_disc_task',
                                city_coordinates, driver, 21)


texts: Group similar objects into array of arrays

texts:
I have the following code, that groups similar todos into an array of arrays, using lodash (https://lodash.com). Here is a plnkr http://plnkr.co/edit/t4J5bKGjMlQxW2z9Zh7x?p=preview (open your console and look into script.js)

function Todo(value) {
  this.value = value;
  this.isSimilar = function(todo) {
    return this.value == todo.value;
  };
}

var _data = [
  new Todo("hello"),
  new Todo("world"),
  new Todo("foo"),
  new Todo("bar"),
  new Todo("hello")
];

var processedTodos = [];
var groups = _.compact(_.map(_data, function(todo) {
  if(processedTodos.indexOf(todo)>-1) {
    return;
  }
  var similarTodos = _.filter(_data, function(todo2) {
    return todo!==todo2 && todo.isSimilar(todo2);
  });
  similarTodos.unshift(todo); // prepend todo to front of array
  [].push.apply(processedTodos, similarTodos);
  return similarTodos;
}));

console.log(groups);

groups contains an array of arrays, where similar todos are in the same array.

For example, when I input this (these are JS objects, but for the sake of readability in JSON):

[
  {"value":"hello"},
  {"value":"world"},
  {"value":"foo"},
  {"value":"bar"},
  {"value":"hello"}
]

It returns this:

[
  [{"value":"hello"},{"value":"hello"}],
  [{"value":"world"}],
  [{"value":"foo"}],
  [{"value":"bar"}]
]

It groups together similar objects.

But the whole code doesn't feel right, there must be a better way to do this!

Another bad thing is that I need an additional array to store the already checked todos (which avoid me duplicate arrays like [todo1,todo2] and [todo2,todo1].

Last but not least, I have to remove undefined values from the array with _.compact, because this line returns undefined when the todo was already processed:

  if(processedTodos.indexOf(todo)>-1) {
    return;
  }

Any idea how to improve this code?


texts:
I'm looking for feedback on things that can be streamlined in each section. The data it creates is all needed whether it's used in a graph or not so I can't get rid of anything, just combine steps maybe.

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
data = pd.read_csv("C:\\Users\\eb2547\\Desktop\\python code for work\\2017 TB.csv")

# Scrap separation
noNan = data[['Quantity','Scrap Cause']].dropna()
scrap = noNan.groupby('Scrap Cause').sum()

# Hanging production
hangdata = data[(data['Transaction Description'].str.contains('INVM') == True) &
                (data['Location No'] == 'SF HANK STAGING')]
hangprod = hangdata['Quantity'].sum()

# Tapered production

# Wrapper production
wrapdatatobug = data[(data['Transaction Description'] == 'INVM-ISS') &
                (data['Location No'].str.contains('BUG') == True)]
wrapprodtobug = wrapdatatobug['Quantity'].sum()
wrapdatatobox = data[(data['Transaction Description'] == 'OOREC') &
                     (data['Location No'].str.contains('BOX ASSEMBLY-WRAP') == True)]
wrapprodtobox = wrapdatatobox['Quantity'].sum()
wrapscrap = data[(data['Scrap Cause'].str.contains('W') == True)]
wrapscraptotal = wrapscrap['Quantity'].sum()
wrapprodtotal = wrapprodtobug + wrapprodtobox

# Cut Piece production
cpdata = data[(data['Transaction Description'] == 'OOREC') &
               (data['Location No'].str.contains('BOX ASSEMBLY-CP') == True)]
cpprod = cpdata['Quantity'].sum()
cpscrap = data[(data['Scrap Cause'].str.contains('C') == True)]
cpscraptotal = cpscrap['Quantity'].sum()

# Graphs of scrap data
wrapscrap2 = scrap[(scrap.index.str.contains('W') == True)]
cpscrap2 = scrap[(scrap.index.str.contains('C') == True)]
spinscrap = scrap[(scrap.index).str.contains('S') == True]
def Wrap_Scrap():
    fix, ax = plt.subplots(figsize=(10,4))
    sns.barplot(data=wrapscrap2,x=wrapscrap2.index,y='Quantity')
def CP_Scrap():
    fix, ax = plt.subplots(figsize=(10,4))
    sns.barplot(data=cpscrap2,x=cpscrap2.index,y='Quantity')

# Graph of production
prodoverview = pd.DataFrame([hangprod,wrapprodtotal,cpprod],
                            index=['Hanging','Wrapping','CP'],
                            columns=['Quantity'])
def Prod_Graph():
    fix, ax = plt.subplots(figsize=(10,4))
    sns.barplot(data=prodoverview,x=prodoverview.index,y='Quantity')


texts: Find The Triangular Number With More Than N Divisors

texts:
My code is a general solution to the following problem from Project Euler #12:

  What is the value of the first triangle number to have over five hundred divisors?

MY CODE

#include <iostream>
int generate_triangular(int n);
int enumerate_divisors(int n);
int main()
{
    std::cout<<"You want to find the first triangular number with less than or more than how many divisors? "<<std::endl;
    int user_input;
    std::cin>>user_input;
    bool result_found = false;
    int test_number = 1;
    int target;
    while(!result_found){
        int factor_count = enumerate_divisors(generate_triangular(test_number));
        if(factor_count < user_input){
            test_number++;
        }else{
            result_found = true;
            target = generate_triangular(test_number);
        }
    }
    std::cout<<"The "<<test_number<<" th triangular number"<<std::endl;
    std::cout<<target<<std::endl;
}
int generate_triangular(int n){
    return (n*(n+1))/2;
}
int enumerate_divisors(int n){
    int divisor_count = 0;
    for(int i = 1;i*i <= n;i++){
        if(n%i == 0){
            divisor_count++;
        }
    }
    return 2*divisor_count;
}

I found my solution to be quite fast for the purposes of the question (it found the first triangular number with over 500 divisors in about .2 seconds). Wondering how I can make it faster, and about any general code suggestions to be made.


texts:
I've created a System.Threading.Timer wrapper in C#. The tasks to be triggered when the timer elapses have highly variable execution times. My design criteria are:

Provide a strongly typed timer state in the callback
Run the timer callback on a periodic basis
If the timer's period elapses before the timer callback completes

Do not run the timer callback a second time in parallel
Run time timer callback again immediately after the running callback completes

Do not run the timer callback more than once per period

As an example, given a timer that elapses every 3 seconds:

3s  - Timer elapse triggers task
6s  - Timer elapse triggers task, but task does not run because      the previous run is not complete
9s  - Timer elapse triggers task, but task does not run because      the previous run is not complete
10s - Task finishes running
10s - Task immediately runs again because the previous run crossed      a period boundary
11s - Task finishes running
12s - Timer elapse triggers task

I ended up with the following class:

public class NonOverrunningTimer<TState>
{
    private readonly Func<TState, TState> _delegate;
    private readonly TimeSpan _interval;
    private readonly System.Threading.Timer _timer;

    public NonOverrunningTimer(Func<TState, TState> @delegate, TimeSpan interval, TState initialState = default(TState))
    {
        if (interval == TimeSpan.Zero)
        {
            throw new Exception($"Cannot initialize a timer with a period of {TimeSpan.Zero}");
        }

        State = initialState;
        _delegate = @delegate;
        _interval = interval;
        _timer = new System.Threading.Timer(UntypedCallback, null, TimeSpan.Zero, interval);
    }

    public TState State { get; private set; }

    private volatile bool _running;
    private volatile bool _waiting;
    private readonly object _executeLock = new object();
    public void UntypedCallback(object state)
    {
        if (_running && _waiting)
        {
            return;
        }

        if (_waiting && !_running)
        {
            _waiting = false;
        }

        if (_running)
        {
            _waiting = true;
            return;
        }

        using (var @lock = new TryLock(_executeLock))
        {
            if (!@lock.HasLock)
            {
                return;
            }

            _running = true;

            State = _delegate(State);

            _running = false;
            if (_waiting)
            {
                _waiting = false;
                _timer.Change(TimeSpan.Zero, _interval);
            }
        }
    }

    private class TryLock : IDisposable
    {
        private object _locked;

        public bool HasLock { get; private set; }

        public TryLock(object obj)
        {
            if (Monitor.TryEnter(obj))
            {
                HasLock = true;
                _locked = obj;
            }
        }

        public void Dispose()
        {
            if (!HasLock)
            {
                return;
            }

            Monitor.Exit(_locked);
            _locked = null;
            HasLock = false;
        }
    }
}

I'm interested in general feedback as well as whether something like this already exists in the BCL/Framework libraries and I just missed it.


texts:
I thought that developing an app in Python should be easier than learning Java. I finally got my isprime app to work but it looks ugly. When I write GUI code I always find myself typing in very long code. This is not Code Golf for sure, but 70 lines for such a simple app is too much in opinion. The shorter (reasonably) a programme is, the easier it is to debug.

This app gives the user a text input and a button, and clicking the button will tell the user whether or not the number entered is prime.

That said, if you own an Android device you can download the app (.apk) here. Please tell me about any improvements.

import time
import random
from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.uix.popup import Popup
from kivy.core.window import Window

class IsprimeApp(App):

    def build(self):

        def avg(lst):
            return sum(lst) / len(lst)

        def get_font(size):
            return str(avg(Window.size) / (10 - size)) + "sp"

        parent = BoxLayout(orientation="vertical")
        number_input = TextInput(
            text=str(random.randint(5, 10 ** 10)), font_size=get_font(3))
        parent.add_widget(number_input)
        btn = Button(text='Is prime?', font_size=get_font(3))

        def callback(instance):
            def isprime(n):
                MAX_TIME = 1
                WRONG_TYPE = "Enter a number"
                MAX = 10 ** 17
                TOO_BIG = "The number must be less than 10^17"
                NO = "No, {} is not prime".format(n)
                YES = "Yes, {} is prime".format(n)
                try:
                    n = int(n)
                except:
                    return WRONG_TYPE
                if n > MAX:
                    return TOO_BIG
                if n in (0, 1):
                    return NO
                if n % 2 == 0 and n != 2:
                    return NO
                upper_limit = int((n ** 0.5) + 1)
                for i in range(3, upper_limit, 2):
                    if n % i == 0:
                        return NO
                return YES

            content = BoxLayout(orientation="vertical")
            content.add_widget(
                Label(text=str(isprime(number_input.text)),
                      font_size=get_font(-15)))
            dismiss = Button(text="OK", font_size=get_font(2))
            content.add_widget(dismiss)
            popup = Popup(title='Is the number prime?',
                          content=content,
                          size_hint=(1, 1),
                          font_size=get_font(2))
            dismiss.bind(on_press=popup.dismiss)
            popup.open()

        btn.bind(on_press=callback)
        parent.add_widget(btn)
        return parent

if __name__ in ('__main__','__android__'):
    IsprimeApp().run()


texts: File path unified in Windows/MacOS/Linux

texts:
We are all tremendously happy about back slashes in Windows file systems and do not think that their sole purpose is to make life complicated for smart people who are capable of using different OS. Upvote if disagree [ :) ].

Converting paths from/to Windows backward slashes is a pretty monotonous task. Here is a library class to help with it. GitHub

OSPath path = @"/foo\bar.txt";

// Windows output
WriteLine(path);            // \foo\bar.txt
WriteLine(path.Windows);    // \foo\bar.txt
WriteLine(path.Unix);       // /foo/bar.txt

// MacOS output
WriteLine(path);            // /foo/bar.txt
WriteLine(path.Windows);    // \foo\bar.txt
WriteLine(path.Unix);       // /foo/bar.txt

It also helps converting between relative and absolute paths:

OSPath ap = "/foo/bar";
WriteLine(ap.Relative.Unix); // foo/bar
WriteLine(ap.Absolute.Unix); // /foo/bar

OSPath rp = "foo/bar";
WriteLine(rp.Relative.Unix); // foo/bar
WriteLine(rp.Absolute.Unix); // /foo/bar

And to perform path arithmetic (Windows output):

OSPath root = @"/foo\bar";
WriteLine(root + "file.txt");        // \foo\bar\file.txt
WriteLine(root + "file.txt" - root); // file.txt

Library class is:

public class OSPath
{
    public static readonly OSPath Empty = "";

    public static bool IsWindows => DirectorySeparatorChar == '\\';

    public OSPath(string path)
    {
        Path = path.Trim();
    }

    public static implicit operator OSPath(string path) => new OSPath(path);
    public static implicit operator string(OSPath path) => path.Normalized;
    public override string ToString() => Normalized;

    protected string Path { get; }

    public string Normalized => IsWindows ? Windows : Unix;
    public string Windows => Path.Replace('/', '\\');
    public string Unix => Volumeless.Path.Replace('\\', '/');

    public OSPath Relative => Volumeless.Path.TrimStart('/', '\\');
    public OSPath Absolute => IsAbsolute ? this : "/" + Relative;

    public bool IsAbsolute => IsPathRooted(Path);
    public bool HasVolume => IsAbsolute && Path[1] == ':';
    public OSPath Volumeless => HasVolume
        ? (this - GetPathRoot(Path)).Absolute
        : this;

    public OSPath Parent => GetDirectoryName(Path);

    public bool Contains(OSPath path) =>
        Normalized.StartsWith(path);

    public static OSPath operator +(OSPath left, OSPath right) =>
        new OSPath(Combine(left, right.Relative));

    public static OSPath operator -(OSPath left, OSPath right) =>
        left.Contains(right)
        ? new OSPath(left.Normalized.Substring(right.Normalized.Length)).Relative
        : left;
}


texts: Scala TryWith that closes resources automatically

texts:
I'm quite new to Scala and was surprised that there doesn't seem to be anything like Java's try-with-resources block. So of course I wrote my own little construct. Is there anything I could improve?

import scala.util.control.NonFatal
import scala.util.Try
import scala.util.Failure
import scala.util.Success

object TryWith {
  def apply [Closable <: { def close() }, Result]
      (resGen: => T) (r: (Closable) => Result): Try[Result] = {

    Try(resGen) match {
      case Success(closable) => {
        try Success(r(closable)) catch {
          case NonFatal(e) => Failure(e)
        } finally {
          try {
            closable.close()
          } catch {
            case e: Exception => {
              System.err.println("Failed to close Resource:")
              e.printStackTrace()
            }
          }
        }
      }
      case Failure(e) => Failure(e)
    }
  }
}

Examples:

val res = TryWith(Source.fromFile("foo.bar")) {
  _.mkString
}

res match {
  case Success(str) => println(str)
  case Failure(e) => e.printStackTrace()
}

--

TryWith(new BufferedReader(new FileReader("foo.bar")))((reader)=> {
  var line = reader.readLine()
  while(line != null) {
    println(line)
    line = reader.readLine()
  }
})

Right now there is no way to react to or even detect a failed attempt to close the resource. I can see four ways to make that possbile but I'm not that happy with any of them:

Instead of catching the Exception, let it through. It can now be dealt with but kind of defeats the purpose of the whole TryWith block.
Return a Failure[Result] if closing fails. I don't like this because the action was actually a success and there is a valid result. By returning a Failure that result is lost.
Return a pair of Trys, i.e. (Try[Result], Try[Unit]). The first one is the result of the operation, the second one is the result of the closing.
Pass a (Closable) => Unit error handler as argument. This would also allow trying to close the resource again (which most likely won't change anything though).

Is handling a failed close even important enough to think about? I know it can happen but usually there is no way to recover from it.


texts: Filtering a DataFrame based on two logical conditions, first one numpy array values, second one current day based

texts:
The following is just a working example.
I have a DataFrame containings a monotonous growing function.
Some of the values are actuals, some are forecasted.
I need to filter specific actuals values based on a set of milestones and I have to avoid to take forecasted values from the dataframe
I created this following script.
It works, but I think is not so much pythoninc.
I am a self taught and my working eviroment is Google Colab
Expected Output

I would avoid the for loop and the if condition

Understand if there is room of improvement in the code quality
#importing libraries
import pandas as pd
import numpy as np
import datetime

#working code mock-up
th_array = np.arange(0, 11000, 1000)
cumulated_array = np.arange(0, 5000, 185)

df_index = pd.date_range(end = "20/04/2021",
                         periods = len(cumulated_array))
df = pd.DataFrame(data = cumulated_array,index = df_index,
                columns = ["cumulated"])

df_filtered = pd.DataFrame()
current_day =  pd.to_datetime(datetime.date.today())

#filtering loop
for y in th_array:
  x = df[(df['cumulated'] > y) & (df.index < current_day)]
  if x.empty is False:
      df_filtered = df_filtered.append(x.iloc[0])


texts: Creating multiple DOM buttons in JavaScript (I am not DRYing)

texts:
I am making a Tic-tac-toe game and I have the basic board but I am repeating the code and it is very badly written. I am wondering how I can use better practices to write the DOM elements that I need.

I am referring to the function boardController.buildBoard() which can be found here:

https://github.com/robbiesoho/TTTJS/blob/master/assets/js/script.js

There are nine buttons and here are the first two

const boxOne = document.createElement('div');
    boxOne.classList.add('boxOne');
    const buttonOne = document.createElement('button')
    buttonOne.classList.add("button")
    buttonOne.setAttribute('type', 'button');
    buttonOne.addEventListener('click', () => {
      boxOne.classList.add('token');
      boxOne.textContent =  playerController.activePlayer;
      boardController.board[0] =  playerController.activePlayer;

      gameController.afterButtonIsPressed();
      gameController.winnerAction;

    });

    const boxTwo = document.createElement('div');
    boxTwo.classList.add('boxTwo');
    const buttonTwo = document.createElement('button')
    buttonTwo.classList.add("button")
    buttonTwo.setAttribute('type', 'button');
    buttonTwo.addEventListener('click', () => {
      boxTwo.classList.add('token');
      boxTwo.textContent =  playerController.activePlayer;
      boardController.board[1] =  playerController.activePlayer;

      gameController.afterButtonIsPressed();
      gameController.winnerAction;

    });

I am new to JS and know only enough to know that this is not a good way to write this. Thank you in advance


texts: Uppercase the initial char of every string in a list

texts:
My problem is that I have a sequence, potentially infinite, of strings. Let's suppose it to be

{"Mickey Mouse", "Bugs Bunny", "Winnie the Pooh"}

I have to make an exthension-method Initials that returns a sequence of their capital letters in uppercase, so in this case, doing:

var names = new string [] {"Mickey  Mouse", "Bugs    Bunny", "Winnie  the Pooh"}
foreach (var cl in names . Initials ())
Console.WriteLine(cl);

returns, in order, MM, BB, WTP. Note that whitespaces have not to be considered.

After hours of staring at the screen, i managed to write this not so goodlooking code:

public static IEnumerable<string> Initials(this IEnumerable<string> names)
{
    var res = new List<string>();
    var  listOfArrayOfStrings = names.Select(s => s.Split());
    foreach (var arrayOfStrings in listOfArrayOfStrings)
    {
        string newString = "";
        foreach (var singleString in arrayOfStrings)
        {
            if (!string.IsNullOrWhiteSpace(singleString)) //no whitespaces
            {
                var temp =  char.ToUpper(singleString[0]).ToString();       //first upper String
                newString += temp;
            }
        }
        res.Add(newString);
    }
    return res;
}

Then, my disliked R# suggested me to do some refacory and then it became the following:

var  listOfArrayOfStrings = names.Select(s => s.Split());
            return listOfArrayOfStrings.Select(arrayOfStrings =>
                (from singleString in arrayOfStrings
                 where !string.IsNullOrWhiteSpace(singleString)
                 select char.ToUpper(singleString[0]).ToString())
                 .Aggregate("", (current, temp) => current + temp))
                 .ToList();

Now, I have two questions about this:

Is this, in your opinion, a good way to reach my aim?
I will have to do a written test where I'll have to do something like that. How can I "guess" something like that without R#? I mean, I'm still having difficulties understanding all that Linq stuff. Have you got any idea to how I can approach problems like this? Often these test are about managing IEnumerables, so Linq could be very helpful, but I rarely understand the right sequence of Linq queries.


texts: Review the code to copy List of custom class to another list of Custom class

texts:
Thanks for the Reply.

Here is the actual Scenario
My application received the data from a backend in the form of a class object ie.

public class FlowObject {
private String id;
private List<FlowStep> flowlSteps;
private List<String> audRefs;

}

Now FlowStep class as mentioned above is

public class FlowStep {

private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}

}

Now since Backend code is NOT ready Im writing the dummy implementation of backend FlowObject Class at my Side whose data gets copied to my local Class FlowCopy
Thats why I need to write both FlowObject and FlowCopy Classes

Now My Backend Dummpy Implemetation of FlowObject is as below

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FlowObject {
    private String id;
    private List<FlowStep> flowlSteps;
    private List<String> audRefs;
    public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public List<FlowStep> getFlowSteps() {
            return flowlSteps;
        }
        public void setFlowSteps(List<FlowStep> flowlSteps) {
            this.flowlSteps= flowlSteps;
        }
        public List<String> getAudRefs() {
            return audRefs;
        }
        public void setAudRefs(List<String> audRefs) {
            this.audRefs = audRefs;
        }
}

And public class FlowStep {

private String id;

 public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}

}

and my local FlowCopy Class is as below

public class FlowCopy {
    private String id;
    private List<FlowStep> flowSteps;
    private List<String> audRefs;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<FlowStep> getFlowSteps() {
        return flowSteps;
    }
    public void setFlowlSteps(List<FlowStep> flowSteps) {
        this.flowSteps= flowSteps;
    }
    public List<String> getAudRefs() {
        return audRefs;
    }
    public void setAudRefs(List<String> audRefs) {
        this.audRefs = audRefs;
    }
}

Now my intention is to Copy the Custom FlowObject Class to a list of FlowCopy which will be used in application

public List<FlowCopy> getFlow(  List<FlowObject > obj  ){
       List<FlowCopy> flowRes = new ArrayList<FlowCopy>(obj.size());
       for (FlowObject object:obj)
       {
           FlowCopy  callFlow = new FlowCopy();
           callFlow.setId(object.getId());
           callFlow.setAudioRefs(object.getAudRefs());
           callFlow.setCallSteps(object.getFlowSteps());
           flowRes .add(callFlow);

       }
     return flowRes ;
   }

Please review the above implemetation and suggest a suitable approach


texts: HackerRank Caesar Cipher, not using map, filter, reduce, regex

texts:
Julius Caesar protected his confidential information by encrypting it in a cipher. Caesar's cipher rotated every letter in a string by a fixed number, K, making it unreadable by his enemies. Given a string,S , and a number, K , encrypt S.

Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.

func cipher(messageToCipher: String, k: Int)-> String{
  var  eMessage = ""
  let arr = messageToCipher.characters.map { String($0) }
  for ch in arr {
    for code in String(ch).utf8 {
        if (65<=code && code<=90) || (97<=code && code<=122) {
              if k > 26{
                    let value =  k % 26 == 0 ? k / 26 : k % 26
                    var pCode  = ((Int(code))  + (value))

                    if (pCode  > 122 && (97<=code && code<=122)) || (pCode  > 90 && (65<=code && code<=90)) {
                        pCode = pCode - 26
                    }

                   let s = String(UnicodeScalar(UInt8(pCode)))
                   eMessage = eMessage + s
                }else
                {
                    var pCode  = Int(code) + k

                    if (pCode  > 122 && (97<=code && code<=122)) || (pCode  > 90 && (65<=code && code<=90)) {
                        pCode = pCode - 26
                    }

                   let s = String(UnicodeScalar(UInt8(pCode)))
                   eMessage = eMessage + s
                }

        }
        else{
            eMessage = eMessage + ch
        }
    }
  }
  return eMessage
}

print(cipher(messageToCipher: "abc", k: 2) )

I solved this way and it was passed all test cases.

More information on this problem: Caesar Cipher


texts: jQuery "on('click')" to toggle webpage content

texts:
I have made a successful test page that satisfies my goals of using JavaScript ( jQuery specifically ) to add and remove content from a webpage.

<!doctype html>

<title>test</title>

For this simple example where only two possible outcomes exist the code isn't too bad to look at, however I know that if this were inflated to what a full website can entail (e.g. dozens of links per page, each one putting in different content) the .on(click) chain would get very complicated.

How else could I handle this situation?

I know that I could just make two different .html files ( foo and bar ) and setup simple anchor links (i.e. ) between them and obtain the same effect but my goal is to have an external source generate the content that is displayed.

I am getting used to JavaScript programming in general so please do point out other ways I can improve what I am doing.


texts:
I'm currently taking a JavaScript class. I'm fairly familiar with JavaScript and coding in general, so I decided to teach myself functional programming on the side. It's been great, my teacher's fine with it. However he doesn't really know much about functional programming, so it's difficult for him to critique my designs. I want to be developing good habits and practices, but so far it's been difficult.

Disclaimer: I am aware that JavaScript isn't the ideal language for functional programming for a variety of reasons, but it's what I have to use for now. Also, I can't use jQuery yet.

My current project is a simple program that just displays an investment and its total over x number of years. What I've written works, but if there's a better way to do things I'd like to learn it. I'd like to become the best programmer I can.

Anyways, here's my code:

function inputMask(source, mask = (x) => x) {
    const input = source();
    if (input === null) {
        return;
    };
    const match = mask(input);
    if (match === null) {
        return;
    };
    if (match === undefined) {
        return inputMask(source,mask);
    } else {
        return match;
    };
}

function investment() {
    const investmentAmount = inputMask(() => prompt("How much would you like to invest?"), function(x) {
        const value = parseInt(x);
        if (isNaN(value)) {
            return alert("[ "+x+" ] "+"is not a number.");
        }

        if (value <= 0) {
            return alert("Input must be greater than 0, [ "+value+" ] is not.");
        }

        return value.toFixed(2);
    })

    const investmentYears = inputMask(() => prompt("How many years would you like to invest?"), function(x) {
        const value = parseInt(x);
        if (isNaN(value)) {
            return alert("[ "+x+" ] "+"is not a number.");
        }

        if (value <= 0 || value != value.toFixed(0)) {
            return alert("Input must be an integer greater than 0, [ "+value+" ] is not.");
        }

        return value.toFixed(2);
    })

    const response = (function recur(amount = investmentAmount, accu = "", iterations = investmentYears, i = 0) {
        if (i > iterations) {
            return accu;
        }

        const string = "Year "+i+": $"+amount+"\n";

        return recur((amount*1.08).toFixed(2), accu+string, iterations, i+1);
    })()

    alert(response);

    if(confirm("Again?")) {
        return investment();
    }
}

investment();


texts: Clubbing three queries that return mutually exclusive records


texts:
I have a library with two methods: one takes an object and vararg strings, the other takes a default value as well.

They are currently implemented as:

export default class koalaesce {
    static get(base, ...steps) {
        return koalaesce.getDefault(base, null, ...steps);
    }

    static getOrThrow(base, ...steps) {
        return // long impl;
    }

    static getDefault(base, def, ...steps) {
        try {
            return koalaesce.getOrThrow(base, ...steps);
        } catch (e) {
            if (e.constructor === MissingLinkError || e.constructor === NullLinkError) {
                return def;
            } else {
                throw e;
            }
        }
    }
}

and would be called like:

get(obj, "foo", "bar", "baz")
getDefault(obj, 9, "foo", "bar", "baz")

I feel weird splitting up the base and args with the default value, but I'm not sure if putting the default value first is appropriate:

getDefault(9, obj, "foo", "bar", "baz")

Since the base object and args are related, this seems more reasonable, but I don't think I've seen the default value come first in a case like this (most often, they come last, but that and varargs seems like lousy API design).

Is there an idiomatic way to do this, for Javascript or in general? If so, what is the reasoning behind that?


texts: Outlook VSTO: Fastening email loop on a large pst file

texts:
In a Outlook VSTO Addin I needed to loop through a large pst file (e.g 30GB containing 50k+ mails). Following code block loop the pst file folder by folder recursively. It takes huge time (1hour+) to complete the loop especially when looping such large pst file for the first time.

The purpose of this code is to get the PR_SEARCH_KEY and the FolderPath of each email (folder wise) and store them in text file which will be used in future, such as in a periodic full loop we can compare the old and new PR_SEARCH_KEY to find out the new emails etc

How can I get a faster performance in this.

Const PropName As String = "http://schemas.microsoft.com/mapi/proptag/0x300B0102"
Dim SourceFolder = Outlook.NameSpace.Folders("Outlook_Backup")
Dim PstName = "Outlook"
Dim MailCount = FunctionToGetTotalMailCount(SourceFolder)
Dim PrSearchKeyDictionary As New List(Of String)

ScanPST(SourceFolder,PstName,MailCount)

Public Sub ScanPST(f As Outlook.Folder, PstName As String, MailCount As Long)
'-========================================================================
'- f = RootFolder/PST with Tag (e.g Outlook_Backup), PstName (e.g Outlook)
'-========================================================================
If f.Items.Count > 0 Then
    For i = f.Items.Count To 1 Step -1
        LoopCount += 1
        Try
            Dim Mail As Object = f.Items(i)
            Dim PropertyAccessor As Outlook.PropertyAccessor = Mail.PropertyAccessor
            Dim PrSearchKey As String = PropertyAccessor.BinaryToString(PropertyAccessor.GetProperty(PropName))

            '/Full folder path splited into array and removed the rootfolder name with tag (e.g Outlook_Backup -> _Backup is the tag)
            Dim FolderPath() As String = f.FolderPath.TrimStart("\"c).Split("\").Skip(1).ToArray

            '/Array joined back to get MailFolderPath without tag
            Dim MailFolderPath As String = String.Join("\", FolderPath)

            PrSearchKeyDictionary.Add(PrSearchKey & "," & PstName & "\" & MailFolderPath)
            Marshal.ReleaseComObject(PropertyAccessor)
        Catch ex As Exception
            LogInput("[Error: " & ex.ToString & "]"
            Continue For
        End Try
        BGWorkerStatus = "[" & PstName & "] " & "Scanning... " & Math.Round((LoopCount / MailCount) * 100, 2, MidpointRounding.AwayFromZero) & "%"
        BackGroundWorker.ReportProgress(0, BGWorkerStatus)
    Next
End If
If f.Folders.Count > 0 Then
    For c = 1 To f.Folders.Count
        OL.Folder = f.Folders.Item(c)
        ScanPST(OL.Folder, PstName, MailCount)
    Next
End If
End Sub


texts: Automate html file editing with python - Change the author

texts:
Hello I would like to use python to change the author of an html file, in order to do so I have written a few lines.

First I have used the HTMLParser class from the standard library to make a class that indicates which line of the html page needs to be changed.

from html.parser import HTMLParser

class AuthorFinder(HTMLParser):
    def __init__(self):
        super().__init__()
        self._edition_line = None

    def handle_starttag(self, tag, attrs):
    '''
    If the tag handled is the meta tag containing the author's name, then
    the value of _edition_line will be set to the current line (starting from 0)
    '''
    if tag.lower() == 'meta':
        for a_tuple in attrs:
            name, value = (field.lower() for field in a_tuple)
            if name == 'name' and value == 'author':
                # getpos() returns (line, column) starting from (1, 1)
                # whereas I want the first index to be 0.
                self._edition_line = self.getpos()[0] - 1

    @property
    def edition_line(self):
        return self._edition_line

I then use that class to get the line of the meta tag that contains the author. The following function changes the whole line and return and the new html page as a string.

def change_author(html_code, author):
    html_parser = AuthorFinder()
    html_parser.feed(html_code)
    author_line = html_parser.edition_line
    html_lines = html_code.splitlines()
    new_tag = '<meta name="author" content="{}">'.format(author)
    html_lines[author_line] = new_tag
    new_html = '\n'.join(html_lines)
    return new_html

From there you can easily change the author of several html files with something as simple as this:

# put the path to your html files in here
html_files = ['example1.html', 'example2.html']
new_author = 'Mario Luigi'
for filename in html_files:
    with open(filename, 'rt') as f:
        html_code = f.read()
    new_code = change_author(html_code, new_author)
    new_filename = '{}-NewAuthor.html'.format(filename.split('.')[0])
    with open(new_filename, 'w') as f:
        f.write(new_code)

Here is my first, quick attempt at automating file editing. I would like, in the future, to automate more changes but for now let's focus on this one. The script works fine but I'm pretty sure it can be improved in several ways as:

the class AuthorFinder will keep on parsing even though the desired meta tag has been found
if no meta tag with the author's name has been found, no author will be added
the previous indentation is ignored
...

I will try to find ways to improve this, and hope to get suggestions from here as well. Thank you for reading, and good day.


texts:
I am trying to resolve following problem. Please advice which part of the code can be improved.
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Example:
Given the below binary tree and sum = 22,
      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct stTree
{
    struct stTree * left;
    struct stTree * right;
    int value;
} stTree;

struct stTestCase
{
   stTree *root;
   int sum;
   bool result;
};

stTree* createNode(int value, stTree *leftNode, stTree *rightNode)
{
    stTree *node = malloc(sizeof *node);
    if (!node) abort();
    node->left = leftNode;
    node->right = rightNode;
    node->value = value;
    return node;
}

bool hasPathSum(const stTree *root, int sum)
{
    if (!root) return false;

    if (!root->left && !root->right)
    {
        if (sum == root->value)
            return true;
        else
            return false;
    }
    return (hasPathSum(root->left, sum - root->value)
      | hasPathSum(root->right, sum - root->value));
}

static stTree* findBottomLeft(stTree *node)
{
    while (node->left)
        node = node->left;
    return node;
}

void freeTree(stTree *node)
{
    if (!node) return true;
    stTree *bottomLeft = findBottomLeft(node);

    while (node)
    {
        if (node->right)
        {
            bottomLeft->left = node->right;
            bottomLeft = findBottomLeft(bottomLeft);
        }
        stTree *old = node;
        node = node->left;
        free(old);
    }
}

int main(void)
{

   struct stTestCase test_cases[3]={
        {
           createNode(5,
            createNode(4,
                createNode(11,
                    createNode(7, NULL, NULL),
                    createNode(2, NULL, NULL)), NULL),
            createNode(8,
                createNode(13, NULL, NULL),
                createNode(4, NULL,
                    createNode(1, NULL, NULL)))),
            22,
            true
         },
         {
            createNode(5,
             createNode(1,
                 createNode(11,
                     createNode(3, NULL, NULL),
                     createNode(2, NULL, NULL)), NULL),
             createNode(7,
                 createNode(13, NULL, NULL),
                 createNode(4, NULL,
                     createNode(1, NULL, NULL)))),
            22,
            false
          },
          {
             createNode(12,
              createNode(4,
                  createNode(11,
                      createNode(7, NULL, NULL),
                      createNode(51, NULL, NULL)), NULL),
              createNode(8,
                  createNode(13, NULL, NULL),
                  createNode(4, NULL,
                      createNode(6, NULL, NULL)))),
               22,
               false
           }
   };

   for(int i=0; i<3; i++)
   {
      if (hasPathSum(test_cases[i].root, test_cases[i].sum)  == test_cases[i].result)
         printf("test case [%d], PASS\n", i);
      else
        printf("test case [%d], FAIL\n", i);
      freeTree(test_cases[i].root);
   }

}

RESULT:
test case [0], PASS
test case [1], PASS
test case [2], PASS


texts:
I wrote some math formulas in Haskell and was wondering about how to clean the code up and make it more readable.

import Math.Gamma

pdf :: Double -> Double -> Double -> Double -> Double
pdf mu alpha beta x =
    ( beta / (2 * alpha * gamma  ( 1/beta) ) ) **
    exp ( -1* ( abs(x - mu )/alpha )) ** beta

cdf :: Double -> Double -> Double -> Double -> Double
cdf mu alpha beta x = 0.5 + signum(x - mu) * ( lowerGamma  (1/beta) ((abs(x-mu) / alpha)**beta) / (2 * gamma(1/beta)))

main = do
    let x = pdf 0 1 2 0.5
    print x
    let y = cdf 0 1 2 0.5
    print y


texts:
This is my first question on this website and I hope it goes well.

I have created a Kotlin factory pattern and I am using it very frequently. the code I use it consists of functions inside a class. This is not a static class however, it does not mutate any field inside this class.

When I look at this code, I can tell there is a pattern, so I thought I could improve it. That's why I am asking this question, for ideas & thoughts on how to improve the structure. The code is the following

class Client() {

    fun dispatchFollowEvent(followerID: Int, destination: Server, callback: (success: Any?) -> Unit) {
        val packet: FollowUserPacket = this.factory.makePacket(PacketType.FOLLOW_USER) as FollowUserPacket
        packet.payload = FollowUserPacket.FollowUserPayload(this, followerID)
        sendToServer(packet, this, destination, callback)
    }

    fun dispatchRegisterEvent(destination: Server) {
        val packet: RegistrationPacket = this.factory.makePacket(PacketType.REGISTRATION) as RegistrationPacket
        packet.payload = RegistrationPacket.RegistrationPayload(this)
        sendToServer(packet, this, destination)
    }

    fun dispatchUploadEvent(image: String, destination: Server) {
        val packet: UploadImagePacket = this.factory.makePacket(PacketType.UPLOAD_IMAGE) as UploadImagePacket
        packet.payload = UploadImagePacket.UploadImagePayload(this, image)
        sendToServer(packet, this, destination)
    }

    fun dispatchListUsersEvent(destination: Server, callback: (usersIDs: Any?) -> Unit) {
        val packet: ListUsersPacket = this.factory.makePacket(PacketType.LIST_USER_IDS) as ListUsersPacket
        packet.payload = ListUsersPacket.ListUsersPayload(this)
        sendToServer(packet, this, destination, callback)
    }

    fun dispatchGetFollowRequestsEvent(destination: Server, callback: (requests: Any?) -> Unit) {
        val packet: GetFollowRequestsPacket = this.factory.makePacket(PacketType.GET_FOLLOW_REQUESTS) as GetFollowRequestsPacket
        packet.payload = GetFollowRequestsPacket.GetFollowRequestsPayload(this)
        sendToServer(packet, this, destination,  callback)
    }
}

The class is simplified just so that it can be easier to read. I'm sure that all of you can see a pattern in this code, but it's beyond my knowledge to know how to make it more structured.

Do not worry about the functionality, the focus of this question is about improving the structure.

The factory code

class PacketFactory : Serializable {

    @Throws(Exception::class)
    fun makePacket(type: PacketType): Packet {
        return when (type) {
            PacketType.REGISTRATION -> RegistrationPacket()
            PacketType.UPLOAD_IMAGE -> UploadImagePacket()
            PacketType.LIST_USER_IDS -> ListUsersPacket()
            PacketType.FOLLOW_USER -> FollowUserPacket()
            PacketType.GET_FOLLOW_REQUESTS -> GetFollowRequestsPacket()
            else -> throw Exception("Type is not provided for the factory!")
        }
    }

}

The sendToServer function

fun sendToServer(
        payload: Packet,
        sender: Client,
        receiver: Server,
        callback: ((data: Any?) -> Unit)? = null
): Unit {
    // Code that sends payload to receiver and then invokes the callback
}