texts: Obtaining project size metrics with PowerShell

texts:
I'm often frustrated by the lack of ability to obtain simple size metrics about code projects I'm working on, like total lines of code, or character count. To fix this, I wrote the following PowerShell utility:

Function GetProjectMetrics
{
    [CmdletBinding()]
    Param(
        [Parameter(mandatory=$True)]
        [string]$projectPath,

        [Parameter(mandatory=$True)]
        [string]$fileFilter,

        [switch]$ignorews
    )

    Set-Location $projectPath
    Switch($ignorews)
    {
        $True
        {
            Get-ChildItem -recurse -include $fileFilter                   `
                | Get-Content                                             `
                | Measure-Object -Character -Word -Line -IgnoreWhiteSpace
            Break
        }

        $False
        {
            Get-ChildItem -recurse -include $fileFilter `
                | Get-Content                           `
                | Measure-Object -Character -Word -Line
            Break
        }

        Default
        {
            Write-Host "Error executing 'GetProjectMetrics'."
            Break
        }
    }
}

New-Alias -Name gpm -Value GetProjectMetrics
New-Alias -Name getpm -Value GetProjectMetrics

The above code is placed within my Microsoft.PowerShell_profile.ps1 file (my PowerShell profile), which gives me the ability to use it straight from the PowerShell command line.

Here's some example usage:

PS C:\Users\Ethan> gpm ".\Documents\MyPythonProject" "*.py" -ignorews
PS C:\Users\Ethan> getpm ".\Documents\MyPythonProject" "*.py"
PS C:\Users\Ethan> GetProjectMetrics ".\OneDrive\CS Projects\CS Tests" "*.cs" -ignorews

What can I improve?


texts:
I have got it working in a way so that there is one superclass, MathObject. In this implementation there is only a Constant subclass. I was forced to implement an abstract MathObject add(MathObject that) and an abstract MathObject add(Constant that) for reasons.

I would like to get that abstract MathObject add(Constant) out of MathObject because its already in Constant and I would have to update MathObject for each object I add.

I'd like to focus on maintainability and expandability first before adding too much features (this is my third or so attempt).

public class MathMain{
    public static void main(String[] args){
        Constant constant = new Constant(1);
        constant.add(constant);
        MathObject mathObject = (MathObject)constant;
        constant.add(mathObject);
        constant.add((Constant)mathObject);
        mathObject.add(constant);
    }
}

public abstract class MathObject{
    public abstract MathObject add(MathObject that);

    public abstract MathObject add(Constant that);

    public abstract MathObject substract(MathObject that);

    public abstract MathObject substract(MathObject that);

    public abstract double evaluate();
}

public class Constant extends MathObject{
    public final double c;

    public Constant(double c){
        this.c = c;
    }

    public MathObject add(MathObject that){
        return that.add(this);
    }

    public MathObject substract(MathObject that){
        return that.substract(this);
    }

    public Constant add(Constant addend){
        return new Constant(c + addend.c);
    }

    public Constant substract(Constant subtrahend){
        return new Constant(c - subtrahend.c);
    }

    public double evaluate(){
        return c;
    }
}


texts: Project Euler 14: Longest Collatz Sequence

texts:
I've brute forced solve Project Euler 14. This is my first attempt at trying to solve it, by caching already solved answers, and skipping them as I run it, I am finding the program take's almost twice as long as the simple brute force method of checking each number.

It works, but I could also use some insight on how to stop calculating, once I run into an integer we have already solved, and how to better write the entire problem into a class.

/*Project Euler 14.
The following iterative sequence is defined for the set of positive integers
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million
*/

#include <iostream>
#include <vector>

//I use this class to mark if a number has been solved.

class Collatz{
public:
    bool solved = false;
    unsigned terms = 0;
};

int main (){

    const unsigned maxnum = 1000000;
    std::vector<Collatz>cz(maxnum);
    unsigned larger = 0; //will be used to find largest sequence.
    unsigned largest = 0;

//This loop checks to see if the num has been solved yet.
//If not it solves its sequence, and marks all numbers in the sequence.

    for(unsigned a = 2; a < maxnum; a++){
        if(cz[a].solved == false){
            std::vector<unsigned long long>cache;
            cache.push_back(a);
            for(unsigned long long n = a; n != 1;){
                if(n % 2 == 0)
                    n = n/2;
                else
                    n = 3*n+1;
                cache.push_back(n);
            }
            //caching all already sovlved numbers
            for(unsigned c = 0; c < cache.size(); c++){
                if(cache[c] <= maxnum){
                    cz[cache[c]].solved = true;
                    cz[cache[c]].terms = cache.size() - c;
                }
            }
        }
        //Storing largest term.
        if(larger < cz[a].terms){
            larger = cz[a].terms;
            largest = a;
        }
    }

    std::cout << largest << std::endl;
}


texts:
I'm a beginner in PHP and I would like to know how to make a good quest system.

What is the code for : This code is to accept quest. It show the quest and where the user is in the quest (Ongoing, Available, Finished..).

What I'm looking for : As a beginner, this code is quite bad, and i'm looking for an improved version. For example, all the code is only working for 1 quest, and I would like an useful way to automatically put the quest when created instead of having to copy/paste the whole thing and change the id of the quest. And of course if i could do this in 1 query instead of querya and queryb (1 For the Fetch and 1 For the FetchColumn) it would be good.

The code is actually working if you wonder

Important informations : Most of the text is in frech, so while I'm translating it, I may forgot to change 1 or 2 things. If that's the case, don't assume the code is not working : just tell me what is wrong and it may be a mistake.

The Code

<?php
  $querya = $db->prepare('SELECT * FROM quetejoueur WHERE id_joueur=:id AND id_queteorij=1');
  $querya->bindValue(':id', $donnees["id"], PDO::PARAM_STR);
  $querya->execute();

  $queryb = $db->prepare('SELECT * FROM quetejoueur WHERE id_joueur=:id AND id_queteorij=1');
  $queryb->bindValue(':id', $donnees["id"], PDO::PARAM_STR);
  $queryb->execute();

while ( $findquetes = $querya->fetch() ) {
    if ($queryb->fetchColumn() > 0) {
      if ($findquetes["comp_quetej"] < 1) {
          ?><button disabled class="pomegranate-flat-button" style=" border-radius:6px; font-size:15px; padding-left:45px; padding-right:45px;"> Quest - Quest 1 (Ongoing) </button><?php
      }

    if ($findquetes["comp_quetej"] > 0) {
      if ($findquetes["recomp_quetej"] < 1) {
          echo '<form action="" method="POST"><input type="submit" class="peter-river-flat-button" style=" border-radius:6px; font-size:15px; padding-left:45px; padding-right:45px;" value="Quest - Quest 1 (Confirm the quest)" name="confirmerquete"></form>';
      }

      if ($findquetes["recomp_quetej"] > 0) {
        echo'<button class="emerald-flat-button" style=" border-radius:6px; font-size:15px; padding-left:45px; padding-right:45px;">Quest- Quest1 (Finished) </button>';
      }
    }

    }
    else {
      ?><button class="peter-river-flat-button" style="border-radius:6px; padding-left:45px; padding-right:45px;" onclick="window.location.href='../quete/vigier.php'">Quête - Le Vigier (Disponible) </button><?php
    }

}

$querya->CloseCursor();
$queryb->CloseCursor();

  if ((isset($_POST["confirmerquete"])) AND ($findquetes["recomp_quetej"] < 1)) {
    $querya=$db->prepare('UPDATE users SET exp= (exp + :queteexp) WHERE username=:username');
    $querya->bindValue(':queteexp', $findquetes["xp_quetej"], PDO::PARAM_INT);
    $querya->bindValue(':username', $username, PDO::PARAM_STR);
    $querya->execute();
    $querya->CloseCursor();

    $queryb=$db->prepare('UPDATE users SET money=(money + :moneyquest) WHERE username=:username');
    $queryb->bindValue(':moneyquest', $findquetes["or_quetej"], PDO::PARAM_INT);
    $queryb->bindValue(':username', $username, PDO::PARAM_STR);
    $queryb->execute();
    $queryb->CloseCursor();

    $query=$db->prepare('UPDATE quetejoueur SET recomp_quetej=1 WHERE id_quetej = :idqj');
    $query->bindParam(':idqj', $findquetes['id_quetej'], PDO::PARAM_INT);
    $query->execute();
    $query->CloseCursor();
  }

?>

If you need further explainations, just tell me. I'm sorry if this code is bad written, as I said this is only a beginner's work.


texts: Cops and robbers program to find the most frequent character in a string

texts:
I made this program to train me for a competition. The hypothetical question I've used was

  The cops need help finding who is the most probable criminal to commit a crime.
  Witnesses tell them multiple different people, making it hard to find the criminal.
  Use your knowledge of coding and the one-letter identifications provided for the criminals
  to find who most likely did it and print.

It was fun making the code; however, it felt like it took too long for such a simple code. Is there any way to make this simpler or better?

import java.util.*;

public class CopsAndRobbers {

    public static void main(String[] args) {
        //The cops need help finding who is the most probable criminal to commit a crime
        //Witnesses tell them multiple different people, making it hard to find the criminal
        //Use your knowledge of coding and the one-letter identifications provided for the criminals
        //To find who most likely did it and print.

        TreeSet<String> done = new TreeSet<String>();
        ArrayList<String> all = new ArrayList<String>();
        ArrayList<Integer> num = new ArrayList<Integer>();
        ArrayList<String> some = new ArrayList<String>();
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        for(int i = 0; i < input.length(); i++)
        {
            done.add(String.valueOf(input.charAt(i)));
            all.add(String.valueOf(input.charAt(i)));
        }
        int amount = done.size();
        for(int i = 0; i < amount; i++)
        {
            String letter = done.first();
            int tempNum = 0;
            for(int j = 0; j < all.size(); j++)
            {
                if(all.get(j).equals(letter))
                {
                    tempNum++;
                }
            }
            num.add(tempNum);
            some.add(letter);
            done.remove(letter);
        }
        int highest = 0;
        int overallIndex = 0;
        for(int i = 0; i < num.size(); i++)
        {
            if(num.get(i) > highest)
            {
                highest = num.get(i);
                overallIndex = i;
            }
        }
        System.out.println("The most likely criminal is " + some.get(overallIndex) + " with " + highest + " witnesses.");
    }

}

Sample Input

aggdhaamfa

Sample Output

The most likely criminal is a with 4 witnesses.


texts:
I created a Rock/Paper/Scissors game in C# that asks the player the number of rounds he wants to play, and then calculates the points and determines the winner.
Is there a way I can fix my code? Is it appropriate to use switch and if/else together?

Console.Write("How many rounds do you want to play ? : ");
int numberOfRounds = Convert.ToInt32(Console.ReadLine());

Random rnd = new Random();
string[] hands = { "Rock", "Paper", "Sci" };
    //               0       1        2

int playerPoints = 0;
int computerPoints = 0;

for (int counter = 1; counter <= numberOfRounds; counter++)
{
    Console.Write("Player Hand : ");
    string playerHand = Console.ReadLine();
    int randomNumber = rnd.Next(0, 3);
    string computerHand = hands[randomNumber];
    Console.WriteLine("Computer Hand : " + computerHand);

    switch (playerHand)
    {
        case "Rock":
            if (computerHand == "Rock")
            {
                playerPoints++;
                computerPoints++;
                Console.WriteLine("Player And Computer Win a Point");
                Console.WriteLine();
            }
            if (computerHand == "Paper")
            {
                computerPoints++;
                Console.WriteLine("Computer wins a point");
                Console.WriteLine();
            }
            if (computerHand == "Sci")
            {
                playerPoints++;
                Console.WriteLine("Player wins a point");
                Console.WriteLine();
            }
            break;

        case "Paper":
            if (computerHand == "Paper")
            {
                playerPoints++;
                computerPoints++;
                Console.WriteLine("Player and Computer Win a Point");
                Console.WriteLine();
            }
            if (computerHand == "Sci")
            {
                computerPoints++;
                Console.WriteLine("Computer wins a point");
                Console.WriteLine();
            }
            if (computerHand == "Rock")
            {
                playerPoints++;
                Console.WriteLine("Player wins a point");
                Console.WriteLine();
            }
            break;

        case "Sci":
            if (computerHand == "Sci")
            {
                playerPoints++;
                computerPoints++;
                Console.WriteLine("Player and Computer Win a Point");
                Console.WriteLine();
            }
            if (computerHand == "Rock")
            {
                computerPoints++;
                Console.WriteLine("Computer wins a point");
                Console.WriteLine();
            }
            if (computerHand == "Paper")
            {
                playerPoints++;
                Console.WriteLine("Player wins a point");
                Console.WriteLine();
            }
            break;
    }
}

Console.WriteLine("*** RESULTS ***");
Console.WriteLine("Player Points : " + playerPoints);
Console.WriteLine("Computer Points : " + computerPoints);

if (playerPoints > computerPoints)
{
    Console.WriteLine("Player Wins");
}
else
{
    if (computerPoints > playerPoints)
    {
        Console.WriteLine("Computer Wins");
    }
    else
    {
        Console.WriteLine("Equal None Win");
    }
}

Console.ReadLine();


texts: Converting PHP defined constant values to multiple languages

texts:
We have a large number of defined constants that are used as enum values when storing records. We convert the int values into language for our web portals. This was very straightforward when only dealing with one language, but now are tasked with making the portals support multiple languages.

The functions doing the value to language are easy enough to change and I have a solution, but I was wondering if there wasn't a better way as what I've come up with involves a little too much copy/paste for my taste. What I can't change are how we define the constants/enums.

The language files are written in json as key/value pairs. Language::_($key) handles looking up the proper language files and returning the string.

Another thought I had was to do the lookup based off the constant's value, but I couldn't find a way to pass constant's name (ACTION_ACCOUNT_NEW) to Language::_($key); I believe constants are evaluated before execution. I also don't want to pass the constant's value (1024) to Language::_($key) as I believe that would make a json file that would be very difficult to read.

Would there be a better way of doing this that involves less cut/paste of the defined constant names?

define('ACTION_ACCOUNT_NEW', 1024);
define('ACTION_ACCOUNT_DELETE', 1025);

function ActionToString($action){

    $actions_map = array(
        ACTION_ACCOUNT_NEW => Language::_('ACTION_ACCOUNT_NEW'),
        ACTION_ACCOUNT_DELETE => Language::_('ACTION_ACCOUNT_DELETE')
    );

    return isset($actions_map[$action])
        ? $actions_map[$action]
        : Language::_('Unknown');
}

json

{
    "ACTION_ACCOUNT_NEW": "Account Created",
    "ACTION_ACCOUNT_DELETE": "Account Deleted",

    "Unknown": "Unknown"
}


texts: Determining if three numbers are consecutive

texts:
This code will determine if three numbers are consecutive for any order they're supplied to the method (any permutation of [n, n+1, n+2] should be accepted). Is there any way to make this code easier for me to write, or make the code more efficient? Any feedback would be most welcome!

I tried testing with 3! combinations of 2, 3, 4, and it seemed to work. I also tried 1, 2, 9, and 1, 0, 1. All cases seem to work.

public static boolean consecutive(int a, int b, int c) {
    if ( a == b || b == c || a == c) {
        return false;
    } else if (((a == b + 1 || a == b - 1) || (a == c + 1 || a == c - 1)) && ((b == c + 1 || b == c - 1))
               || ((b == c + 1 || b == c - 1) || (a == b + 1 || a == b - 1)) && (a == c + 1 || a == c - 1))  {
        return true;
    }
    return false;
}


texts: Add getters and setters to a set of variables

texts:
Any improvements are welcome.

a.bat

sed -r "s/private (.*) (.*);(.*)/&\npublic \1 get\u\2(){return \2;}\npublic void set\u\2(\u\2){this.\2=\u\2;}\n/" "%~1">"%~2"

in:

private String firstName;// Stores firstName
private String lastName;
private String address;

using a.bat in out

out:

private String firstName;// Stores firstName
public String getFirstName(){return firstName;}
public void setFirstName(FirstName){this.firstName=FirstName;}

private String lastName;
public String getLastName(){return lastName;}
public void setLastName(LastName){this.lastName=LastName;}

private String address;
public String getAddress(){return address;}
public void setAddress(Address){this.address=Address;}

To do:
add javadoc generation to methods.


texts: Function for timing executions (inspired by MATLAB tic toc)

texts:
Inspired by MATLAB's tic/toc I've written a short helper function for calculating execution time.

from time import time

def tic():
    """Simple helper function for timing executions.

    Returns a closure that holds current time when calling tic().

    Usage:
    toc = tic()
    //some code
    print(toc())
    """
    t = time()
    return (lambda: (time() - t))

I'm well aware that there are python modules (e.g. timeit) that handle this kind of problem. However I do not want to time the execution of a whole script. I'm using this function in an interavtive shell for querying a mssql server.

What do you think? Is this good practice?


texts: Python function to map True, False, and None to symbols for display

texts:
I have a use case in which I need to check whether a given value is explicitly True or False:

def stringify(value):
    """Returns the string representation of the value."""

    if value is None:
        return '-'

    if value is True:
        return '✓'

    if value is False:
        return '✗'

    return str(value)

I know, that in most cases, where you just need the truthiness, you'd just do if value:. But here this will not suffice, since I want zero ints and floats to be displayed in their decimal form as well as empty lists, sets dicts as such.
Is the above code acceptable or should I rather check using isinstance(value, bool) first and then do if value:?

What's the least surprising way to go?

Usage Context
The function is part of an API that converts database records to terminal output:
MariaDB → peewee → API → terminal

Example output:

$ termutil ls -T 1000
  ID  TID         CID  VID  OS                     IPv4 Address               Deployed  Testing  Tainted  Address                                           Annotation
 214    1        1000    -  HIDSL latest              XX.Y.Z.75                      -        ✓        ✗  Musterstraße 42, 123456 Irgendwo                      -
 215    2        1000    -  HIDSL latest              XX.Y.Z.76                      -        ✓        ✗  Musterstraße 42, 123456 Irgendwo                      -
 216    3        1000    -  HIDSL latest              XX.Y.Z.77                      -        ✓        ✗  Musterstraße 42, 123456 Irgendwo                      -
 217    4        1000    -  HIDSL latest              XX.Y.Z.78                      -        ✓        ✗  Musterstraße 42, 123456 Irgendwo                      -
 218    5        1000    -  HIDSL latest              XX.Y.Z.79                      -        ✓        ✗  Musterstraße 42, 123456 Irgendwo                      -
 219    6        1000    -  HIDSL latest              XX.Y.Z.80                      -        ✓        ✗  Musterstraße 42, 123456 Irgendwo                      -
 330    7        1000  399  HIDSL latest             XX.Y.Z.182                      -        ✗        ✗  Musterstraße 42, 123456 Irgendwo                      -
 508    8        1000    -  HIDSL latest             XX.Y.Z.189                      -        ✗        ✗  N/A                                                   -


texts: Learning Javascript OOP with a Collapsing Item Class

texts:
I'm trying to get into object oriented javascript programming. I have written a class for collapsible elements as a test. These elements all have a certain class and no matter how many elements there are on the page, they should all be collapsible.
It works so far, but I don't think it's very elegant yet. For example, I wonder if the function "checkforCollapsibles" doesn't actually belong in the class? But can a class create instances of itself?
But that's probably not the only thing. I would be very happy if you have any suggestions on how to make this even better, cleaner and more elegant ;-)
--- EDIT: I know you don't need a class for collapsing elements :-)
"use strict";

class bb_Collapsible {
  constructor(link, content) {
    this.link = link;
    this.content = content;
    this.content.classList.toggle("bb-collapsed");
    this.link.addEventListener("click", this);
  }
  handleEvent(event) {
    if (event.type === "click") {
      this.switchStatus();
    }
  }
  switchStatus() {
    this.content.classList.toggle("bb-collapsed");
  }
}

function checkForCollapsibles() {
  const collapsibleLinks = document.querySelectorAll(".bb-collapsible");
  const collapsibleContents = document.querySelectorAll(".bb-collapsible-content");

  if (collapsibleLinks.length > 0) {
    collapsibleLinks.forEach((element, index) => {
      new bb_Collapsible(collapsibleLinks[index], collapsibleContents[index]);
    });
  } else {
    console.log("No collapsible Elements");
  }
}
document.addEventListener("DOMContentLoaded", checkForCollapsibles);

EXTENSION
I used this article for event handling. However, I don't quite understand it yet. In the example, only pass this as the callback. I assume javascript interprets this as the eventHandle function of the respective instance. But what if I have different elements that should trigger different functions? In my example, I could only ask which event was triggered and not which element? Or should I then write switches and get it from the respective event object? but that no longer sounds clean and tidy to me.
https://dev.to/rikschennink/the-fantastically-magical-handleevent-function-1bp4


texts:
I have a string that must be splitted into an array of strings so using strtok makes perfect sense but before that I want to allocate the array of strings and thus I count how many words in it.

static inline int countWords(char *str)
{
        int count = 0;
        char *buf = str;

        if(isgraph(*buf) > 0)//checking for the first word
                count++;
        while(*buf != '\0')
        {
                if(isblank(*buf) > 0){//reached a blank
                        while(*buf == ' ' || *buf == '\t')//keep ignoring them
                                buf++;
                        if(*buf == '\0')//return if string is over
                                return count;
                        count++;//no more blank and string didn't end=new word
                }
                buf++;
        }
        return count;
}

Am I doing this right? I've tested all weird cases that can come to my mind and it seems to work; but is there a faster way to do this? I am mainly concerned about the performance of the above code.


texts:
I am required to write a simple matrix program and swap the diagonal.

Given the input

1 2 3
4 5 6
7 8 9

After swapping the diagonal it should be

3 2 1
4 5 6
9 8 7

Here is my code:

public static void main(String[] args) {
    int i,j = 0,m,k;
    int Number[][] = new int [3][3];
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the elements of matrix");
    for(i=0;i<=2;i++)
    {
        for(j=0;j<=2;j++)
        {
            m = scanner.nextInt();
            Number[i][j] = m;
        }
    }
    System.out.println("This is the original matrix");
    for(i=0;i<=2;i++)
    {
        for(j=0;j<=2;j++)
        {
            System.out.print(Number[i][j]+"\t");
        }
        System.out.println();
    }
    //Swapping
    for(i=0;i<=3;i++)
    {
        k=Number[i][j];
        Number[i][j] = Number[i][3-i-1];
        Number[i][3-i-1] = k;
    }
    for(i=0;i<=2;i++)
    {
        for(j=0;j<=2;j++)
        {
            System.out.print(Number[i][j]+"\t");
        }
        System.out.println();
    }
}


texts: Calculator comparing your inflation rate to the Consumer Price Index

texts:
This code works fine and outputs the expected result. It is a small part of a larger program I'm working on to calculate personal inflation. I feel there is a better or more elegant way do this. I am trying to improve my programming logic skills so I hope its ok to ask for this kind of help.

I'm taking two arrays, both with 12 decimal numbers, dividing them by each other which will return an answer that is either above or below 1. I'm updating the above and below variables accordingly as counters. Then the conditional statements at the bottom are deciding which variable (above, below, avg) to be set to true. Based on which is true an arrow will be displayed as up, down or straight.

let personalCPI = [99.8, 100.8, 101.9,
                   102.1, 102.1, 101.9,
                   101.7, 102.5, 102.5,
                   102.6, 102.1, 102.2];

const nationalCPI = [99.5, 100.4, 101.4,
                     101.4, 101.4, 101.2,
                     101.1, 101.7, 101.6,
                     101.5, 101.1, 101.2];

let index;
let avg;
let above = 0;
let below = 0;

for (let i = 0; i < personalCPI.length; i++) {
    index = personalCPI[i] / nationalCPI[i];
    if (index > 1) {
        above += 1;
    } else if (index < 1) {
        below += 1;
    }
}

if (above > below) {
    above = true;
    below = false;
} else if (above >= 5 && above < 7 || below >= 5 && below < 7) {
    avg = true;
    above = false;
    below = false;
} else {
    below = true;
    above = false;
}

console.log(above);
console.log(below);
console.log(avg);

if (avg) {
    $("#inflation").attr("title", "Inflation is affecting you close to the
                                   National Average");
    $("#inflation").html('');
    } else if (below) {
        $("#inflation").attr("title", "Inflation is affecting you below the
                              National Average");
        $("#inflation").html('');
    } else if (above) {
        $("#inflation").attr("title", "Inflation is affecting you above the
                              National Average");
        $("#inflation").html('');
    }


texts: Exclusive and inclusive filtering of attributes

texts:
Here is a simple filter function I have:

function filter (attributes, data, include) {
    if (include) {
        let res = {}
        if (typeof attributes === 'string') {
            res[attributes] = data[attributes]
            return res
        }
        if (attributes.length) {
            attributes.forEach(attr => res[attr] = data[attr])
        }
        return res
    } else {
        if (typeof attributes === 'string') {
            delete data[attributes]
            return data
        }
        if (attributes.length) {
            attributes.forEach(attr => delete data[attr])
        }
        return data
    }
}

As you can see, these parts are same:

if (typeof attributes === 'string') {
    // some code
    return // some variable
}
if (attributes.length) {
    attributes.forEach(attr => /* some code */)
}
return // some variable

What is the best way to remove this duplicated code?


texts:
I have just started learning Python. This is code for a TicTacToe game. Can you please suggest any improvements?

pos_matrix=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
def my_tictactoe(pos,symbol):
    if pos_matrix[pos[0]-1][pos[1]-1]!=' ':
        print('Invalid input')
        exit
    else:
        pos_matrix[pos[0]-1][pos[1]-1]=symbol
    for i in range(0,3):
        print(pos_matrix[i][0]+' | '+pos_matrix[i][1]+' | '+pos_matrix[i][2])
        print('--|---|--')

    if is_win():
        print('GAME OVER. \n Player with symbol {x} wins!'.format(x=pos_matrix[pos[0]-1][pos[1]-1]))
        for i in [0,1,2]:
            pos_matrix[i][0]=pos_matrix[i][1]=pos_matrix[i][2]=' '

def is_win():
    for i in [0,1,2]:
        if pos_matrix[i][0]==pos_matrix[i][1]==pos_matrix[i][2]!=' ':
            return True
        elif pos_matrix[0][i]==pos_matrix[1][i]==pos_matrix[2][i]!=' ':
            return True
    if pos_matrix[0][0]==pos_matrix[1][1]==pos_matrix[2][2]!=' ':
        return True
    elif pos_matrix[0][2]==pos_matrix[1][1]==pos_matrix[2][0]!=' ':
        return True
    else:
        return False

my_tictactoe((1,1),'o')
my_tictactoe((2,2),'x')
my_tictactoe((3,2),'o')
my_tictactoe((1,3),'x')
my_tictactoe((2,1),'o')
my_tictactoe((3,3),'x')
my_tictactoe((3,1),'o')
my_tictactoe((1,2),'x')


texts: Filling random values in two sheets from a single sheet via Excel VBA

texts:
I fill out random values in two sheets (Testfall-Input_Vorschlag) and (Testfall-Input_Antrag) out of another sheet (ADMIN_ARB11).

I have 371 rows in sheet (Testfall-Input_Vorschlag) and I have 488 rows in sheet (Testfall-Input_Antrag). I have 859 columns in sheet (ADMIN_ARB11).

I pick a random value from each of the 1st 371 columns (from ADMIN_ARB11) and I put them in the 371 rows in sheet (Testfall-Input_Vorschlag) and then I pick a random value from each of the next 488 columns (from ADMIN_ARB11) and put them in 488 rows in sheet (Testfall-Input_Antrag).

Sub Random_Befüllung_Vorschlag_ARB11()
Dim sh1 As Worksheet, sh2 As Worksheet, i As Long, j As Long, LB As Long, UB As Long
Set sh1 = Sheets("Testfall-Input_Vorschlag")
Set sh2 = Sheets("ADMIN_ARB11")

Application.ScreenUpdating = False
    For j = 7 To 300
        LB = 2
        If sh1.Cells(1, j) = "ARB11" Or sh1.Cells(1, j) = "ARB13" Or sh1.Cells(1, j) = "FVB1" Or sh1.Cells(1, j) = "FVB1E" Or sh1.Cells(1, j) = "FVB4" Or sh1.Cells(1, j) = "FVB4E" Then
            sh1.Cells(2, j) = sh1.Cells(1, j) & "_Schicht 1"
            sh1.Cells(3, j) = "TPL maximale Eingaben"
            If j = 7 Then
                sh1.Cells(6, j) = 1
            Else
                sh1.Cells(6, j) = sh1.Cells(6, j - 1) + 1
            End If
            sh1.Cells(5, j) = "TF " & sh1.Cells(6, j)
            sh1.Cells(7, j) = "Test_GE"
            sh1.Cells(8, j) = "x"

            For i = 11 To 382
            UB = sh2.Cells(Rows.Count, i - 10).End(xlUp).Row 'i - 10 controls column in Admin start at col 1.

            sh1.Cells(i, j).Value = sh2.Cells(Int((UB - LB + 1) * Rnd + LB), i - 10)

            Next

        End If

    If sh1.Cells(1, j) = vbNullString Then
    Exit For
    End If
    Next
Application.ScreenUpdating = False
End Sub

Sub Random_Befüllung_Antrag_ARB11()
Dim sh1 As Worksheet, sh2 As Worksheet, i As Long, j As Long, LB As Long, UB As Long
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Sheets("Testfall-Input_Vorschlag")
Set sh1 = Sheets("Testfall-Input_Antrag")
Set sh2 = Sheets("ADMIN_ARB11")

Application.ScreenUpdating = False
    'Testfallinfo in Testfall-Input_Antrag kopieren
    For j = 7 To 300
    If Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "ARB11" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "ARB13" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB1" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB1E" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB4" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB4E" Then
    Union(ws.Cells(1, j), ws.Cells(2, j), ws.Cells(3, j), ws.Cells(4, j), ws.Cells(5, j), ws.Cells(6, j), ws.Cells(7, j), ws.Cells(8, j)).Copy
    sh1.Range("IV1").End(xlToLeft).Offset(, 1).PasteSpecial xlValues
    End If

        LB = 2
        If sh1.Cells(1, j) = "ARB11" Then
            For i = 13 To 501
                UB = sh2.Cells(Rows.Count, i + 364).End(xlUp).Row 'i - 10 controls column in Admin start at col 1.
                sh1.Cells(i, j).Value = sh2.Cells(Int((UB - LB + 1) * Rnd + LB), i + 364)

            Next
        End If

    If sh1.Cells(1, j) = vbNullString Then
    Exit For
    End If
    Next j
Application.ScreenUpdating = True
End Sub

It works as expected but it takes 5 min to run the code. How can I optimize this?


texts: Parallel SQL queries using completable future

texts:
My problem is I'm having a table and 7 child table. I'm fetching details using querying the main table first then querying the child tables one by one sequentially. To improve performance I decided to execute all the seven queries parallely using completable future.

 StoryDetail storyDetail = new StoryDetail();
      CompletableFuture<IStoryDetail> iStoryDetailCompletableFuture = CompletableFuture
          .supplyAsync(() -> storyRepository.getStoryDetails(id), executorService);
      CompletableFuture<List<Comment>> iCommentFuture = CompletableFuture
          .supplyAsync(() -> commentRepository.getComments(id), executorService);
      CompletableFuture<List<Images>> iImageFuture = CompletableFuture
          .supplyAsync(() -> imageRepository.getImagesByStoryId(id), executorService);

Here we are executing all the queries sequentially:

CompletableFuture.allOf(iCommentFuture, iStoryDetailCompletableFuture, iImageFuture)
      ;

And waits for all of them to finish then sets the value in the StoryDetail object:

  storyDetail.setComments(iCommentFuture.get());
  storyDetail.setImages(iImageFuture.get());
  mapStoryDetail(iStoryDetailCompletableFuture.get(), storyDetail);

Is the approach correct?


texts: Simple local cache that checks by date else get from db

texts:
I'm looking for feedback on how this can be improved. Basically what I'm trying to do is check if the cache has the object, else check from the database.

I have a list of ids, then I separate them based on whether they already exist in the cache or not, based on the date as well. One list fetches from the cache, the other from the db. Then return the list. That way I don't have to make multiple calls to cache/db.

The alternative is to implement a compound-key, but I would rather not go that route.

https://github.com/mel3kings/taxi-cab-api/blob/master/src/main/java/com/simple/controller/CabController.java

 private List<Cab> getFromCacheOrDb(CabTripsRequest request) {
        Map<Boolean, List<String>> cachedCabs = request.getMedallions().stream().collect(
                partitioningBy(key -> {
                    if (!cache.peek(key)) { return false; }
                    return cache.get(key).stream().anyMatch(a -> a.getPickupDateTime().equals(request.getDate()));
                }));
        List<Cab> response = cachedCabs.get(true).stream().map(k -> cache.get(k)).flatMap(List::stream)
                .filter(cab -> cab.getPickupDateTime().equals(request.getDate())).collect(toList());
        if (cachedCabs.get(false).size() > 0) {
            List<Cab> database = storage.fetch(cachedCabs.get(false), request.getDate());
            response.addAll(database);
            cache.save(database);
        }
        log.info("response from cache/db size:" + response.size());
        return response;
    }


texts: PHP: Overuse of date manipulation leading to convoluted code

texts:
I despise playing with dates in PHP so no doubt the below is too convoluted for what is needed. What I am looking for is a general tidy/reduction.

Everything but the wednesday and friday arrays are in a loop. The loop is from a ROQL statement. Oracle SQL for it's RightNow product, which is a very very stripped down version of MySQL from what I understand, meaning we are limited to basic SELECT statements i.e. we can't do anything worthwhile there.

$inc['order_date'] is a string representing a date in the format yyyymmdd
$inc['order_dispatch_date'] is a string representing a date in the format yyyymmdd
$inc['order_address'] is a string representing an address

So the basics of the code is:

Loop through each row in the database
Convert some dates
If the order address in the database is in the wednesday array, set the collection date to the Thursday after
If the order address in the database is in the friday array, set the collection date to the Saturday after
Do some more date conversion/manipulation
END GOAL: Get the difference in days between the order_date and the collection_date

CODE

$wednesday = array("Paris","London","New York");
$friday = array("Munich", "Cardiff", "Sydney");

$res = RNCPHP\ROQL::query( "SQL QUERY HERE")->next();
while($inc = $res->next()) {

    $order_date = DateTime::createFromFormat('Ymd', $inc['order_date']);
    $order_date = $order_date->format('Ymd');

    $order_dispatch_date = DateTime::createFromFormat('Ymd', $inc['order_dispatch_date']);
    $order_dispatch_date = $order_dispatch_date->format('Ymd');

    if (in_array($inc['order_address'], $wednesday)) {
        $order_collection = date('Ymd', strtotime('next thursday', strtotime($order_dispatch_date)));
    }
    if (in_array($inc['order_address'], $friday)) {
        $order_collection = date('Ymd', strtotime('next saturday', strtotime($order_dispatch_date)));
    }

    $order_collection = new DateTime($order_collection);
    $order_date   = new DateTime($order_date);

    $interval = $order_date->diff($order_collection);
    $interval = $interval->d;
}

FIRST REVISION

if (in_array($inc['order_address'], $wednesday)) {
    $order_collection = new DateTime(date('Ymd', strtotime('next thursday', strtotime($inc['order_dispatch_date']))));
}
if (in_array($inc['order_address'], $friday)) {
    $order_collection = new DateTime(date('Ymd', strtotime('next saturday', strtotime($inc['order_dispatch_date']))));
}

$order_date = new DateTime(date('Ymd', strtotime($inc['order_date'])));
$interval = $order_date->diff($order_collection)->d;


texts:
The following methods just write strings to the screen over time to make it look like a typing effect, instead of all at once. The only difference is the argument in the foreach loop.

I end up having lots of similar methods like these. How do I refactor them?

public IEnumerator TypeCharText(string message, Text textComp, bool resetTextComp = false)
{
    if (resetTextComp)
        textComp.text = "";

    foreach (char letter in message.ToCharArray())
    {
        textComp.text += letter;

        if (textComp.text.Length >= message.Length)
            OnMessageTyped(message);

        yield return new WaitForSeconds(2f);
    }
}

public IEnumerator TypeWordText(string message, Text textComp, bool resetTextComp = false)
{
    if (resetTextComp)
        textComp.text = "";

    foreach (string word in message.Split(' '))
    {
        textComp.text += " " + word;

        if (textComp.text.Length >= message.Length)
            OnMessageTyped(message);

        yield return new WaitForSeconds(2f);
    }
}

Here's what I have attempted:

public static IEnumerator TypeText<T>(Func<string, T> action, string message, Text textComp, bool resetTextComp = false)
{
    if (resetTextComp)
        textComp.text = "";

    textComp.text += action(message);

    if (textComp.text.Length >= message.Length)
        OnMessageTyped(message);

    yield return new WaitForSeconds(wordPause);
}

and to call it (StartCoroutine is a built-in Unity3D method that just calls a method):

StartCoroutine(TextTyper.TypeText<string>((x) => { x.Split(' '); return x;}, message, vanishText, true));
StartCoroutine(TextTyper.TypeText<string>((x) => { x.ToCharArray(); return x;}, message, vanishText, true));

It doesn't split the string up though or turn it into char array; action(message) still has the entire string.


texts: Regular Expression in Javascript to test a string of 1s and 0s

texts:
I have a string of four bits which represent true/false values. There are only seven valid  options:

1010
1110
0000
1101
1001
1000
0101

There are three options which could potentially be selected which are not valid and that I want to check for before I proceed with some other code. These are:

0110
0100
0010

I want to do this with as little code as possible thus having one regex to test all three conditions. My question is if this is a correct regex to accomplish this test. It seems to work, but I am not a regex expert, and have to be sure in this case.

 if (!/0(10|01|11)0/.test(precode)) {
     //do some code
 }


texts: Inserting nodes into a singly linked list based on size of number

texts:
Given a set of numbers insert them so that they are ordered ie.

add(5)
add(3)
add(6)
add(2)

Output: 6 5 3 2

GetNumber() returns the number of that term
insertAfter() inserts that node after the pointer
insertAtHead() inserts as the head node
Term is the Node which holds the number

How can I refactor this working code?

        boolean inserted = false;
        Node pointer = head;
    if (pointer == null || term.getNumber() > pointer.data.getNumber()) {
        // If head is empty insert there or if term is larger than head.
        insertAtHead(term);
    } else if(pointer.next == null) {
        insertAfter(term, head);
    } else {
        while (pointer.next != null) {
            //Insert at end.
            if (term.getNumber() > pointer.next.data.getNumber()) {
                insertAfter(term, pointer);
                inserted = true;
                break;
            }
            pointer = pointer.next;
        }
        if (!inserted) {
            //If not inserted it must be the smallest so add to the end.
            insertAfter(term, pointer);
        }
    }
    printList();


texts:
This is my implementation of Project Euler #7.  Have I overdone it again?  Is there anything else I should or should not do?  It runs in 9 milliseconds on my computer.

  What is the 10001st prime number?

static int NPrimeGenerator(int nPrime)
{
    List<int> primes = new List<int>();

    primes.Add(2);
    int nPrimeVal = 3;

    while (primes.Count != nPrime)
    {
        int sqrtNPrimeVal = (int) Math.Sqrt(nPrimeVal);

        foreach (int i in primes)
        {
            if (nPrimeVal % i == 0) { break; }

            if (i >= sqrtNPrimeVal)
            {
                primes.Add(nPrimeVal);
                break;
            }
        }

        nPrimeVal += 2;
    }

    return primes[primes.Count - 1];
}

static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    int nPrime = NPrimeGenerator(10001);

    s.Stop();

    Console.WriteLine(nPrime);

    Console.WriteLine(s.ElapsedMilliseconds);
}


texts: Version 2 - print new even-length arrays from two arrays

texts:
This is an update of the code for my previous post (which has now been removed as this code is more efficient and accurate) for the GeeksForGeeks task.

Task outline

Given two arrays, print all new arrays of even length where each subsequent element in the new array comes alternately from A then B and each element is larger than the previous element

Example:

Array 1 = [1, 2, 3]
Array 2 = [2, 4, 6]

Possible new array lengths = [2, 4, 6]

The output for arrays of length 2 is:
[1,2], [1,4], [1,6], [2,4], [2,6], [3,4] [3,6]

The full solution for the above includes the following two additional arrays:
[1 2 3 4], [1 2 3 6]

This solution uses the itertools library

import itertools
A=[10, 20, 30,40]
B=[11,21,31,41]
list_solutions = []

for x in range (1,min(len(A),len(B))+1):
    newA = list(itertools.combinations(A,x))
    newB = list(itertools.combinations(B,x))
    for itemA in newA:
        for itemB in newB:
            to_print = True
            for index in range (min(len(itemA),len(itemB))):
                if itemA[index] >= itemB[index]:
                    to_print = False
                    break
            if to_print == True:
                list_solutions.append([itemA, itemB])

#Print only valid solutions:
for item in list_solutions:
    print_valid = True
    for index in range (len(item[0])):
        if item[0][index] >= item[1][index]:
            print_valid = False
            break
        if index >= 1:
            if item[0][index] <= item[1][index-1]:
                print_valid = False
                break
    if print_valid == True:
        for index in range (len(item[0])):
            print (item[0][index], item[1][index], sep = " ", end = " ")
        print ("")
    if print_valid == False:
        continue


texts: Leap year determination using guard clause

texts:
I have a function to check the leap year as follows

bool IsLeapYear(int year)
{
    if (year % 4 == 0)
    {
        if (year % 100 == 0)
        {
            if (year % 400 == 0)
                return true;
            else
                return false;
        }
        else
            return true;
    }
    else
        return false;
}

I was wondering whether it would be correct to change this function by using guard clauses like below

bool IsLeapYear(int year)
{
    if (year % 4 != 0)
    {
        return false;
    }

    if (year % 4 == 0 && year % 100 == 0 && year % 400 != 0)
    {
        return false;
    }

    return true;
}

Is it going to introduce any side effects by using guard clause like this or is there a better way to write this function?


texts: Adding several text parts to one file in sequence

texts:
In my script, node.js reads text files and generates text itself. At the end, I have five "text parts", and want to add them to one file. For this step, it must be considered that the sequence is important, so unfortunately the great async technique of node is obstructive. How would you handle this?

The five text parts consists of:

Read File "head.txt" and than write/append its text (not much data) to the file
Text (not much data) generated by node itself -> write/append its text to the file
Text (large data) generated by node itself (loop)
Text (large data) generated by node itself (loop)
Read File "footer.txt" and than write/append its text (normal size) to the file

var fs = require('fs');

var filename = "content.txt";

// (1) Read 'head.txt'
fs.readFileSync('head.txt', 'utf8', function (err, head) {
    if (err) {
        return console.log('Could not read file.');
    }
    fs.appendFile(filename, head);
    //var writeStream = fs.createWriteStream(filename);
    //writeStream.write(head);
});

// (2)
var a = '...';
var b = '...';
var ab = a + b;
//var writeStream = fs.createWriteStream(filename);
//writeStream.write(ab);
//writeStream.end();
fs.appendFileSync(filename, ab);

// (3)
var writeStream = fs.createWriteStream(filename);
for (i = 0; i < xzy.length; i++) {
    writeStream.write('...' + xyz[i] + '...');
}
//writeStream.end();

// (4)
var writeStream = fs.createWriteStream(filename);
for (i = 0; i < xyz.length; i++) {
    writeStream.write('...' + xyz[i] + '...');
}
//writeStream.end();

// (5) Read 'footer.txt'
fs.readFileSync('footer.txt', 'utf8', function (err, footer) {
if (err) {
    return console.log('Could not read file.');
}
var writeStream = fs.createWriteStream(filename);
writeStream.write(footer);
//writeStream.end();
});

/*writeStream.on('finish', function () {
    console.log('finish');
});
writeStream.on('close', function () {
    console.log('close');
});*/


texts:
The purpose of the following code is to, given a vector, compute the two accumulators: 1. head-till-nth element, 2. (n+1)th element-till-last (where n, and this is the catch, iterates from 1 till length-of-list, inclusive).

(let [my-list [1 2 3 4 5 4 3 2 6]]
  (loop [elem 0]
    (when (<= elem (count my-list))
      (do        (println (reduce + (take elem my-list)))
                 (println (reduce + (drop elem my-list)))
                 (recur (inc elem))))))

While this code gets the job done, it is not functional but rather imperative (using a local, elem, as a running index and comparing against the vector's length to determine termination).

I considered using doseq but I can see no immediate way to incrementally slice the vector per the requirements. Using for is also wrong as I'm not trying to create a list comprehension.

I'd appreciate any answer showing the idiomatic Clojure way of doing this.


texts: Extract unique terms from a PANDAS series

texts:
Background

I have process tons of DataFrames with shapes of ~230 columns x ~2000-50000+ rows. Here is an extremely simplified example;

 numbers                colors
0    0.03620894806802     1xYellow ; 2xRed
1  0.7641262315308163  2xYellow ; 1xOrange
2  0.5607449770945651   3xYellow ; 2xGreen
3  0.6714547913365702     1xYellow ; 1xRed
4  0.8646309438322237     2xYellow ; 1xRed

Problem

I need to break the colors column down to a set that looks like this;
{'Green', 'Orange', 'Red', 'Yellow'}. The example code below can do this but it is painfully slow on huge DataFrames.

import re
import pandas as pd
import numpy as np
# Generating example data
color = ["1xYellow ; 2xRed ",
         "2xYellow ; 1xOrange ",
         "3xYellow ; 2xGreen ",
         "1xYellow ; 1xRed ",
         "2xYellow ; 1xRed "]
numbers = np.random.rand(len(color))
ex_df = pd.DataFrame(np.array([numbers,color]).T,
                     columns = ["numbers","colors"])
# Compile the regex to apply with findall
rx = re.compile("x(\w+)\s")
just_colors = ex_df.colors.apply(rx.findall)
# Below is the painfully slow operation that needs optimization.
present_colors = set(sum(just_colors,[]))

Question

Is there a better method out there for pulling unique terms out of a pandas series?


texts: ReactJS paginated component with React Router

texts:
I've recently started journey with ReactJS and to begin with I wanted to try something a bit more complex - paginated list of elements with back functionality enabled.
Below are two main components that I'd like to get feedback about. Especially PagedListings.
import './App.css';
import PagedListings from './components/PagedListings';
import ScrollToTop from './components/ScrollToTop';
import React from "react";
import { Route } from 'react-router';
import { BrowserRouter as Router } from 'react-router-dom';

function App() {
  return (
    <Router>
    <ScrollToTop>
       <Route path={["/", "/:page"]} component={PagedListings}/>
    </ScrollToTop>
    </Router>
  );
}

export default App;

And the actual component executing planned task
import React, { useMemo } from "react";
import ListingsContainer from "./ListingsContainer";
import Pagination from "@material-ui/lab/Pagination";
import { useHistory, useLocation } from "react-router-dom";

const LISTINGS = ["Rec1", "Rec2", "Rec3",
  "Rec4", "Rec5", "Rec6", "Rec7", "Rec8",
  "Rec9", "Rec10",];
const DEFAULT_PAGE = 1;
const MAX_PAGE_COUNT = 10;

function PagedListings(props) {
  const history = useHistory();
  const location = useLocation();
  const urlParams = useMemo(() => {
    return new URLSearchParams(location.search);
  }, [location.search]);

  const handleChange = (
    event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number
  ) => {
    let oneBasedNewPage = newPage;

    urlParams.set("page", oneBasedNewPage.toString());
    updateURL();
  };

  const updateURL = () => {
    history.push({
      pathname: location.pathname,
      search: `?${urlParams}`,
    });
  };

  function getPageNumber() {
    let newPage = parseInt(urlParams.get("page")) || DEFAULT_PAGE;
    return newPage <= MAX_PAGE_COUNT ? newPage : MAX_PAGE_COUNT;
  }

  return (
    <>
      <ListingsContainer listings={LISTINGS.slice(0, getPageNumber())} />
      <Pagination
        count={MAX_PAGE_COUNT}
        defaultPage={DEFAULT_PAGE}
        page={getPageNumber()}
        onChange={handleChange}
      />
    </>
  );
}

export default PagedListings;


texts: “Real world” JSON transformation using Node.js

texts:
Background

I transformed a non-trivial JSON response that uses arrays into

a nested object
eliminating some of the original properties
inserting a new summary property that is a unique list of values from the original object

I did this with temporary variables, foreach loops and some conditional logic.  My first working code, sample input / output JSON are below.

Question / Concern

While this works, I'm concerned about the "smell" of the code and the maintainability.  Is there a way to do this that would be more maintainable (perhaps with Array. ..., map, filter, reduce) ?  I'm not looking for a working solution but more than "one liners".

CODE

const raw = require('../tests/data/sample-input.json');

const types = new Set();

function parseLoc(loc) {
  // constant properties with loc_id the name of the object
  let o = { [loc.loc_id]: { last_update: loc.last_update, type_id: loc.type_id } };
  types.add(loc.type_id);
  // optional property
  if (loc.contents) {
    o = { [loc.loc_id]: { ...o[loc.loc_id], contents: loc.contents } };
    loc.contents.forEach((item) => {
      types.add(item.type_id); // can have nested types
    });
  }
  // optional property
  if (loc.plan_id) {
    o = { [loc.loc_id]: { ...o[loc.loc_id], plan_id: loc.plan_id } };
  }
  // summary properties
  o = {
    [loc.loc_id]: {
      ...o[loc.loc_id],
    },
  };
  return o;
}

const driver = () => {
  const { locs } = raw[Object.keys(raw)[0]];

  let out = {};
  locs.forEach((loc) => {
    const t = parseLoc(loc);
    out = { ...out, [Object.keys(t)[0]]: t[Object.keys(t)[0]] };
  });
  console.log('types', ...types);
  out = { ...out, Types: [...types] };
  console.log('out', JSON.stringify(out));
};

driver();

Input

   {
  "Input": {
    "locs": [
      {
        "contents": [{ "amount": 1, "type_id": 2393 }],
        "last_update": "2013-09-22T21:53:51Z",
        "obsolete1": 1.52384062551,
        "obsolete2": 1.56361060962,
        "loc_id": 1011160470678,
        "type_id": 2524
      },
      {
        "last_update": "2019-07-29T10:56:27Z",
        "obsolete1": 1.60921860432,
        "obsolete2": 1.60545414964,
        "loc_id": 1028580652821,
        "plan_id": 97,
        "type_id": 2474
      },
      {
        "contents": [
          { "amount": 560, "type_id": 2393 },
          { "amount": 560, "type_id": 9838 },
          { "amount": 560, "type_id": 2317 },
        ],
        "last_update": "2019-02-28T22:09:51Z",
        "obsolete1": 1.55924075537,
        "obsolete2": 1.58171860958,
        "loc_id": 1029669382563,
        "type_id": 2544
      }
    ]
  }
}

OUTPUT

{
  "1011160470678": {
    "last_update": "2013-09-22T21:53:51Z",
    "type_id": 2524,
    "contents": [{ "amount": 1, "type_id": 2393 }]
  },
  "1028580652821": {
    "last_update": "2019-07-29T10:56:27Z",
    "type_id": 2474,
    "plan_id": 97
  },
  "1029669382563": {
    "last_update": "2019-02-28T22:09:51Z",
    "type_id": 2544,
    "contents": [
      { "amount": 560, "type_id": 2393 },
      { "amount": 560, "type_id": 9838 },
      { "amount": 560, "type_id": 2317 }
    ]
  },
  "Types": [2524, 2393, 2474, 2544, 9838, 2317]
}


texts: PHP - Packing widgets into the fewest number of boxes, plus minimum order quantity

texts:
The problem is this:

A company supplies widgets in a set of pack sizes:

250
500
1000
2000
5000

Customers can order any number of widgets, but the following rules apply:

Only whole packs can be sent and …
No more widgets than necessary should be sent and …
The fewest packs possible should be sent

Some examples showing the number of widgets ordered and the required pack quantities and sizes to correctly fulfill the order:

1 (1 x 250)
251 (1 x 500)
501 (1 x 500 and 1 x 250)
12001 (2 x 5000 and 1 x 2000 and 1 x 250)

I’ve looked at some algorithms (greedy coin change, LAFF, etc.) as these seem to provide similar solutions, but can’t seem to see how to adapt them to the above.

For example:

<?php

function countWidgets($amount)
{
    $packs = array(5000, 2000, 1000, 500,
                  250);
    $packCounter = array(0, 0, 0, 0, 0);
    $packsCount = count($packs);

    // loop packs
    for ($i = 0; $i < $packsCount; $i++)
    {
        if ($amount >= $packs[$i])
        {
            $packCounter[$i] = intval($amount /
                                      $packs[$i]);
            $amount = $amount -
                      $packCounter[$i] *
                      $packs[$i];
        }
    }

    // if remainder
    if ($amount > 0) {
        // and if smallest pack size populated
        if ($packCounter[4] == 1) {
            // clear smallest pack size
            $packCounter[4] = 0;
            // increment next biggest pack size
            $packCounter[3] += 1;
        } else {
            // increment smallest pack size
            $packCounter[4] +=1;
        }
    }

    // Print packs
    echo ("Pack ->"."\n");
    for ($i = 0; $i < $packsCount; $i++)
    {
        if ($packCounter[$i] != 0)
        {
            echo ($packs[$i] . " : " .
                  $packCounter[$i] . "\n");
        }
    }
}

$amount = 251;
countWidgets($amount);


texts: Representing and Parsing an Open or Closed Range

texts:
I would like to represent a numeric range in C#. Either open-ended, such as "up to 35" or "100 on up" or closed-ended, such as "34 to 65". I'd like to represent the open end with NULL. Further, I'd like to parse strings into the range. Strings will look like "-35", "100+", "34-65" or even "-10.5--0.5". I hate that the dash means negative and the range separator, but it is what I'm given. That all being said, I've tested my cases against this code and they work. My questions are: is this the best way to accomplish this? Is it okay to let certain exceptions be thrown for invalid data or should I do more checking on it beforehand? Should this even be called Range? Is Interval better?

public struct Range<T> where T : struct, IComparable<T>
{
    private static readonly Regex _RemoveSpaces = new Regex(@"\s+", RegexOptions.Compiled);

    private static readonly char[] _SplitOnDash = { '-' };

    private static readonly TypeConverter _Converter = TypeDescriptor.GetConverter(typeof(T));

    private readonly T? _Minimum;

    private readonly T? _Maximum;

    public Range(T? minimum = null, T? maximum = null)
    {
        if ((minimum != null) && (maximum != null) && Comparer<T?>.Default.Compare(minimum, maximum) > 0)
        {
            throw new ArgumentException("minimum is greater than maximum.");
        }

        this._Minimum = minimum;
        this._Maximum = maximum;
    }

    public T? Minimum
    {
        get
        {
            return this._Minimum;
        }
    }

    public T? Maximum
    {
        get
        {
            return this._Maximum;
        }
    }

    public static Range<T> Parse(string range)
    {
        range = _RemoveSpaces.Replace(range, string.Empty);

        // No maximum.
        if (range.EndsWith("+"))
        {
            return new Range<T>(_Converter.ConvertFromString(range.Substring(0, range.Length - 1)) as T?);
        }

        // No minimum.
        if (range.StartsWith("-") && !range.Substring(2).Contains("-"))
        {
            return new Range<T>(null, _Converter.ConvertFromString(range.Substring(1)) as T?);
        }

        var rangeParts = range.Split(_SplitOnDash);

        // Two positive numbers.
        if (rangeParts.Length == 2)
        {
            return new Range<T>(
                _Converter.ConvertFromString(rangeParts[0]) as T?,
                _Converter.ConvertFromString(rangeParts[1]) as T?);
        }

        // One negative, one positive number.
        if (rangeParts.Length == 3)
        {
            return new Range<T>(
                _Converter.ConvertFromString("-" + rangeParts[1]) as T?,
                _Converter.ConvertFromString(rangeParts[2]) as T?);
        }

        // Two negative numbers.
        if (rangeParts.Length == 4)
        {
            return new Range<T>(
                _Converter.ConvertFromString("-" + rangeParts[1]) as T?,
                _Converter.ConvertFromString("-" + rangeParts[3]) as T?);
        }

        // No idea what we were given, give a completely open range.
        return new Range<T>(null, null);
    }

    public override string ToString()
    {
        return (this._Minimum == null) && (this._Maximum == null)
            ? string.Empty
            : (this._Minimum == null
                ? string.Format("-{0}", this._Maximum)
                : (this._Maximum == null
                    ? string.Format("{0}+", this._Minimum)
                    : string.Format("{0} - {1}", this._Minimum, this._Maximum)));
    }
}


texts:
This function finds a certain string within a string. I feel like my function is too messy.

I'm new to C memory functions. Are there any shortcuts I can take to make this function shorter? Is this implementation effective?

bool strfound(char * find, char * name) {
    int j = 0;
    int size = strlen(name) + 1;
    char * buffer;
    buffer = (char*)malloc(size + 1);
    for (int i = 0; i < size; i++) {
        std::cout << buffer << std::endl;
        if (i == 0 && name[i] != ' ') {
            j++;
            buffer[j - 1] = name[0];
        }
        if (i != 0 && name[i] != ' ') {
            buffer[j] = name[i];
            j++;
        }

        if (name[i] == ' ' || i == size - 1) {
            buffer[j] = '\0';
            if (strcmp(buffer, find) == 0) {
                std::cout << "String is found: " << buffer << std::endl;
                buffer[j] = '\0';
                std::cout << name << std::endl;
                free(buffer);
                return true;
            }
            strcpy(buffer, ""); // or null from 0
            buffer = (char*)malloc(size + 1);
            j = 0;
        }
    }
    return false;
}

Output: https://gyazo.com/2fc0fe88958dfeb2f8cf20eff1f2d113


texts:
We have conception as "fiscal year" and have calculations based on start/end date (April 1, March 31).

My question is: what is better, store end date time as April 1 or March 31?
Now I have next code:

public DateTime GetFiscalYearStart(int fiscalYear)
{
    return new DateTime(fiscalYear, 4, 1);
}

public DateTime GetFiscalYearEnd(int fiscalYear)
{
    return new DateTime(++fiscalYear, 4, 1).AddTicks(-1);
}


texts: Web service - getting data from SQL and adding to Object

texts:
I have created a class called CommandMessages

    public class CommandMessages
    {
        public string CommandType { get; set; }
        public string Command { get; set; }
        public DateTime? SendDateTime { get; set; }

        public CommandMessages()
        {
        }

        public CommandMessages(string commandtype, string command, DateTime? senddatetime)
        {
            CommandType = commandtype;
            Command = command;
            SendDateTime = senddatetime;
        }
    }

I also have a web service called GetData

    [WebMethod]
    public CommandMessages GetData()
    {
        var result = new CommandMessages();

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestProjectConnectionString"].ConnectionString))
        {
            string query = "exec usp_dequeueTestProject";
            SqlCommand command = new SqlCommand(query, connection);
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                 result.CommandType = reader.GetString(0);
                 result.Command = reader.GetString(1);
                 result.SendDateTime = reader.GetDateTime(2);
                 reader.Close();
            }
            connection.Close();
        }

        return result;
    }

Please can someone let me know how efficient my web service is being at getting data from the SQL table?  I don't know if this is the best way to do it or not.


texts: Find the number of all specific substrings in a string

texts:
I would like to ask a code review  regarding a concrete exercise. Let's suppose I have to get the number of all specific substrings in a string.
We call something specific if any of these conditions are is true:

The string consists of similar characters. For example: "aaaaa"

The string consists of similar characters except the middle one, which can be anything. For example: "aabaa"

To do this, I first decided to get all combinations into a list. I did it in an O(n³) solution just with 2 basic for loops and using substring() (see more), this way:
private static List<String> allCombinations(String s) {
    List<String> output = new ArrayList<>();
    for (int i = 1; i <= s.length(); i++) {
        for (int j = 0; j <= s.length() - i; j++) {
            output.add(s.substring(j, j + i));
        }
    }
    return output;
}

Subsequently, I used this method to count how many of these are special:
static long substrCount(String s) {
    long res = 0L;
    List<String> output = allCombinations(s);
    for (String x : output) {
        if(isSpecial(x)){
            res++;
        }
    }
    return res;
}

isSpecial() looks like this:
private static boolean isSpecial(String input) {
    Set<Character> occurrences = new HashSet<>();
    for (int i = 0; i < input.length(); i++) {
        occurrences.add(input.charAt(i));
    }
    if (occurrences.size() > 2) {
        return false;
    }
    if (occurrences.size() == 1) {
        return true;
    }
    return input.length() % 2 == 1 && input.charAt(0) == input.charAt(input.length() - 1) && input.charAt(input.length() / 2) != input.charAt(0);
}

I've got 2 questions:

This is a practice exercise with provided tests, and most of the test cases failed due to time complexity problems. How could I reduce the time complexity of my solution?

If you could give me any general feedback what to improve in - based on my code - I would be really thankful.

Thank you in advance.


texts: Check if all of the delimiters in an expression are matched and closed

texts:
Problem

Write an algorithm to determine if all of the delimiters in an
expression are matched and closed.
{(abc)22}[14(xyz)2] should pass
[ { ] } should fail
{ (x) } [ should fail

Any advice of code functional bug, performance in terms of algorithm time complexity, code style are appreciated.
delimiters = ['[', ']', '(', ')', '{', '}']
delimiters_map = {']':'[', ')':'(', '}':'{'}

def check_match(source):
    working_set = []
    for i,v in enumerate(source):
        if v not in delimiters:
            continue
        if v in delimiters_map: # end of a delimiter:
            if working_set[-1] != delimiters_map[v]:
                return False
            else:
                working_set.pop(-1)
        elif v in delimiters:
            working_set.append(v)

    if len(working_set) > 0:
        return False
    else:
        return True

if __name__ == "__main__":
    print check_match('{(abc)22}[14(xyz)2]')
    print check_match('[ { ] }')
    print check_match('{ (x) } [')


texts:
In all the examples I've come across so far, (like this, this or this) I see stacked charts in d3 have an ordinal scale. I presume this is because stacked charts are considered an extension of bar charts which are generally of ordinal scale on the one of the axis.

In my case, using sample data

{"a":[20,10],"b":[50,0],"c":[45,60],"d":[10,40]}

I need to generate a stacked chart with a linear scale x-axis like below.

(The width of each column is a scale of the sum of 2 elements of the array, and the 2 cells in each column represent the values of the array elements as a % of the height. The columns are sorted left to right on sum desc)

I tried to use d3.stack to generate such a chart using the below code, but this seems a little messy to me, as I'm accessing the data object of the stack array.

var body = d3.select('body');
var svg = body.append('svg').attr('height',200).attr('width',500);
var maing = svg.append('g');

var inputData = JSON.parse('{"a":[20,10],"b":[50,0],"c":[45,60],"d":[10,40]}')

// generate class
var colors = d3.schemeCategory10
var mysheet = document.styleSheets[0];

Object.keys(inputData).forEach(function(d,i){
  mysheet.insertRule(`.${d}{fill:${colors[i]}; opacity:0.8}`);
  mysheet.insertRule(`.${d}_h{fill:${colors[i]}; opacity:0.6}`);
});

// convert to flattened array
var vals = Array("p", "h");
var cumT = +0
var transformedData = Object.keys(inputData).map(function(d,i){
  let o = {}; o.mp = d;
  inputData[d].forEach(function(d,i){o[vals[i]]=d})
  o.t=o.p+o.h;
  return o;
}).sort(function(a,b){
  return b.t - a.t
}).map(function(d,i){
  let o = d; o.cumT = cumT += d.t
  return o;
})

var stack = d3.stack().keys(vals);
var stackData = stack(transformedData);

var g = maing.selectAll('g')
  .data(stackData).enter().append('g')

var x = d3.scaleLinear().domain([0,230]).range([0,100])  // TODO: use d3.max here
var y = d3.scaleLinear().domain([0,1]).range([0,140])    // some predefined height

g.selectAll('rect').data(function(d){return d})
  .enter().append('rect')
  .attr('x', function(d,i){return x(d.data.cumT-d.data.t)})
  .attr('y', function(d,i){return y(d[0]/d.data.t)})
  .attr('width', function(d,i){return x(d.data.t)})
  .attr('height', function(d,i){return y((d[1]-d[0])/d.data.t) })
  //.style('stroke-width', 1).style('stroke', 'black')
  .attr('class', function(d){
    return d3.select(this.parentNode).datum().key === "p" ? d.data.mp : d.data.mp+"_h";
  })
;
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Stack Dev</title>
    <style media="screen">

    </style>
  </head>
  <body>

    <script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
  </body>
</html>

What would be a better way to go about generating something like this? Especially if I have to generate many many small charts like this on a single page?


texts: Looking for a better way to define and use constants

texts:
In a custom Ant task, I have the following constants:

private static final String _REVISION = ".revision";
private static final String _CODEBASE_INFO = ".codebase";
private static final String _DIFF = ".diff";
private static final String _TYPE_GIT = "git";
private static final String _TYPE_SVN = "svn";
private static final String[] _COMMAND_REV_GIT =
    {"git", "rev-parse", "HEAD"};
private static final String[] _COMMAND_REV_SVN =
    {"svn", "info"};
private static final String[][] _COMMAND_CODEBASEINFO_GIT = {
    {"git", "branch", "-v"},
    {"git", "remote", "-v"},
    {"git", "log", "--max-count=1"},
    {"git", "status"}};
private static final String[][] _COMMAND_CODEBASEINFO_SVN = {
    _COMMAND_REV_SVN,
    {"svn", "status"}};
private static final String[][] _COMMAND_DIFF_GIT = {
    {"git", "diff", "HEAD"},
    {"git", "diff", "HEAD", "--no-prefix"}};
private static final String[][] _COMMAND_DIFF_SVN = {
    {"svn", "diff"}};

private static final Map<String, Object> _COMMANDS;

static {
    Map<String, Object> map = new HashMap<>();
    map.put(_TYPE_GIT + _REVISION, _COMMAND_REV_GIT);
    map.put(_TYPE_SVN + _REVISION, _COMMAND_REV_SVN);
    map.put(_TYPE_GIT + _DIFF, _COMMAND_DIFF_GIT);
    map.put(_TYPE_SVN + _DIFF, _COMMAND_DIFF_SVN);
    map.put(_TYPE_GIT + _CODEBASE_INFO, _COMMAND_CODEBASEINFO_GIT);
    map.put(_TYPE_SVN + _CODEBASE_INFO, _COMMAND_CODEBASEINFO_SVN);
    _COMMANDS = Collections.unmodifiableMap(map);
}

What the task should do is to run commands according to a given version control type. For example if I give it git then it will run commands in _COMMAND_REV_GIT, _COMMAND_CODEBASEINFO_GIT and _COMMAND_DIFF_GIT.

The reason I separate them into three constants is that the outputs of them have to be handled in different ways.

The reason I use a map is that I don't want to use a lot of "if" or "switch-case" in my code. In the map there are keys like git.revision, git.codebase, etc. If git is given when running this task, _COMMAND_REV_GIT will be fetched from the map using the key git.revision in the method handling running the revision command:

String[] command = _COMMANDS.get(_givenType + _REVISION);

But these constants looks really complicated, and I think the types of version control should be Enum rather than String, so is the suffixes indicating the types of the commands. So how should I modify these codes to make it clear, safe and elegant?


texts:
Assuming everything else works as expected, is the following a correct - but not the most efficient way - of implementing Dijkstra algorithm? Because I have tested it on several examples and it gives correct result. But I can't imagine Dijkstra is that simple.

  public static void FindShortestPath(Node source, Directed graph)
    {
        if(source==null)
        {
            System.err.println("Source doesn't exist.");
            System.exit(0);
        }
       source.setCost(0); // all nodes are initialized with cost=Double.Max_VALUE when first created.
       PriorityQueue<Node> pq=new PriorityQueue<>(); // Node implements comparable according to cost
       for(Node node:graph.getAdj().keySet()) // get all nodes
          pq.add(node);
        while(!pq.isEmpty())
        {
            Node u=pq.poll(); // the minimum
            List<Node> neighbours=graph.getAdj().get(u); // get the minimum direct successors
            for(Node v:neighbours)
            {
                if(v.getCost()>(u.getCost()+(graph.getCost(u, v)))) // if there is a cheaper one
                {
                    v.setCost(u.getCost()+graph.getCost(u, v)); // change its cost
                    pq.remove(v);  //remove it
                    pq.add(v);  // add it again
                }
            }
        }
    }


texts: JavaScript calculator with two inputs and four operations

texts:
i build a calc & want to a review that what i did wrong & what is right method to do.

      Enter first number
      <input type="number" id="valueOfX">
      Enter second number
      <input type="number" id="valueOfY">
      <button onclick="operation('add')"> Add </button>
      <button onclick="operation('sub')"> Sub</button>
      <button onclick="operation('mul')"> Mult</button>
      <button onclick="operation('div')"> Divi</button>


texts: Middlewares with Route definition or Routes with Middleware definition

texts:
I am currently working on an Node based Express application. I have found Express's middlewares approach quite pleasing however, we all run in scenarios where a certain route or routes don't need a specific middleware.

I have found two approaches:

Adding middleware globally exempting the routes it doesn't need to run for. express-jwt is good example of this:

app.use(jwt().unless(
    '/someroute',
    '/someotherroute',
    ...
);

app.use(someothermiddleware().unless(
    '/someroute2',
    ...
);

app.use(someothermiddlewaretoo().unless(
    '/someroute3'
    ...
);

Adding middleware(s) to each route you define:

route.get(
   '/someroute1',
   [ jwt(), someothermiddleware, someothermiddlewaretoo ],
   function(req, res) {
       ...
   }
);

route.get(
   '/someroute2',
   [ jwt(), someothermiddlewaretoo ],
   function(req, res) {
       ...
   }
);

route.get(
   '/someroute3',
   [ jwt(), someothermiddleware ],
   function(req, res) {
       ...
   }
);

I can see that Approach #2 looks like some work however, I believe Approach #2 is way better in terms of a large application where you might have nested routers. You can be on any route and know exactly what middlewares it gets executed with.

With Approach #1, you get things up and running easily but, it will be pain to check if this route is being included for specific middleware every time you try to fix a bug.

Which approach is better in your opinion? Or, is there another approach that you would like to share?


texts:
I have a model object class like this

public class EventInterestsResponse
{
  public string id { get; set; }
  public int sortOrder { get; set; }
  public string name { get; set; }
  public string categoryName { get; set; }
  public string categoryId { get; set; }
}

And I am using it to hold some data like this

public List<EventInterestsResponse> GetEventInterests()
{

  _data = _rh.ExecuteGetRequest();
  var yourObject = _data != null ? (List<EventInterestsResponse>)jsonSerializer.Deserialize<List<EventInterestsResponse>>(_data) : null;
  return yourObject;
}

Later I want to preform some operations on this.
For example, I want to check if any of the resulting objects contain a specific categoryId and if yes, I want to print it. I have written this working code:

foreach (var interest  in InterstList)
{
  if (interest.categoryId == "11")
  {

    Branche:@interest.name
  }
  if (interest.categoryId == "22")
  {

    Udviklingsstadie:@interest.name
  }
}

Now I wonder: Is this the most elegant way to do this? Maybe I don't even want to use a foreach loop. Can this be achieved by LINQ and using lambda expressions?

Can any one tell me how I can modify this code so that it uses LINQ and lambda expressions?


texts: Debounce function that limits the rate a callback is triggered. Which implementation is better, and why?

texts:
The Debounce technique allow us to “group” multiple sequential calls in a single one - The debounce() function forces a function to wait a certain amount of time before running again.
I wrote both debounce_1 & debounce_2 functions while solving a programming challenge, they produce the same result but I want to know which implementation is better and why, as I'm currently studying JavaScript to improve the quality of my code.

/* Write a function called 'debounce' that accepts a function and returns a
   new function that only allows invocation of the given function after
   'interval' milliseconds have passed since the last time the returned
   function ran.

   Additional calls to the returned function within the 'interval' time
   should not be invoked or queued, but the timer should still get reset. */

function debounce_1(callback, interval) {
  let lastTime = -Infinity;

  return function(){
    let now = Date.now(), res;

    if (now - lastTime > interval) {
      res = callback();
    }

    lastTime = now;
    return res;
  }
}

function debounce_2(callback, interval) {
  let timeout = null;

  return function(){
    let res;

    if (!timeout) { res = callback(); }

    clearInterval(timeout);
    timeout = setTimeout(() => timeout = null, interval);

    return res;
  }
}

/* TESTING */
function hello() { return 'hello'; }

// UNCOMMENT BELOW TO TRY EITHER ONE:
const sayHello = debounce_1(hello, 3000);
// const sayHello = debounce_2(hello, 3000);

console.log( sayHello() );                                 // -> 'hello'
setTimeout(function() { console.log(sayHello()); }, 2000); // -> undefined
setTimeout(function() { console.log(sayHello()); }, 4000); // -> undefined
setTimeout(function() { console.log(sayHello()); }, 8000); // -> 'hello'


texts: Return a tuple from MySQL database with statements

texts:
I have a database from which I'd like to return a tuple of two elements (ID and URL) with check digit to see if operation was successful.

Is correct this code to return this tuple and control?

public function getManufacturer($id) {
    $stmtManufacturer = $this->dbConnection->prepare("SELECT ID, URL FROM ERP.MANUFACTURER WHERE ID = ?");
    $stmtManufacturer->bind_param("i", $id);
    $stmtManufacturer->execute();
    $stmtManufacturer->store_result();
    $stmtManufacturer->bind_result($id, $url);
    $stmtManufacturer->fetch();
    $stmtManufacturer->close();
    return [
                ACTION_RESULT => $this->processServerResponse($stmtManufacturer),
                "data" =>
                [
                    "id" => $id,
                    "url" => $url
                ]
            ];
}

ACTION_RESULT is defined as a constant in the class.

I think function processServerResponse() could be improved:

public function processServerResponse($stmt) {
    if ($stmt->errno || $stmt->affected_rows === 0) {
        $_actionResult = 0;
    } else if ($stmt->affected_rows !== 0) {
        $_actionResult = 1;
    }
    return $_actionResult;
}


texts: Form a string consisting of the common letters that appear in two input strings

texts:
The idea is to write a function that takes two strings and returns a new string that repeats in the previous two: examples:

'ABBA' & 'AOHB' => 'AB'
'cohs' & 'ohba' => 'oh'

A brute force solution would be nested for loops like so:

const x = 'ABCD'
const y = 'AHOB'

function subStr(str1, str2) {
  let final = ''

  for (let i = 0; i < str1.length; i++) {
    for (let j = 0; j < str2.length; j++) {
      if (str1[i] === str2[j]) {
        final += str1[i]
      }
    }
  }

  return final
}

console.log(subStr(x, y)) // => AB


texts:
Before saving the input from users in the database, I am using the below function to replace all HTML special chars. All my users will always be using the English Language.

Option 1

function clean($var) {
  $regEx="/[^a-zA-Z0-9 -_]/";
  $var = preg_replace($regEx, "", $var);
  return $var;
}

I want users to be able to only store

Letters (a to z) (Case Insensitive)
Numbers (0 to 9)
Space, Dash, Underscore

Will the above function is good for this job, or should I be using a more efficient/inbuilt function in PHP?

This is how I am using the function.

$userInput = htmlspecialchars(clean($userInput));

Option 2

function h($str_to_encode = ""){
    // Pregmatch will replacte all HTML characters with Empty string
    return preg_replace("/&#?[a-z0-9]{2,8};/i","", htmlspecialchars($str_to_encode));
}

Regex from : https://stackoverflow.com/a/657670/4050261


texts:
I simply made this for practice. But I want to know if it can be used in the realworld or not. Please point out any bad programming practices and how I can change them and look out for them next time.
Your advice or tip will be the invaluable rain
on my deadly isolated programming land.

import os
import hashlib
from base64 import b64encode, b64decode

def convert_to_bytes(value, value_name):
    if isinstance(value, str):
        return value.encode('UTF-8')
    else:
        raise ValueError('%s must be string or bytes' % value_name)

def derive_passhash(password, hash_name='sha512', salt=None, iterations=100000):
    '''This function returns str type password_hash.
    hash contains hash_name, iterations, salt, derived_key
    -> [hash_name] $ [iterations] $$ [salt] $s_k$ [derived_key] '''
    if salt is None:
        salt = os.urandom(32)
    if not isinstance(salt, bytes):
        salt = convert_to_bytes(salt, 'salt')
    if not isinstance(password, bytes):
        password = convert_to_bytes(password, 'password')
    if not isinstance(iterations, int):
        if isinstance(iterations, str) and iterations.isnumeric():
            iterations = int(iterations)
        else:
            print('iterations must be integer.')
            raise ValueError
    # derive passhash
    try:
        d_key = hashlib.pbkdf2_hmac(hash_name, password, salt, iterations)
        del password    # maybe it can help to make more secure?
    except ValueError as error:
        print('[!] Error cused %s' % error)
        # log(error)

    # put hash_name, salt, iterations and derived key together
    # and encode to base64 format.
    pre_v = '$'.join((hash_name, str(iterations))).encode('utf-8')
    end_v = b'$s_k$'.join((salt, d_key))
    total_value = b'$$'.join((pre_v, end_v))

    user_hash = b64encode(total_value).decode(encoding='utf-8')
    return user_hash

def check_password(user_hash, asserted_pw):
    if not isinstance(asserted_pw, bytes):
        asserted_pw = convert_to_bytes(asserted_pw, 'password')

    user_hash = b64decode(user_hash.encode('utf-8'))

    h_i, s_k = user_hash.split(b'$$')
    hash_name, iterations = h_i.decode('utf-8').split('$')
    salt, key = s_k.split(b'$s_k$')

    try:
        asserted_key = hashlib.pbkdf2_hmac(hash_name, asserted_pw,
                                           salt, int(iterations))
        del asserted_pw
    except ValueError as error:
        print('[!] Error cused %s' % error)

    if key == asserted_key:
        return True
    else:
        return False


texts:
Context: I wrote a simple as an answer to a problem in Unix.SE and it was suggested to me to post it here for review.

A comma separated file is generated by an application. On the first column it contains a last name, on the second a first name and on the tenth column a telephone number. For each row of this csv an vcard entry should be generated.

This was my solution:

#!/usr/bin/python

import csv
import sys

def convert(file):
    reader = csv.reader(open(file, 'rb'))

    for row in reader:
        print 'BEGIN:VCARD'
        print 'VERSION:2.1'
        print 'N:' + row[0] + ';' + row[1]
        print 'FN:' + row[1] + ' ' + row[0]
        print 'TEL;HOME;VOICE:' + row[9]
        print 'END:VCARD'

def main(args):
    if len(args) != 2:
        print "Usage:"
        print args[0] + " filename"
        return

    convert(args[1])

if __name__ == '__main__':
    main(sys.argv)

Outputting the generated vcard on stdout was fine for me, I just redirected it into an appropriate file.


texts: 2D Array Word Search: Complexity and Optimization

texts:
Objective
Determine whether a given word is contained in a 2D Array word search.
 Question
1. What are the time and space complexities of the current algorithm?
Time complexity
Linear: \$O(2(r * n))\$
There are iterations through the outer and inner loops for the rows and columns occurring twice, once for the horizontal search, and once for the vertical search.
Space complexity
Constant: \$O(1)\$
The only data stored is the currentSearch string that will not grow based on the size of the word search.
2. How can the time complexity be optimized?

If the currentSearchIndex == 0, skip rows/columns that do not contain the first character of the word that is being searched for.

 Implement

Iterate through the 2D Array for the word to find both horizontally and vertically.
Horizontally: Outer loop iteration is rows, inner loop iteration is columns
Vertically: Outer loop iteration is columns, inner loop iteration is rows

Sample
Input
findWord(
    arrayOf(
        arrayOf("b", "r", "n"),
        arrayOf("a", "s", "h"),
        arrayOf("z", "x", "y")
    ),
    "ash"
)

Output
true
Code
fun findWord(wordSearch: Array<Array<String>>, word: String): Boolean {
    checkArgErrors(wordSearch, word)
    return horizSearch(wordSearch, word) || vertSearch(wordSearch, word)
}

fun horizSearch(wordSearch: Array<Array<String>>, word: String): Boolean {
    for (r in wordSearch) {
        var currentSearch = ""
        var currentSearchIndex = 0
        for (c in r) {
            if (word.substring(currentSearchIndex, currentSearchIndex + 1).equals(c.toString())) {
                currentSearch += c
                currentSearchIndex++
                if (currentSearch.equals(word))
                    return true
            } else {
                currentSearch = ""
                currentSearchIndex == 0
            }
        }
    }
    return false
}
fun vertSearch(wordSearch: Array<Array<String>>, word: String): Boolean {
    for (cIndex in 0 .. wordSearch[0].size - 1) {
        var currentSearch = ""
        var currentSearchIndex = 0
        for (rIndex in 0 .. wordSearch.size - 1) {
            println("c:${wordSearch[rIndex][cIndex]}")
            val currentChar = word.substring(currentSearchIndex, currentSearchIndex + 1)
            if (currentChar.equals(wordSearch[rIndex][cIndex].toString())) {
                currentSearch += currentChar
                currentSearchIndex++
                if (currentSearch.equals(word)) return true
            } else {
                currentSearch = ""
                currentSearchIndex == 0
            }
        }
    }
    return false
}

fun checkArgErrors(wordSearch: Array<Array<String>>, word: String) {
    val exception =
            if (wordSearch.size == 0 || wordSearch[0].size == 0) "The word search cannot be empty."
            else if (word.isEmpty()) "Cannot search for an empty word."
            else if (word.length > wordSearch[0].size || word.length > wordSearch.size)
                "The word is too long to search for within the word search."
            else null
    if (exception != null)
        throw IllegalArgumentException(exception)
}


texts: Flagging employees whose spending is close to the budgeted amount

texts:
I am working with an SQLite database. Is this code written the best way it can be and correct? The code:

Selects from the db adding a column for the percentage difference between two columns
Loops through the values of the columns
If the date is in the past
If the price is greater than 500 and the percentage difference is less than 1st argument set flag to 1
Else if the price is less than 500 and the percentage difference is less than 2nd argument set flag to 1
Otherwise keep the flag as 0

from datetime import datetime as dt

def calculateEmployeeSpend(read_cursor, flag_higher_amount, flag_lower_budget):

    read_cursor.execute("SELECT distinct b.employee_id, b.amount, "
                "s.spend, b.date, b.amount - s.spend as spend_left,  "
                "100.0*(b.amount - s.spend) / b.amount As PercentDiff FROM employee_budget_upload "
                "As b JOIN employee_budget_spent As s ON  b.employee_id = s.employee_id where b.amount != 0")

    for employee_id, amount, spend, date, spend_left, percent_diff in read_cursor:
        flag=0
        date_of_amount = dt.strptime(date, "%d/%m/%Y")
        if date_of_amount <= dt.now():
            if amount > 500 and percent_diff < int(flag_higher_amount) or amount < 500 and percent_diff < int(flag_lower_budget):
                flag=1

        write_cursor.execute('INSERT OR REPLACE INTO employee_overall_spend VALUES (?,?,?,?,?,?,?,?)',
                         (employee_id, amount, spend, date, spend_left, percent_diff, dt.now().strftime("%d/%m/%Y"), flag))


texts: Browser freeze - How to handle or optimize 50,000 rows in one HTML select element more than several times?

texts:
I have an increasing table which already has records of 50,000+.
So in a combo box I have to load it, so that it shows which one is selected and its a main record which need to be selected and based on that it spread other relational records. But when I load it the whole web browser freeze.

How do you handle it?

My controllers:

$sql = "select name,name from countryCity";
$secondResult = $this->db->fetchPairs($sql);
$this->view->selectitems = array(''=>'') + $secondResult;

My view file:

<?for($i=0; $i<10; $i++):?>
<?=$this->formSelect("a",
                     "select one",
                     array('class'=>'largetosmall'),
                     $this->selectitems)?>

<?endfor;?>

Output:

<select class=largetosmall id=a>
 <option>...</option>
 <option>50,000+++... records</option>
</select>

More than 10 times I have a huge select element in one page. Never working.


texts:
SPOJ problem PRIME1 (also found on other sites in identical form):

  Input

  The input begins with the number t of test cases in a single line
  (t<=10). In each of the next t lines there are two numbers m and n (1
  <= m <= n <= 1000000000, n-m<=100000) separated by a space.

  Output

  For every test case print all prime numbers p such that m <= p <= n,
  one number per line, test cases separated by an empty line.

My Answer:

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

int main() {
    int iter = 0;
    scanf("%d",&iter);
    while(iter--) {
        long num1, num2;
        scanf("%ld%ld",&num1,&num2);

        long prime[60000];
        prime[0] = 2;
        long prime_count = 1;
        long result[60000];
        long result_count = 0;

        if(num1 <= 2){
            result[0] = 2;
            result_count++;
            printf("2\n");
        }

        for(long i = 3; i <= num2; i++) {
            int isPrime = 1;

            for(long j = 0; j < prime_count; j++) {
                if(i % prime[j] == 0) {
                    isPrime = 0;
                    break;
                }
            }
            if(isPrime) {
                prime[prime_count] = i;
                prime_count++;
                if(i >= num1){
                    result[result_count] = i;
                    result_count++;
                    printf("%ld\n",i);
                }
           }
        }
        printf("\n");
    }

    return 0;
}

Is there any way to improve my code?


texts:
Simple really my javascript function for checking my form.

var errors = {};
errors.email = true;
errors.cemail = true;
errors.password = true;
errors.cpassword = true;
errors.username = true;
function joinAjax (id) {

var val = $('#' + id).val();
if (id == 'email') {

    $('#emailMsg').hide();
    var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    if (val == '') {

        $('#' + id).after('
Enter your email
');
    }
    else if (reg.test(val) == false) {

        $('#' + id).after('
Email invalid
');
    }
    else {

        errors.email = false;
        $('#' + id).after('
Email OK
');
    }
    joinAjax('cemail');
}
if (id == 'cemail') {

    $('#cemailMsg').hide();
var email = $('#email').val();
    if (errors.email == false) {

        if (val != email) {

            $('#' + id).after('
Emails do not match
');
        }
        else {

            errors.cemail = false;
            $('#' + id).after('
Success
');
        }
    }
    else {

        $('#cemail').val('');
    }
}
if (id == 'password') {

    $('#passwordMsg').hide();
    if (val == '') {

        $('#' + id).after('
Enter a password
');
    }
    else if (val.length < 6) {

        $('#' + id).after('
Minimum length of 6
');
    }
    else {

        errors.password = false;
        $('#' + id).after('
Password OK
');
    }
    joinAjax('cpassword');
}
if (id == 'cpassword') {

    $('#cpasswordMsg').hide();
    var password = $('#password').val();
    if (errors.password == false) {

        if (val != password) {

            $('#' + id).after('
Passwords do not match
');
        }
        else {

            errors.cpassword = false;
            $('#' + id).after('
Success
');
        }
    }
    else {

        $('#cpassword').val('');
    }
}
if (id == 'username') {

    $('#usernameMsg').hide();
    if (val == '') {

        $('#' + id).after('
Enter a username
');
    }
    else if (val.length < 3) {

        $('#' + id).after('
Minimum length is 3
');
    }
    else {

        errors.username = false;
        $('#' + id).after('
Available
');
    }
}
$('#joinForm').submit(function(event){

    if ((errors.email == true) || (errors.cemail == true) || (errors.password == true) || (errors.cpassword == true) || (errors.username == true)) {

        event.preventDefault();
    }
    return true;
});
}

Can this be improved? I was looking for a way to create a function for the submit event, but I can't figure it how as I don't know how many parameters I will need each time.


texts:
Inspired by this question I thought I provide my implementation. I tried to go with the spirit of the *nix tool chain - read from stdin and write to stdout. This has the added benefit of making buffering very easy (current and previous characters and the count).

All kinds of reviews welcome (best practices, error handling, weird edge cases, potential bugs or other pitfalls).

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>

void write_char(int c)
{
    if (EOF == putchar(c))
    {
        if (ferror(stdout))
        {
            perror("error writing char to stdout");
            exit(EXIT_FAILURE);
        }
    }
}

void write_count(uint64_t count)
{
    if (printf("%ull", count) < 0)
    {
        perror("error writing character count to stdout");
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char** argv)
{
    int current_char = 0;
    int previous_char = 0;
    uint64_t current_char_count = 0;

    while (EOF != (current_char = getchar())
    {
        if (current_char_count == 0 || current_char_count == UINT64_MAX || previous_char != current_char)
        {
            if (current_char_count > 0)
            {
                write_count(current_char_count);
            }
            write_char(current_char);
            current_char_count = 1;
            previous_char = current_char;
        }
        else
        {
            current_char_count += 1;
        }
    }
}


texts:
This integration test involves database access and hence opening and closing a database connection. Does it look correct? I am concerned about ensuring the the database connection is closed should the test fail.

"use strict";

describe("MyCtorFunction", function () {

  describe("myMethod", function () {
    var _db = null,
        _testContext = null;

    beforeEach(function () {
      _testContext = {};
      new DbHelper().openConnection(function (err, dbConnection) {
        if (err) {
          throw err;
        }

        _db = dbConnection;
      });

      waitsFor(function () {
        return _db;
      }, "establishing a connection to the database.", 5000);
    });

    afterEach(function () {
      waitsFor(function () {
        return _testContext.assertions.callCount === 1;
      }, "waiting for the assertions to be called.", 5000);

      runs(function () {
        if (_db) {
          _db.close();
          _db = null;
        }
      });
    });

    it("should do something", function () {
      runs(function () {
        //arrange
        _testContext.assertions = assertions;
        spyOn(_testContext, "assertions").andCallThrough();

        //act (_testContext.assertions invoked as callback)
        new MyCtorFunction(_db).myMethod(_testContext.assertions);

        //assert
        function assertions(err, config) {
          expect(config).toNotBe(null);
          //etc.
        }
      });
    });
  });
});