texts:
In the pursuit of learning F#, I have been working through some Project Euler problems.

This is my solution for problem 3:

open System
open System.Collections.Generic

let number = 600851475143L
let limit = Convert.ToInt32(sqrt (float number))

let sieve = Array.create (limit+1) true
sieve.SetValue(false,0)
sieve.SetValue(false,1)

let rec markNotPrime prime multiple =
    if multiple > limit then prime
    else
        sieve.SetValue(false, multiple)
        let nm = prime+multiple
        markNotPrime prime nm

let smallPrimes =
    Seq.unfold(fun a -> Some(a, (a+1))) 2
    |> Seq.takeWhile(fun a -> a <= limit)
    |> Seq.filter( fun a -> sieve.[a])
    |> Seq.map( fun a ->
        let b = a+a
        markNotPrime a b)
    |> Seq.filter( fun a -> number % (int64 a) = 0L)

let bigPrimes = new List<int>()

let rec addBigPrime potentialPrime =
    match potentialPrime with
    | p when bigPrimes.Contains(potentialPrime) ->
        ignore()
    | p when smallPrimes |> Seq.forall(fun a -> (potentialPrime % a) <> 0) ->
        bigPrimes.Add(p)
    | _ ->
        smallPrimes
            |> Seq.filter(fun a ->
                (potentialPrime % a) = 0)
            |> Seq.iter(fun a ->
                addBigPrime (potentialPrime / a))

smallPrimes
    |> Seq.map(fun a -> (int (number/(int64 a))))
    |> Seq.iter(addBigPrime)

let answer = smallPrimes |> Seq.append(bigPrimes) |> Seq.max

printfn "smallPrimes: %A" smallPrimes
printfn "bigPrimes: %A" bigPrimes
printfn "answer: %d" answer

I am aware of how simply this could have been done, but I was trying to do this in a vacuum as much as possible.

I am new to both prime factorization and F#; however, I am really only looking for comments on F#, not how poorly my factorization algorithm works (I know it's bad) i.e. what style mistakes am I making, or how the code could be made more functional.

Of particular interest, where do you think I am missing the mark entirely?

Update

After thinking more about my solution overnight, I had more thought about exactly what my solution was doing, and why the simpler methods are so much simpler.

During my research on factoring primes, I think I got too caught up in the sieve of Eratosthenes, and didn't focus on the actual problem.

What I should have been trying to do:

Search for the smallest prime factor
Once found save it to the list of prime factors
Divide this factor out of the number to be factored
Repeat from step 1 substituting the number to be factored with the quotient from step 3, and start the search from the prime factor found in step 2.
Get the biggest prime from the list.

What I actually did:

Search for all prime numbers from 2 to the square root of the number to be factored.
During the search, check each prime to see if it divides evenly.
Once complete divide each of these "small primes" to generate a list potential big primes.
Divide each of the big primes by all of the small primes as a test for primality.
Combined the lists, and get the biggest one.


texts: Thread that monitors a web API to get the latest announcement via JSON

texts:
I'm working to make a thread that monitors a web API to get the latest announcement via JSON. I cannot test this currently, so I'm unsure if anything needs to be changed with this. I've read through other questions but everyone else doesn't seem to be using a loop to keep getting a response.

public void run(){
    try {
        URL url = new URL(announcementsURL);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod("GET");
        http.setRequestProperty("Connection", "keep-alive");
        http.setUseCaches(false);
        http.setAllowUserInteraction(false);
        http.setConnectTimeout(10);
        http.setReadTimeout(10);
        while (true){
            http.connect();
            int status = http.getResponseCode();
            if (status == 201){
                BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                String json = sb.toString();
                JSONParser parser = new JSONParser();
                JSONObject jsonResponse = (JSONObject) parser.parse(json);
                if (!(lastAnnouncement == (long) jsonResponse.get("time"))){
                    //String announcement = (String) jsonResponse.get("message");
                    //TODO What to do with announcement...
                }
            }
            http.getInputStream().close();
            http.disconnect();
        }

    } catch (IOException | ParseException e) {
        e.printStackTrace();
        this.interrupt();
        try {
            this.join();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }
}


texts:
I'm actually spending time on it, unlike the first time and going through, understanding and implementing the several suggestions I've landed on two different approaches.

Approach 1: Employing Java 8 Lambdas and stream functions made to be the equivalent of David Zheng's answer in Python.

import java.util.ArrayList;

public class Euler5 {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        final long MAX_NUM = 20L;

        ArrayList<Long> numbers = new ArrayList<Long>() {
            { for (long i = 1L; i <= MAX_NUM; i++) { add(i); } }
        };

        long result = numbers
            .stream().reduce(Euler5::lcm).get();

        System.out.print("Result: " + result +
                ".\nTime used for calculation in nanoseconds: " +
                (System.nanoTime() - startTime) + ".");
    }

    /*Greatest Common Divisor
    Euclidean algorithm: http://en.wikipedia.org/wiki/Euclidean_algorithm */
    public static long gcd(long a, long b) {
        return b == 0 ? a : gcd(b, a % b);
    }
    // Least Common Multiple
    public static long lcm(long a, long b) {
        return (a * b) / gcd(a, b);
    }
}

Sample output:

  Result: 232792560.
  Time used for calculation in nanoseconds: 111370744.

Approach 2: More similar to my original method, using several suggestions, including one in the OP's comment section which I'm unsure about.

public class Euler5 {
        public static void main(String[] args) {
            long startTime = System.nanoTime();
            // Multiplying by primes for a starting point * 2 for evenness
            int givenTimesPrimes = 2520 * 2 * 11 * 13 * 17 * 19,
                result = givenTimesPrimes;

            while (!isSmallestMultiple(result)) {
                result += givenTimesPrimes;
            }

            System.out.print("Result: " + result +
                ".\nTime used for calculation in nanoseconds: " +
                (System.nanoTime() - startTime) + ".");
        }

        public static boolean isSmallestMultiple(int n) {
            for (int i = 11; i <= 20; i++) {
                if (n % i != 0) {
                    return false;
                }
            }
            return true;
        }
    }

Example output:

  Result: 232792560.
  Time used for calculation in nanoseconds: 141635.

Approach 2 is clearly faster, but I'm wondering if givenPrimes qualify as "magic numbers?" Or is the explanation enough (feels tenuous/not 100% certain it would qualify as an effective strategy in a different context).
The first method seems the more understandable/applicable. Am I wrong? Which would you fellow CR folks prefer and why?


texts: Easy-to-use C++ class for asking current time stamp in milli-, micro- and nanoseconds

texts:
I have to benchmark my code often, and decided that it is about time to implement an easy API for that:

current_time.h:

#ifndef CURRENT_TIME_H
#define CURRENT_TIME_H

#include <chrono>
#include <cstdint>

class CurrentTime {
    std::chrono::high_resolution_clock m_clock;

public:
    uint64_t milliseconds();
    uint64_t microseconds();
    uint64_t nanoseconds();
};

#endif  /* CURRENT_TIME_H */

current_time.cpp:

#include "current_time.h"

uint64_t CurrentTime::milliseconds()
{
    return std::chrono::duration_cast<std::chrono::milliseconds>
              (m_clock.now().time_since_epoch()).count();
}

uint64_t CurrentTime::microseconds()
{
    return std::chrono::duration_cast<std::chrono::microseconds>
              (m_clock.now().time_since_epoch()).count();
}

uint64_t CurrentTime::nanoseconds()
{
    return std::chrono::duration_cast<std::chrono::nanoseconds>
              (m_clock.now().time_since_epoch()).count();
}

main.cpp:

#include <iostream>
#include "current_time.h"

using namespace std;

int main(int argc, char** argv) {
    CurrentTime current_time;

    uint64_t start1 = current_time.milliseconds();
    uint64_t start2 = current_time.microseconds();
    uint64_t start3 = current_time.nanoseconds();

    for (int i = 0; i < 100000000; ++i) {

    }

    uint64_t end1 = current_time.milliseconds();
    uint64_t end2 = current_time.microseconds();
    uint64_t end3 = current_time.nanoseconds();

    cout << "Milliseconds: "   << (end1 - start1)
         << ", microseconds: " << (end2 - start2)
         << ", nanoseconds: "  << (end3 - start3)
         << ".\n";

    return 0;
}

Any critique is much appreciated, yet I would like to hear your opinions on returning uint64_t: is there some implicit conversions going on?


texts: Find the kth element which is either divisible by l or r or both

texts:
This was asked to me in one of interview, so can someone please have a look is my code efficient or we can further improve it.

Example

Input  l=2 r=3 k=10

Output:  15

Explanation 15 is at the 10 position of number divisible by 2 or 3 or both.

{2, 3, 4, 6, 8, 9, 10, 12, 14, 15} 15 is at 10th position.

Assumption: L < R

Code

int main()
{
    long long int l, r, k;
    cin>>l>>r>>k;
    int lValue=l*k;
    int numberofElemtsin_l_Range=k+lValue/r - lValue/(l*r);
    if(numberofElemtsin_l_Range>=k)
    {
        int i, j;
        for(i=numberofElemtsin_l_Range, j=lValue; i>=k; j--)
        {
            if(j%l==0 || j%r==0) i--;
        }
        cout<<j+1;
    }
    else
    {
        int rValue = rValue*k;
        int numberofElemtsin_R_Range= k + rValue/l - rValue/(l*r);
        if(numberofElemtsin_l_Range>=k)
        {
            int i, j;
            for(i=numberofElemtsin_R_Range, j=rValue; i>=k; j--)
            {
               if(j%l==0 || j%r==0) i--;
            }
            cout<<j+1;
        }
    }
    return 0;
}


texts: Drawing an Archimedean spiral using Pillow

texts:
From Rosetta Code:

  The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. It can be described by the equation:
  $$r=a+b\theta$$
  with real numbers \$a\$ and \$b\$.

Here is my attempt to draw it in Python (using Pillow):

"""This module creates an Archimdean Spiral."""

from math import cos, sin, pi
from PIL import Image, ImageDraw

def translate(point, screen_size):
    """
    Takes a point and converts it to the appropriate coordinate system.
    Note that PIL uses upper left as 0, we want the center.
    Args:
        point (real, real): A point in space.
        screen_size (int): Size of an N x N screen.
    Returns:
        (real, real): Translated point for Pillow coordinate system.
    """
    return point[0] + screen_size / 2, point[1] + screen_size / 2

def draw_spiral(a, b, img, step=0.5, loops=5):
    """
    Draw the Archimdean spiral defined by:
    r = a + b*theta
    Args:
        a (real): First parameter
        b (real): Second parameter
        img (Image): Image to write spiral to.
        step (real): How much theta should increment by. (default: 0.5)
        loops (int): How many times theta should loop around. (default: 5)
    """
    draw = ImageDraw.Draw(img)
    theta = 0.0
    r = a
    prev_x = int(r*cos(theta))
    prev_y = int(r*sin(theta))
    while theta < 2 * loops * pi:
        theta += step
        r = a + b*theta
        # Draw pixels, but remember to convert to Cartesian:
        x = int(r*cos(theta))
        y = int(r*sin(theta))
        draw.line(translate((prev_x, prev_y), img.size[0]) +
                  translate((x, y), img.size[0]), fill=1)
        prev_x = x
        prev_y = y

if __name__ == '__main__':
    IMAGE_SIZE = 300, 300
    img = Image.new('1', IMAGE_SIZE)
    draw_spiral(1, 2, img)
    img.save('spiral.png')

The program outputs this image:


texts: Parsing Oracle errors with a ksh function

texts:
Some time ago I wrote a small routine to run some quick n' dirty queries (and with that I mean it is not used for large queries) against an Oracle DB, but also wanted to do it a bit easier to parse errors.

# Executes the query
#
# Will execute a query contained in the variable named
# in the parameter $4 and store the result in the variable
# named in $5.
# In case of errors (even SQL related) the function should
# exit with status 1, making it possible to "if execQuery".
#
# @param    $1 = User
#           $2 = Pasword
#           $3 = Tns Alias
#           $4 = Name of the variable containing the query
#           $5 = Name of the variable to hold the result
#
# @return   query execution status
function execQuery {
    typeset eSQLU=$1
    typeset eSQLP=$2
    typeset eSQLS=$3
    typeset etQUERY=$4
    eval typeset eQUERY=\$$etQUERY
    typeset eQRES=$5
    logMessageFile "DEBUG" "Query: $eQUERY"

    typeset res=$(sqlplus -s $eSQLU/$eSQLP@$eSQLS <<EOF
set echo off newpage 0 space 0 pagesize 0 feed off head off verify off lines 999
WHENEVER SQLERROR EXIT 1
$eQUERY
exit;
EOF
)
    [[ $? -gt 0 ]] && return 1 || eval "$eQRES=\"$res\""

}

The idea of this function is that later I could do something like:

query="select sysdate from dual;"
if execQuery $RAID_APP_PI_USR $RAID_APP_PI_PWD $RAID_APP_PI_SID query result ; then
    echo $result
    logMessageFile "INFO" "Inserts into XX successful."
else
    logMessageFile "ERROR" "Error insertando XXX."
fi

It kinda works. A properly written query will do it fine, and the result variable is all correctly evaluated and all. The problem are the errors. If the query in that example was something like select * potato potato;, It'd still not yield the correct return value thus missing the error test.

I'm not particularly good with SQL*Plus nor ksh and am probably just missing something obvious. Could someone lend me a hand here?


texts: Removing duplicates from list and filtering non-letter characters

texts:
I'm just starting out in Haskell and have been set an assignment for uni where I have to create a reverse index of words in a text file and find what line numbers they appear on. I also have to remove any stop words like "the" or "and" that aren't needed.

So far I have this, but I feel that there should be a better way to remove duplicates from a list and to filter by non-letters:

module Main where
import qualified Data.List as List
import qualified Data.Char as Char
import qualified Data.Set as Set
import qualified Data.Maybe as Maybe

main = do
    -- load file to be indexed and stop words
    text <- readFile "test.txt"
    stopWords <- readFile "stopWords.txt"

    -- convert all chars to lower case, split by lines, then split by words
    let word = map words (lines (map Char.toLower text))
    let stopWord = map words (lines (map Char.toLower stopWords))

    -- concatenate lists, remove non letters, then remove any empty list elements
    let word' = filter (not.null) (map (filter Char.isLetter) (concat word))
    let stopWord' = filter (not.null) (map (filter Char.isLetter) (concat stopWord))

    -- cast both lists to a set to remove duplicates and remove any instances of stopWord' from word'
    let index = Set.toList (Set.difference (Set.fromList word') (Set.fromList stopWord'))

    -- get line numbers from indexed words
    let lineNumbers = generateIndex index word

    -- zip index of words with line numbers and print
    mapM print (List.zip index lineNumbers)

generateIndex :: [String] -> [[String]] -> [[Int]]
generateIndex xs y = foldr (\ x -> (++) [getLineNumbers x y]) [] xs

getLineNumbers' :: String -> [[String]] -> Int -> [Int]
getLineNumbers' x [] n = []
getLineNumbers' x (y:ys) n
    | x `elem` y = n : getLineNumbers' x ys (n + 1)
    | otherwise = getLineNumbers' x ys (n + 1)

getLineNumbers :: String -> [[String]] -> [Int]
getLineNumbers x y = getLineNumbers' x y 1


texts:
I have written the code below as a BFS implementation. Could someone please review. In particular, I want to know if there could be a memory leak.

#include <iostream>
#include <list>

class Graph
{
  int number_of_vertices;
  std::list<int> *adjList;

  public:
          Graph(int number_of_vertices);
          void addEdge(int first_vertex, int second_vertex);
          void BFS(int vertex);
};

Graph::Graph(int number_of_vertices)
{
  this->number_of_vertices = number_of_vertices;
  adjList = new std::list<int>[number_of_vertices]; // Allocates space for list equal to number_of_vertices.
}

void Graph::addEdge(int first_vertex, int second_vertex)
{
  adjList[first_vertex].push_back(second_vertex);
}

void Graph::BFS(int vertex)
{

  bool *visited = new bool [number_of_vertices];

  for (int i = 0; i < number_of_vertices; i++)
  {
      visited[i] = false;
  }

  visited[vertex] = true; // Mark the vertex as visited
  std::list<int> queue;
  queue.push_back(vertex);

  while(!queue.empty())
  {
    vertex = queue.front();
    std::cout << vertex << " ";
    queue.pop_front();

    for(auto it = adjList[vertex].cbegin(); it!= adjList[vertex].cend(); ++it)
    {
      if(!visited[*it])
      {
        visited[*it] = true; // Mark the vertex as visited
        queue.push_back(*it);
      }
    }

  }
}

// Driver Program
int main()
{
    // Create a graph
    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);

    std::cout << "Following is Breadth First Traversal "
         << "(starting from vertex 2) \n";
    g.BFS(2);

    return 0;
}


texts:
This is my simple Fibonacci implementation in CoffeeScript. What do you think?  Using cache (fibResults), it's very very fast.

fibResults = []
defaultMax = 1000
nrMax = defaultMax

fibonacci = (n) ->
  return fibResults[n] if fibResults[n]

  if n < 2
    fibResults[n] = n
  else
    fibResults[n] = fibonacci(n - 1) + fibonacci(n - 2)

nrMax = process.argv[2] if process.argv[2]

console.log("#{i}: #{fibonacci(i)}") for i in [0..nrMax]


texts:
It's sometimes useful to pause until a specified time (but inconvenient to use at or the like), so I wrote a tiny script to wait until a user-specified time point is reached.

I use this when I want to keep the output of preceding and subsequent commands together, but I don't mind blocking the current terminal.  Quite often, this would be M-xcompile when I want to wait until after new source code/data have been uploaded, but still have the results in a compilation-mode buffer.

Although it's a very short script, my time at Code Review has taught me that almost any program has something that can be improved, so please make your suggestions!

#!/bin/sh

# Sleep until the specified time

# Accepts any date/time format accepted by 'date'

# Assumes GNU date and GNU sleep

die() {
    echo "$@" >&2
    exit 1
}

usage() {
    echo "Usage: $0 TIME"
}

test $# = 1 || die $(usage)

case "$1" in
    --version)
        echo "sleep_until version 1.0"
        exit 0
        ;;
    --help)
        usage
        exit 0
        ;;
    -*)
        die "Unrecognised option: $1"
        ;;
    *)
        end=$(date -d "$1" +%s.%N)
        now=$(date +%s.%N)
        test ${end%.*} -gt ${now%.*} || die "$1 is in the past!"
        exec sleep $(echo $end $now - p | dc )
        ;;
esac

Notes:

We need GNU date for its -d option and a good range of input formats.
GNU sleep handles fractional seconds; we could remove .%N from the date formats to work with traditional/POSIX sleep.
I've used dc for the arithmetic so we can use plain sh rather than requiring a more heavyweight shell.


texts:
I'm finishing the book C Primer Plus by Stephen Prata and I wrote as a part of the homework program to convert binary string to decimal number:

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

typedef unsigned char byte;
typedef unsigned int uint;

int strbin_to_dec(const char *);

int main(void) {
    char * wbin = "01001001";
    printf("%s to dziesietnie %d.\n", wbin, strbin_to_dec(wbin));
    return 0;
}

int strbin_to_dec(const char * str) {
    uint result = 0;
    for (int i = strlen(str) - 1, j = 0; i >= 0; i--, j++) {
        byte k = str[i] - '0'; // we assume ASCII coding
        k <<= j;
        result += k;
    }
    return result;
}

Questions:

How's the efficiency of this program?
Are byte operations faster than
normal?


texts:
I have two lists of the same type and I want to be able view a list of both lists:

    public List<Page> HeaderPages;
    public List<Page> SurveyPages;

    public IReadOnlyList<Page> AllPages
    {
        get
        {
            List<Page> allPages = new List<Page>();
            allPages.AddRange(this.HeaderPages);
            allPages.AddRange(this.SurveyPages);
            return allPages;
        }
    }

I think it is very inefficient to keep creating a new list object each time I want to get AllPages, so I thought I could store a private allPages list.  But then I thought if I am in the class, I would have to remember to use the public AllPages rather than the private allPages - which may not be up-to-date.

Any elegant solutions?


texts: Number of right cyclic shifts to give the biggest number

texts:
I am preparing to coding interview and I met this task today:

You are given 30-bit unsigned integer N. A right cyclic shift of N by K bits is the result of performing a right cyclic shift of N by one bit K times. Leading zeros may appear.

For example:

the right cyclic shift of 9736 by one bit is 4868,
the right cyclic shift of 9736 by two bits is 2434,
the right cyclic shift of 9736 by eleven bits is 809500676

The number 809500676 is the largest value that can be obtained by performing a right cyclic shift of 9736.

The aim is to find integer K such that right cyclic shift of N by K bits gives the largest possible value. In example above method should return 11. 0<=N<=1073741823. Worst-case time complexity is O(log(N)).

My try should be correct value but does not meet (in my opinion, but I am not sure) time complexity.

    public int solution(int N) {
        long m = N;
        long max = N;
        int res = 0;
        for(int i =1;i<30;i++) {
            m=(N>>>i) & 0x3fffffff | (N<<(30-i)& 0x3fffffff);
            if(m>max) {
                max=m;
                res=i;
            }
        }
        return res;
    }


texts: SPOJ "TESSER" - Getting TLE using KMP algorithm

texts:
The TESSER - Finding the Tesserect problem is tagged as a problem to be solved by Knuth-Morris-Pratt (KMP) algorithm. I'm using KMP, but am still getting time-limit-exceeded.

Task

Each of T test cases (1 ≤ T ≤ 105) consists of three lines:

A single integer N (2 ≤ N ≤ 105) denoting the number of data points.
N integers (ai, where 1 ≤ ai ≤ 109)
A message pattern (a string consisting only of letters G, L, and E).

In the sequence of ai, each element may be greater than (G), less than (L), or equal to (E) the preceding element.  Find out whether there is some substring of consecutive elements within the sequence that matches the given message pattern, and print "YES" if it is found or "NO" if it is not found.

Example

Input:

1
5
1 2 3 4 1
GGL

Output:

YES

The answer is "YES", because 2 3 4 1 satisfies the pattern GGL, i.e. 3 is greater than 2, 4 is greater than 3, 1 is less than 4.

Here is the code that I submitted:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    string text, pattern;
    vector<int> computePrefixFunction(string p);
    vector<long long int> v;
    int no, test_case;
    long long value;
    cin >> test_case;
    while(test_case)
    {
        cin >> no;
        bool flag = false;
        for(int i = 0; i < no; ++i)
        {
            cin >> value;
            v.push_back(value);
        }

        for(int i = 0; i < (no - 1); ++i)
        {
            if(v[i+1] > v[i])
                text = text + 'G';
            else if(v[i] == v[i+1])
                text = text + 'E';
            else
                text = text + 'L';
        }
        v.clear();
        cin >> pattern;
        int n = no - 1;
        int m = pattern.length();
        vector<int> pi = computePrefixFunction(pattern);
        int q = -1;
        for(int i = 0; i < n; ++i)
        {
            while(q > -1 && pattern[q+1] != text[i])
                q = pi[q];
            if(pattern[q+1] == text[i])
                q = q + 1;
            if(q == (m-1))
            {
                flag = true;
                break;
            }
        }

        if(flag == true)
            cout << "YES\n";
        else
            cout << "NO\n";
        pi.clear();
        test_case = test_case - 1;
    }
    return 0;
}

vector<int> computePrefixFunction(string p)
{
    int m = p.length();
    vector<int> pi;
    pi.push_back(-1);
    int k = -1;
    for(int q = 1; q < m; ++q)
    {
        while(k > -1 && p[k+1] != p[q])
            k = pi[k];
        if(p[k+1] == p[q])
            k = k + 1;
        pi.push_back(k);
    }
    return pi;
}


texts: JavaScript Determine if Array has Almost Increasing Sequence

texts:
A coding challenge on a website says to determine if an array would have an increasing sequence if one element were removed from that array.

Here is the function:

const almostIncreasingSequence = sequence => {
  const increasingSequence = arr => {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i - 1] >= arr[i]) {
        return false;
      }
    }
    return true;
  };
  for (let i = 0; i < sequence.length; i++) {
    const left = sequence.slice(0, i);
    const right = sequence.slice(i + 1);
    const newArr = left.concat(right);
    if (increasingSequence(newArr)) {
      return true;
    }
  }
  return false;
};

The function produces the exact same output as all of the visible tests on the site:

var toTest = [
  [1, 3, 2, 1],
  [1, 3, 2],
  [1, 2, 1, 2],
  [1, 4, 10, 4, 2],
  [10, 1, 2, 3, 4, 5],
  [1, 1, 1, 2, 3],
  [0, -2, 5, 6],
  [1, 2, 3, 4, 5, 3, 5, 6],
  [40, 50, 60, 10, 20, 30],
  [1, 1],
  [1, 2, 5, 3, 5],
  [1, 2, 5, 5, 5],
  [10, 1, 2, 3, 4, 5, 6, 1],
  [1, 2, 3, 4, 3, 6],
  [1, 2, 3, 4, 99, 5, 6],
  [123, -17, -5, 1, 2, 3, 12, 43, 45],
  [3, 5, 67, 98, 3]
];

for (let i = 0; i < toTest.length; i++) {
  console.log(almostIncreasingSequence(toTest[i]));
}

Outputs:

false
true
false
false
true
false
true
false
false
true
true
false
false
true
true
true
true

But then a hidden error triggers upon submission telling me that the execution time is longer than the maximum of 4 seconds. How can I improve the time complexity of this algorithm?


texts:
I have a table with forms in two colors - the first row is one color, the second is the other. Can you please tell me if there is a way to optimize my code (such as with this)?

I have two CSS classes:

tr.content1{
    background-color: #EFF4FA;
}

tr.content2{
    background-color: #F7FAFD;
}

And the table looks this way:

        Previous Plan:
        {{ form_row(form.prev_plan) }}

        Previous Server:
        {{ form_row(form.prev_srv) }}

There is also a problem this way - I get some text in the second column in front of the form field.


texts: Make two random enemies shoot projectiles every second

texts:
Just finished my canvas game that is more or less replica of the old school arcade game "Space Invaders".
The code below chooses two random enemies every second (approximately) from the enemies array to shoot projectiles. If there are two or more enemies left in the array I want two random enemies to shoot every second and if there is only one enemy left only that enemy will shoot every second.
I have two solutions for this problem. Both of them work. However the first one seems quite unnecessary repetitive and the second solution although short and elegant is probably unnecessary more "expensive". Keep in mind I am beginner and I might be wrong here with my assumptions and conclusions.
First solution:
let req;
let timer = 0
function animate() {
  req = requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // other game logic

  // two random enemies shoot every second
  if (timer % 60 === 0 && timer !== 0) {
    let enemiesLength = enemies.length;
    if (enemiesLength > 2) {
      let rndIndex_1;
      let rndIndex_2;
      rndIndex_1 = Math.floor(Math.random() * enemiesLength);
      do {
        rndIndex_2 = Math.floor(Math.random() * enemiesLength)
      } while (rndIndex_1 == rndIndex_2);
      enemies[rndIndex_1].shootProjectile();
      enemies[rndIndex_2].shootProjectile();
    } else if (enemiesLength === 2) {
      enemies[0].shootProjectile();
      enemies[1].shootProjectile();
    } else if (enemiesLength === 1) {
      enemies[0].shootProjectile();
    }
  }

  // other game logic
  timer++
}

animate();

Second solution:
let req;
let timer = 0
function animate() {
  req = requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // other game logic

  // two random enemies shoot every second
  if (timer % 60 === 0 && timer !== 0) {
    enemies.sort(() => 0.5 - Math.random()).slice(0, 2).forEach(e => {
      e.shootProjectile();
    });
  }

  // other game logic
  timer++
}

animate();

Any other solutions and help is much appreciated.
EDIT:
In response to CertainPerformance answer. I changed the answer to this so it would work:
   if (timer % 60 === 0 && timer !== 0) {
    const enemiesCopy = [...enemies];
    const enemiesToShoot = [];

    while (enemiesToShoot.length < 2 && enemiesCopy.length) {
        const [enemy] = enemiesCopy.splice(Math.floor(Math.random() * enemiesCopy.length), 1);
        enemiesToShoot.push(enemy);
    }
    for (const enemy of enemiesToShoot) {
        enemy.shootProjectile();
    }
}

It works fine like this. Is this how it should be? Some clarification please.


texts: Php how to properly connect functions with pagination

texts:
Am I doing this right? I do not know how to properly connect functions with pagination. To make everything work, I have to duplicate this variables. When I add variables to the function and to the index, then everything works.

$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;

Function

function find_all_products_by_cat_id2($cat_id, $options=[]) {
    global $db;

    $visible = $options['visible'] ?? false;

    $rowperpage = 10;
    $page = $_GET['page'] ?? 1;
    $page = $page - 1;
    $p = $page * $rowperpage;

    $sql = "SELECT * FROM products ";
    $sql .= "WHERE cat_id='" . db_escape($db, $cat_id) . "' ";
    if($visible) {
      $sql .= "AND visible = true ";
    }
    $sql .= "ORDER BY prod_name ASC ";
    $sql .= "LIMIT ".$p.", ".$rowperpage." ";
    $result = mysqli_query($db, $sql);
    confirm_result_set($result);
    return $result;

index.php

<?php

        $rowperpage = 10;
        $page = $_GET['page'] ?? 1;
        $page = $page - 1;
        $p = $page * $rowperpage;

        $category_id = $_GET['id'] ?? 1;

        $products_count = count_products_by_cat_id($category_id, ['visible' => true]);

        if(isset($_GET['id'])) {
        $category_id = $_GET['id'];

        $product_set = find_all_products_by_cat_id2($category_id, ['visible' => true]);

        if(!$product_set) {
            redirect_to(url_for('/index.php'));
        }

        $product_count = mysqli_num_rows($product_set);

        if($product_count == 0) {
              echo "
No more products
";
              }

 ?>

I think I found a solution.

Update 1
Function

  function find_by_sql($sql) {
    global $db;

    $result = mysqli_query($db, $sql);
    confirm_result_set($result);
    return $result;
  }

index.php

$visible = $options['visible'] ?? false;

$sql = "SELECT * FROM products ";
$sql .= "WHERE cat_id='" . db_escape($db, $category_id) . "' ";
if($visible) {
  $sql .= "AND visible = true ";
}
$sql .= "ORDER BY prod_name ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";

$product_set = find_by_sql($sql, ['visible' => true]);


texts: Event handlers & helper methods for a Kendo Grid

texts:
Below are a few of my handlers and helper methods. This works perfectly fine, but I'm pretty sure I'm breaking about 1001 modern conventions and possibly even optimizations.
Could you provide some insights as to how I can improve the structure and design of this code?

function getSelectedId() {
    var grid = $("MainGrid").data("kendoGrid");
    var selected = grid.select();
    var data = grid.dataItem(selected);

    return data.Id;
}

function changeGrid(e) {
    var id = getSelectedId();

    if (id == 0) {
        hideSubGrid();
    } else {
        refreshSubGrid();
        showSubGrid();
        setTitle(id);
    }
}

function hideSubGrid() {
    var subGrid = $("SubGrid").data("kendoGrid");

    subGrid.addClass("hidden");
}

function showSubGrid() {
    var subGrid = $("SubGrid").data("kendoGrid");

    subGrid.removeClass("hidden");
}

function refreshSubGrid(e) {
    var subGrid = $("SubGrid").data("kendoGrid");

    subGrid.dataSource.read();
    subGrid.refresh();
}

function setTitle(id) {
    $("#Title").text(id);
}

Some quick searching on the subject, suggests a style similar to what I've tried in the below code. However, I don't think this looks a whole lot better. I guess it's a step in the right direction, where I won't have to repeat myself as much, though.

var gridHandler = {
    mainGrid: $("MainGrid").data("kendoGrid"),
    subGrid: $("SubGrid").data("kendoGrid"),
    title: $("#Title"),

    getSelectedId: function () {
        var selected = this.mainGrid.select();
        var data = this.mainGrid.dataItem(selected);

        return data.Id;
    }

    changeGrid: function (e) {
        var id = this.getSelectedId();

        if (id == 0) {
            this.hideSubGrid();
        } else {
            this.refreshSubGrid();
            this.showSubGrid();
            this.setTitle(id);
        }
    }

    hideSubGrid: function () {
        this.subGrid.addClass("hidden");
    }

    showSubGrid: function () {
        this.subGrid.removeClass("hidden");
    }

    refreshSubGrid: function (e) {
        this.subGrid.dataSource.read();
        this.subGrid.refresh();
    }

    setTitle: function (id) {
        this.title.text(id);
    }
}


texts:
I'm working on a script where I want to create one dataframe from a series of files with annual baseball data in them.

I'm relatively new to R and I feel like the way I wrote get_seasons_range() is probably more like writing C# in R, rather than doing it the idiomatic R way. Is there a cleaner way to do this?

read_season <- function(yearID) {
  season = read.csv(paste("../retrosheetData/gamelog/GL", yearID, ".TXT", sep=""))
  glheaders = read.csv("../retrosheetData/gamelog/game_log_header.csv")
  names(season) = names(glheaders)
  return(season)
}

read_season_range <- function(year_range) {
  seasons = read_season(year_range[1])

  for(y in year_range) {
    if(y == year_range[1])
      next

    s = read_season(y)
    seasons = rbind(seasons, s)
  }

  return(seasons)
}

sixties = read_season_range(1960:1969)


texts:
Common Lisp has a "special operator" called multiple-value-call, which does something similar to Scheme's call-with-values but with a nicer syntax, and allowing multiple producers (unlike call-with-values). So I thought I'd try to implement multiple-value-call in Scheme, using call-with-values (dressed up here as receive) behind the scenes:

(define-syntax multiple-value-collect
  (syntax-rules ()
    ((multiple-value-collect) '())
    ((multiple-value-collect expr next ...)
     (receive vals expr
       (cons vals (multiple-value-collect next ...))))))

(define-syntax multiple-value-call
  (syntax-rules ()
    ((multiple-value-call func expr ...)
     (apply func (concatenate! (multiple-value-collect expr ...))))))

Is there a better (more idiomatic, performant, etc.) way to implement this? (concatenate! is from SRFI 1, and receive is from SRFI 8.)


texts: Function to find the shortest word in an array, where not every element is a string

texts:
I wrote a solution for a codeCamp exercise:

  Write a function called findShortestWordAmongMixedElements.

  Given an array, findShortestWordAmongMixedElements returns the
  shortest string within the given array.

  Notes:

  If there are ties, it should return the first element to appear in the given array.
  Expect the given array to have values other than strings.
  If the given array is empty, it should return an empty string.
  If the given array contains no strings, it should return an empty string.

Right now I essentially break this function into two parts. The filtering method—to just get the strings—and then reduce to find the shortest one among them.

function findShortestWordAmongMixedElements(arr) {
  var containsStrings = function(arr){
   return arr.every(function(cv){
      return Object.prototype.toString.call(cv) !== '[object String]';
    });
  }, shortestWord;

  if ((!(arr.length)) || ((containsStrings(arr)))) return '';

   arr = arr.filter(function(e, i, a){
     if (typeof e == 'string') {
       return e;
     }
   });

   shortestWord = arr.reduce(function(prev, next) {
     if (prev.length < next.length) {
         return prev;
     } else if (prev.length === next.length){
        return prev;
     } else {
        return next;
     }
   });

   return shortestWord;

}

My take is this is certainly readable which I like and I LOVE the helper function I made for the initial check which uses the every method.

Since (at first) I spent a lot of time trying to do all the operations within the body of the callback for the filter—I feel this take is like I used flat head screw driver for every screw instead of a phillips...


texts: Which class is best to call .getResource on?

texts:
I'm creating a Java Helper Library with helpful static methods. I find myself needing to call ...getResource(...) or ...getResourceAsStream(...) in several instances and I'm wondering what's the best practice for this. It seems to be working fine when I say: Helper.class.getResource(...), but I'm wondering whether that will bite me in the future.

I have a few alternatives I'm thinking of. Below is an example of when I need to use this and the alternatives I have thought of:

Alternative 1 (what I would prefer for the sake of users):

/**
* Takes the given resource and returns that as a string.
*
* @param location of the file
* @return the file as a string
* @throws IOException
*/
public static String resourceToString(String location) throws IOException {
  InputStream is = IOHelper.class.getResourceAsStream(location);
  InputStreamReader r = new InputStreamReader(is);
  return readerToString(r);
}

Alternative 2:

/**
* Takes the given resource (based on the given class) and returns that as a string.
*
* @param location of the file
* @param c class to get the resource from
* @return the file as a string
* @throws IOException
*/
public static String resourceToString(String location, Class c) throws IOException {
  InputStream is = c.getResourceAsStream(location);
  InputStreamReader r = new InputStreamReader(is);
  return readerToString(r);
}

Alternative 3 (should I just have the user give me the resource?):

/**
* Takes the given InputStream and returns that as a string.
*
* @param is the InputStream of the File to read
* @return the file as a string
* @throws IOException
*/
public static String resourceToString(InputStream is) throws IOException {
  InputStreamReader r = new InputStreamReader(is);
  return readerToString(r);
}


texts:
I am just trying to understand the algorithm of the problem statement

  Given an array, we need to find the maximum sum of absolute difference of any permutation of the given array.

Here is my implementation after following the algorithm mentioned in the link

static int sumOfMaxAbsDiff(int[] arr) {
    Arrays.sort(arr);
    int len = arr.length;
    int[] temp = new int[len];
    int sum = 0;
    for (int i = 0, j = 1, k = 0; i < len / 2; i++, j++, k++) {
      temp[k] = arr[i];
      temp[++k] = arr[len - j];
    }
    if (len % 2 != 0) { // Odd numbered length
      temp[len - 1] = arr[len / 2]; // copy the middle element of arr to last place in temp
    }
    // Now accumulate sum
    for (int i = 0; i + 1 < len; i++) {
      sum += Math.abs(temp[i] - temp[i + 1]);
    }
    // max abs diff at last index - NOT sure of this
    sum += Math.abs(temp[len - 1] - temp[0]); // assuming array size is >= 2
    return sum;
  }

I know why we have to sort, as we are trying to find max diff, it's obviously the least-highest
If we arrange the sequence as firstSmallest, firstLargest, and so on for a given input arr [1,2,4,8]
it would be [1,8,2,4]
Now, checking the max diff in forward direction, max diff at each index, it would be 7,6,2,?

2 questions

For odd numbered length arr [1,2,3,4,8] why place middle at the end of arr?
And, for last index, why do we have to find abs difference between val at last index and first index?

Is there is any better and clear algorithm to think about or links to apply for this


texts: Validity checks for a user signup process

texts:
Background:

I have been working on a service which allows users to signup on different apps and on each login checks if the request is valid or not based on a series of checks.

The below snippet is small part of the whole application but covers my question and is working fine for now:

Code:

'use strict';

const bcrypt = require('bcrypt');
const boom = require('boom');
const joi = require('joi');
const flatten = require('lodash/flatten');
const pick = require('lodash/pick');

const models = require('../../models');
const { AccessToken, App, User } = models;

const debug = require('debug')('microauth:test');

const loginSchema = joi
  .object({
    appname: joi.string().required(),
    email: joi.string().required(),
    password: joi.string().required(),
  })
  .required();

async function run(req, res, next) {
  const { appname, email, password } = joi.attempt(req.body, loginSchema);

  const app = await getApp(appname);
  if (!app) {
    throw boom.badRequest(`Invalid app name: ${appname}.`);
  }
  if (app.isInactive()) {
    throw boom.badRequest('App is not active.');
  }

  const { isAuthorized, user } = await authorize({ email, password });
  if (!user) {
    throw boom.notFound('User not found.');
  }
  debug(`User ${user.get('email')} is authorised? ${isAuthorized}`);
  if (!isAuthorized) {
    throw boom.unauthorized('Invalid email or password.');
  }

  const { result } = await isUserBelongsToApp(user, app.get('name'));
  if (!result) {
    throw boom.badRequest(`User is not authorised to access app.`);
  }

  return successResponse(email, app.get('secret'), res);
}

async function getApp(name) {
  return await App.findOne({ name });
}

async function authorize({ email, password }) {
  const user = await User.findOne(
    { email, status: 'active' },
    { withRelated: ['apps', 'roles.permissions'] }
  );

  let isAuthorized = false;
  if (user) {
    isAuthorized = await bcrypt.compare(password, user.get('password'));
  }
  return { isAuthorized, user };
}

async function isUserBelongsToApp(user, appname) {
  let result = false;
  let app = null;
  app = user.related('apps').findWhere({ name: appname });
  if (app) {
    result = true;
  }
  return { result, app };
}

async function successResponse(email, secret, res) {
  const userFields = [
    'device',
    'email',
    'firstname',
    'language',
    'lastname',
    'phone',
    'uid',
  ];
  const roleFields = ['name', 'description'];
  const permissionFields = ['name', 'object', 'action'];

  let user = await User.findOne(
    {
      email: email,
    },
    {
      withRelated: ['roles.permissions'],
    }
  );
  user = user.toJSON();
  const result = Object.assign({}, { ...user });
  result.roles = [];
  result.permissions = [];

  if (user.roles) {
    result.roles = user.roles.map(role => pick(role, roleFields));
    result.permissions = user.roles.map(role => {
      return role.permissions.map(permission =>
        pick(permission, permissionFields)
      );
    });
  }
  result.permissions = flatten(result.permissions);
  const { token, expiration } = new AccessToken(secret).create(result);
  res.json({ token, expiration });
}

module.exports = run;

Questions:

The code above belongs to the controller of the applications, is that the right place to do all these checks?

Right now the main logic seems pretty obvious but each step depends of the previous step. Is there any better way to write the same logic?


texts: Converting the comma seprated numeric string into int array

texts:
//convert the comma separated numeric string into the  array of int.
public class HelloWorld
{
  public static void main(String[] args)
   {
     // line is the input  which have the comma separated number
     String line = "1,2,3,1,2,2,1,2,3,";
     // 1 > split
     String[] inputNumber =  line.split(",");
    // 1.1 > declear int array
     int number []= new int[10];
     // 2 > convert the String into  int  and save it in int array.
 for(int i=0; i<inputNumber.length;i++){
       number[i]=Integer.parseInt(inputNumber[i]);
  }
 }

}

Is there a more efficient solution to achieve the same result?


texts: Creates a series of folders from a given starting date

texts:
I made this python script to create dated folders within a directory. This is my first practical automation project and I don't want to cement any bad habits so I was wondering if there is anything I can improve in the code I have written here. Any feedback will be appreciated!
The main challenge I had was to account for months with different day ranges, and then to reset the counts properly for all the variables. I feel like this is more complicated than it probably needs to be but I don't know if there are some python libraries I am unaware of that could help simplify it more.
I thought about having a predefined end date as well but that would require the user to open up a calendar and find 2 dates. I figured by just asking for a start date and how many folders they want, I could make things simpler for the end user but I'm not even sure that that is actually the case.
I also don't know if I've used classes correctly here. At first I had everything thrown into the while statement. I also considered using a for loop instead of while but went with while instead. Again, this is my first real project so any help with other decisions I could have made will be appreciated!
import os
import pathlib

directory = "/Users/myName/Box Sync/SAFAC/Budget Requests/2020-2021/Weekly/"

# directory = input("Enter the path where you would like to create files: ")
date = input("Enter the starting date in mm-dd-yyyy format: ")
period = int(input("Enter the period between each date folder: "))
instances = int(input("How many folders do you want? "))

Folders = []

arguments = date.split("-")
dayArgument = arguments[1]
monthArgument = arguments[0]
yearArgument = arguments[2]
init = instances - instances
elapse = period - period
seperator = "-"

month = int(monthArgument)
day = int(dayArgument) + int(elapse)

def make_directories(input_list):
    for folderName in input_list:
        dirpath = os.path.join(directory, folderName[0:],'Documentation')
        try:
            os.makedirs(dirpath)
        except FileExistsError:
            print('Directory {} already exists'.format(dirpath))
        else:
            print('Directory {} created'.format(dirpath))

def add_folder_to_list(month,day,year,extra):
    full_name_constructor = (month,day,year,extra)
    # full_name_constructor = (str(month),str('0'+str(day)),yearArgument,"Budgets")
    fullName = seperator.join(full_name_constructor)
    Folders.append(fullName)

def format_and_append_folder_name():
    if day < 10 and month >= 10:
        add_folder_to_list(str(month),str('0'+str(day)),yearArgument,"Budgets")
    elif day >= 10 and month < 10:
        add_folder_to_list(str('0'+str(month)),str(day),yearArgument,"Budgets")
    elif day < 10 and month < 10:
        add_folder_to_list(str('0'+str(month)),str('0'+str(day)),yearArgument,"Budgets")
    else:
        add_folder_to_list(str(month),str(day),yearArgument,"Budgets")

def check_month():
    global maxDays
    if (month % 2 ) == 0 and month != 2 : # if even but not February
        maxDays = 30
    elif month == 2 :
        maxDays = 28 #if February
    else :
        maxDays = 31 # if odd

while init < instances :
    check_month()
    format_and_append_folder_name()
    make_directories(Folders)
    # print(Folders[init])            # for debugging

    init += 1
    elapse += period
    day = int(dayArgument) + int(elapse)

    if day > maxDays :
            month += 1
            day -= maxDays                  # reset days
            dayArgument = day               # recalibrate the new zero point for the day to be the date in the new month
            elapse = 0                      # recalibrate elapse point to 0 so it can reiterate the period again


texts:
I would like to get a distinct array of objects. The code below is the first thing that came to mind.

Do you see any room for improvements?

function distinct(objectArray){

    var distinctResult = [];

    $.each(objectArray, function(i, currentObject){
        if(!exists(distinctResult, currentObject))
            distinctResult.push(currentObject);
    });

    return distinctResult;
}

function exists(arr, object){
    var compareToJson = JSON.stringify(object),
        result = false;
    $.each(arr, function(i, existingObject){
        if(JSON.stringify(existingObject) === compareToJson) {
            result = true;
            return false; // break
        }
    });

    return result;
}

var testList = [{ foo: 1 }, { foo: 1 }, { bar: 1 }, { bar: 2, baz: 3 }];

console.log(distinct(testList));


texts: Capturing and taking a screenshot of a window in a loop

texts:
I am capturing a window of my own choice, and taking a screenshot of it constantly in a loop. Latency and speed is everything.

It's very capable, but I hope it can be improved.

var proc = Process.GetProcessesByName(prcname)[0];
IntPtr hwnd = proc.MainWindowHandle;
RECT rc;
NativeMethods.GetWindowRect(hwnd, out rc);
Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap = gfxBmp.GetHdc();
NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);
gfxBmp.ReleaseHdc(hdcBitmap);
gfxBmp.Dispose();
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

return new MemoryStream(Lz4.CompressBytes(ms.GetBuffer()));

I will set a name prcname which will be the name of a process, for example, Internet Explorer. It will then hook on to that and save it as a bitmap and then .bmp (or other).

I then return the memory stream , and then I can do what I want with it (lz4 is used here to compress, which is very fast and lossless so it works pretty well).

Here are the Imports used:

[DllImport("user32.dll")]
internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
internal static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

Then there is the RECT class, which is enormous, and I did not write it. I took it and reused this code for my own purposes, but RECT has been untouched, as I don't feel safe messing around with it.

Now, is there a way to improve the speed? Preferably I would like to improve the latency, meaning the frame it lags behind.

I am willing to try something else if user32 is not enough for this, so I'm open for suggestions and examples on that.

Can this code be improved?

NetSerializer.Serializer.Serialize(tcpcap.GetStream(), PrintWindow(process));
PrintWindow(process).Dispose();

panel1.BackgroundImage = Image.FromStream(new Lz4DecompressionStream((MemoryStream)NetSerializer.Serializer.Deserialize(tt1.GetStream())));


texts: Euler-Mascheroni Single Thread Speed Improvements

texts:
The below code was written to generate γ, for educational purposes.

My general methodology is as follows:
Compute Gamma via the accepted answer's algorithm here.

In order to do this I need to compute the natural log of a large k.

Compute Pi via the AGM as here.
Compute the natural log of 2 via the last algorithm here.
Compute the natural log of a large k via Gauss's AGM method here.
Compute Gamma as described in the accepted answer here.
I am very grateful to the community for sharing the knowledge and I have improved the speed by orders of magnitude compared to the previous version (because of the accepted answers improvements).

One can pip3 install tqdm to see progress, I've wrapped a few ranges with it.

import decimal
#non-builtin
from tqdm import tqdm

D = decimal.Decimal

def agm(a, b):      #Arithmetic Geometric Mean
    a, b = D(a),D(b)
    for x in tqdm(range(prec)):
        a, b = (a + b) / 2, (a * b).sqrt()
    return a

def pi_agm():       #Pi via AGM and lemniscate
    print('Computing Pi...')
    a, b, t, p, pi, k = 1, D(2).sqrt()/2, 1/D(2), 2, 0, 0
    while 1:
        an    = (a+b)/2
        b     = (a*b).sqrt()
        t    -= p*(a-an)**2
        a, p  = an, 2**(k+2)
        piold = pi
        pi    = ((a+b)**2)/(2*t)
        k    += 1
        if pi == piold:
            break
    return pi

def factorial(x ,pfact, pfactprd):
    x = int(x)
    if pfact == (x-1):
        return pfactprd*x
    else:
        factorial = D(1)
        for i in range(1, x+1):
            factorial *= i
        return factorial

def lntwo():        #Fast converging Ln 2
    print('Computing Ln(2)...')
    def lntwosum(n, d, b):
        logsum, logold, e = D(0), D(0), 0
        while 1:
            logold = logsum
            logsum += D(1/((D(b**e))*((2*e)+1)))
            e += 1
            if logsum == logold:
                return (D(n)/D(d))*logsum
    logsum1 = lntwosum(14, 31, 961)
    logsum2 = lntwosum(6, 161, 25921)
    logsum3 = lntwosum(10, 49, 2401)
    ln2 = logsum1 + logsum2 + logsum3
    return ln2

def lnagm(x):   #Natural log of via AGM,
    try:
        if int(x) == 1:
            return 0
        if int(x) == 2:
            return lntwo()
    except:
        pass
    m = prec*2
    ln2 = lntwo()
    decimal.getcontext().prec = m
    pi = D(pi_agm())
    print('Computing Ln(x)...')
    twoprec = D(2**(2-D(m)))/D(x)
    den = agm(1, twoprec)*2
    diff = m*ln2
    result = (D(pi/den) - D(diff))
    logr = D(str(result)[:m//2])
    decimal.getcontext().prec = prec
    return logr

def gamma():   #Compute Gamma from Digamma Expansion
    print('Computing Gamma!')
    k = D(prec//2)
    lnk = lnagm(k)
    upper = int((12*k)+2)
    print('Summing...')
    # First Sum
    logsum = D(0)
    pterm = D((k**2)/2)
    for r in tqdm(range(1, upper)):
        r = D(r)
        logsum += pterm
        nterm = D(((-1)*D(k)*D(r+1))/(r*(r+2)))*pterm
        pterm = nterm
    logsum1 = D(0)
    print('...')
    pfact, pfactprd = 1, 1
    for r in tqdm(range(1, upper)):
        calfact = factorial((r-1), pfact, pfactprd)
        pfact, pfactprd = (r-1), calfact
        logsum1 += D((D(-1)**D(r-1))*(k**D(r+1)))/D(calfact*D(D(r+1)**2))
    twofac = D(2)**(-k)
    gammac = str(D(1)-(lnk*logsum)+logsum1+twofac)
    return D(gammac[:int(prec//6.66)])

#Calling Gamma
prec = int(input('Precision for Gamma: '))*8
decimal.getcontext().prec = prec
gam = gamma()
print('\n')
print(gam)


texts: var that = this; Keeping a class in scope of nested functions

texts:
I've been using this syntax alot recently to keep my class in scope of nested functions. It seems to work well in small to moderately sized class but I'm starting to wonder how efficient it actually is and if there is a better way to handle this. Any suggestions would be really useful.

myClass.prototype.myMethod = function() {
    var that = this; // Without taking the size of the class into consideration
                     // does this create an unecessarily high load?
    function callback_one(data) {
        that.myOtherMethod();
    }

    function callback_two(data) {
        that.myErrorMethod();
    }

    $.post(this.getRequest(), this.getUrl())
        .success(function(data) {
            callback_one(data);
            // Can also use that.anotherMethod() here
        })
        .error(function(data) {
            callback_two(data);
            // Can also use that.anotherMethod() here
        });
}


texts:
Problem Statement :
Print the first non repeating character in a string.
Example :
In the string somecharsjustdon'tliketorepeat, m is the first non-repeating charecter.

My attempt :
New Code : Old one was not working as expected so I have updated the post. Old code can be found below new code
public class FirstNonRepeatedChar{
    static boolean isRepeated(String str, char c){
        int count = 0;
        for(char ch: str.toCharArray()){
            if(c == ch){
                count++;
            }
        }

        return count > 1;
    }

    static void printFirstNonRepeatedChar(String str){
        boolean found = false;

        for(char c : str.toCharArray()){

            if(! isRepeated(str, c)){
                found = true;
                System.out.println(str + " : " +c);
                break;
            }
        }

        if(!found){
            System.out.println(str + " : No non-repeated char");
        }
    }

    public static void main(String [] args){
        String []testCases = {"aaabbcc", "sss", "121", "test", "aabc"};

        for(String str: testCases){
            printFirstNonRepeatedChar(str);
        }
    }
}

Old code
public class FirstNonRepeatedChar{

    public static void main(String [] args){
        String str = "somecharsjustdon'tliketorepeat";

        loopI:
        for(int i = 0;i<str.length();i++){
            for(int j = i+1; j<str.length();j++){
                if(str.charAt(i)==str.charAt(j))
                    continue loopI;
            }
            System.out.println(str.charAt(i));
            break;
        }
    }
}

I want to ask :

Is there better way to solve this problem? Especially, is there efficient way to do this using built-in classes?
Can I reduce complexity?
Is there any case where my code may fail to generate appropriate result? and how can I avoid these failures?

Thanks in advance!


texts:
We start off we the following Person class:

class Person:
    def __init__(self):
        self.moods = {
            "happy": 5,
            "angry": 5,
            "sad": 5
        }

    def updateStates(self, stateUpdates: {}):
        for mood, valChange in stateUpdates.items():
            self.moods[mood] += valChange

From here I implemented a restriction on what the values self.moods can be.
I have implemented the restriction using descriptors. But I find it distasteful.

The following works. But I don't think it is worth it because now I have to append .__get__(instance=self, owner=None) to self.moods[<mood>] whenever I need to access a mood, or .__set__(instance=self, value=<newVal>) whenever I want to update one. This will quickly pollute my code and make it unreadable, which is why I am not a fan of this approach.

class OneDigitNumericValue():    # descriptor class
    def __set_name__(self, owner, name):
        self.name = name

    def __init__(self, defaultVal=5):
        self.value = defaultVal

    def __get__(self, instance, owner) -> object:
        return self.value

    def __set__(self, instance, value) -> None:
        if not (0 < value < 9) or int(value) != int:
            raise AttributeError("The value is invalid")
        self.value = value

class Person:
    moods = {
        "happy": OneDigitNumericValue(),
        "angry": OneDigitNumericValue(),
        "sad": OneDigitNumericValue()
    }

    def updateStates(self, stateUpdates: {}):
        for mood, valChange in stateUpdates.items():
            oldVal = self.moods[mood].__get__(self, owner=None)
            self.moods[mood].__set__(self, value=oldVal + valChange)


texts: Add elements to a textfile using a dictionary

texts:
Is there a shorter way to write this code or parts of it and where can i inculde some try and excepts for validation

   People={"Dan":22,
            "Matt":54,
            "Harry":78,
            "Bob":91}

schoice=input('Enter existing name: ')
while schoice not in People:
    schoice=input('Invalid entry name is non existant, Enter a chosen name: ')
if schoice in People:
    getscore=People[schoice]
    if getscore<50:
        presents=[]
        for x in range(2):
            present=input('Enter present ' +str(x+1))
            while present == '':
                present = input('Invalid. Try again: ')
            presents.append(present)
    if getscore>=100:
        presents=[]
        for x in range (8):
            present=input('Enter present ' +str(x+1))
            while present == '':
                present = input('Invalid. Try again: ')
            presents.append(present)
    if getscore>=50 and getscore <100:
        presents = []
        for x in range (5):
            present=input('Enter present ' +str(x+1))
            while present == '':
                present = input('Invalid. Try again: ')
            presents.append(present)
File=open("presfile.txt",'a')
File.write(schoice)
File.write(str(presents)+'\n')
File.close()


texts: How to best structure an abstract class where a member field will depend on the deriving type?

texts:
Puts and calls are two types of options. One parameter that they both share is called a strike price. The valuation of an option is related to the strike price, but the exact methodology is different depending on the type of option. All things being equal, a lower strike price is better when valuing a call, and vice versa when considering a put. I am considering the best way to model my code so that these comparisons could be performed as simply and intuitively as possible.
Ideally, I would like to be able assign optionInstance1.Strike = 5, and to evaluate if optionInstance1.Strike > optionInstance2.Strike while considering the rules of the particular type of option. I am trying to explore the best ways to accomplish this.
The first approach: attach an evaluator class to every option instance
interface IOptionRules
{
    bool GTE(decimal s1, decimal s2);
}

class CallRules : IOptionRules{ ... }

abstract class Option
{
    public decimal strike;
    public IOptionValuationRules rules;

    public Option(decimal strike, IOptionRules rule){ this.strike = strike; rules = rule;}
}

class CallOption : Option
{
    public CallOption(decimal strike) : base(strike, new CallRules()){}
}

this would allow for easy assignment => strike = 5m
but comparisons would be cumbersome and unintuitive => optionInstance1.Rules.GTE( optionInstance1.strike, optionInstance2.strike);
it would not preclude direct comparison operators => optionInstance1.strike >= optionInstance2.strike
The second approach: perform the evaluations in a completely different class
class OptionEvaluator
{
    public bool GTE(CallOption o1, CallOption o2){}
    public bool GTE(PutOption o1, PutOption o2){}
}

It seems this approach invites maintenance issues in the future, for example if I were to create any sort of exotic options with special rules in the future, I would have to remember to update this separate class. Furthermore, I think with this approach I would have to upcast whenever I am working with Option Types.
The third approach: defining a strike type
abstract class Option
{
    public Strike strike;

    public Option(Strike strike){ this.strike = strike;}
}

abstract class Strike
{
    public decimal Amount{get; set;}
        public abstract bool GTE(decimal otherStrike);
}

class CallStrike : Strike{...}

class PutStrike : Strike {...}

This seems to be a desirable approach, but the main issue I have is how cumbersome it would be to assign a strike amount as it would make more sense to type OptionInstance1.Strike = 4 rather than OptionInstance1.Strike.Amount = 4.
Also, I would potentially be able to assign a PutStrike to a CallOption at runtime since the type of the strike field is Strike, although I suppose this is easily fixable if I made it readonly.
Are there any other approachs for this particular issue? Are there particular issues that I am not considering with any of these approachs? Which is the best approach to take?


texts: Finding permutation from given lexicographical rank

texts:
I wrote the following little piece of Python code to take in some integer, and return a permutation that has that rank in the lexicographical ordering of permutations. While this works, I'm worried that the number of calls to pop() and append() might be slowing this down. This function is part of a larger program, which will call FromRank() millions of times, and any small efficiency may make a large impact down the road.

Note: The same topic for Java is here!

Input:

There are four arguments: rank, level, ordered, and perm. rank is the rank given. level is the number of uncertain digits of the permutation minus one. Hence, if the size of a permutation is 8 digits, then level is initially 7. ordered is initially list(range(size)) and is always sorted. perm keeps track of the permutation, and is initially an empty list.

Code:

def FromRank(rank,level,ordered,perm):
    fact = math.factorial(level)
    section = rank // fact
    if len(ordered) == 1:
        perm.extend(ordered)
        return perm
    elif rank % fact == 0:
        ordered.sort()
        nxt = ordered.pop(section - 1)
        perm.append(nxt)
        ordered.sort(reverse = True)
        perm.extend(ordered)
        return perm
    elif rank < fact:
        ordered.sort()
        first = ordered.pop(0)
        perm.append(first)
        return FromRank(rank,level - 1,ordered,perm)
    else:
        ordered.sort()
        nxt = ordered.pop(section)
        perm.append(nxt)
        rank = rank - (rank // fact) * fact
        return FromRank(rank,level - 1,ordered,perm)

Time Complexity Example:

While the goal of this function is to work on a single rank, I ran the following code to see how runtime would ramp up with an increasing number of permutations to handle. And, although this function would never be running on permutations larger than 20, I included a section giving the runtimes for a single permutation of increasing size.

I ran this to see how the function would respond to volume

for j in range(2,11):
    start_time = timeit.default_timer()

    for i in range(1,math.factorial(j)+1):
        x = FromRank(i,j-1,list(range(j)),[])))

    elapsed_time = timeit.default_timer() - start_time
    print("Permutations of size {} took {} seconds."\
              .format(j,elapsed_time))

and got the following times:

Permutations of size 2 took 0.000249750356557 seconds.
Permutations of size 3 took 0.00016293644837 seconds.
Permutations of size 4 took 0.000660726542604 seconds.
Permutations of size 5 took 0.00366414564209 seconds.
Permutations of size 6 took 0.0185743274595 seconds.
Permutations of size 7 took 0.160154982071 seconds.
Permutations of size 8 took 1.48163329891 seconds.
Permutations of size 9 took 15.2436537109 seconds.
Permutations of size 10 took 177.243403105 seconds.

I then ran the following to see how the function would respond to large permutations:

for size in [10,50,100,500,1000]:
    start_time = timeit.default_timer()
    x = FromRank(size ** 2, size - 1, list(range(size)), [])
    elapsed_time = timeit.default_timer() - start_time
    print(elapsed_time)

and got the following times:

0.000118032702744
0.00074668514128
0.00260142366255
0.110989229516
0.684973282271


texts: Python3 Stack implementation with List built-in - Round Two

texts:
Previous code is available at Python3 Stack implementation with List built-in, this is a second-round review after I made alterations.

Once again, let's review my Stack implementation, with built-in lists, and with review notes from the prior review implemented.

Any changes and suggestions are welcome!

class Stack:
    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def pop(self):
        if len(self) == 0:
            raise IndexError("You cannot pop from an empty stack.")

        return self._stack.pop()

    def peek(self):
        if len(self) == 0:
            raise IndexError("You cannot peek into an empty stack.")

        return self._stack[len(self) - 1]

    def push(self, item):
        self._stack.append(item)

    def __iter__(self):
        return iter(self._stack)


texts: Finding count of character occurrences in a string

texts:
I am taking an introductory course in java in high school, however I have some experience in python. I was tasked to find the number of times a character occurs in a string so I did this.

String a = "hello";
String letter = "l";
int occurrence = a.length() - a.replace(letter, "").length();

Happy that I came up with a clever one-liner, I showed it to my teacher and she said that it's more elegant to use a for loop. What does she mean by that? How do we define elegance in code? Is it subjective? As an aside is this more efficient than a for loop or vice-versa?


texts: Optimization of matrix determinant calculation

texts:
I have this algorithm that calculates the matrix determinant using recursive divide-and conquer-approach:

int determ(int a[max][max],int max) {
  int det=0, p, h, k, i, j, temp[max][max];
    //base case omitted
    for(p=0;p<max;p++) {
      h = 0;
      k = 0;
      for(i=1;i<max;i++) {
        for( j=0;j<max;j++) {
          if(j==p) {
            continue;
          }
          temp[h][k] = a[i][j];
          k++;
          if(k==max-1) {
            h++;
            k = 0;
          }
        }
      }
      det=det+a[0][p]*pow(-1,p)*determ(temp,max-1);
    }
    return det;
}

I want to optimize the main loop (with a loop unwinding or any strategy that can reduce the execution time).  Any suggestion?


texts:
Some exercise required me to write a piece of code to double every second item in a list. My first thought was just using cons and I came up with the following:

doubleSecond :: Num a => [a] -> [a]
doubleSecond [] = []
doubleSecond [x] = [x]
doubleSecond (x:y:xs) = x : (y * 2) : doubleSecond xs

While it's straightforward and does work, it just doesn't look that elegant and I'm curious how this could be rewritten in a more elegant fashion :)


texts:
If I need to obfuscate an iPhone password that is hardcode (Oauth Client Identifier and Client Secret), would this be a way to do it?

NSString *a = @"a";
NSString *b = @"b";
NSString *c = @"c";
NSString *d = @"d";
NSString *e = @"e";
NSString *f = @"f";
NSString *g = @"g";
NSString *h = @"h";
NSString *i = @"i";
/*    hidden     */
NSString *w = @"w";
NSString *x = @"x";
NSString *y = @"y";
NSString *z = @"z";

NSString *pwd = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@", p,a,s,s,w,o,r,d];

I know obfuscate isn't recommended but after reading this Oauth secrets in mobile apps it seems like the only way.


texts: An efficient way to find the most similar vectors

texts:
Let's say we train a model with more than 1 million words. In order to find the most similar words we need to calculate the distance between the embedding of the test word and embeddings of all the 1 million words words, and then find the nearest words. It seems that Gensim calculate the results very fast. Although when I want to calculate the most similar, my function is extremely slow:

def euclidean_most_similars (model, word, topn = 10):
      distances = {}
      vec1 = model[word]
      for item in model.wv.vocab:
        if item!= node:
          vec2 = model[item]
          dist = np.linalg.norm(vec1 - vec2)
          distances[(node, item)] = dist
      sorted_distances = sorted(distances.items(), key=operator.itemgetter(1))

I would like to know how Gensim manages to calculate the most nearest words so fast and what is an efficient way to calculate the most similar words.


texts:
I'm working on a vue.js / nuxt.js project, applying the Atomic Design methodology, I need to do one to set the grid layout and using CSS Grid Layout.

I already did the component, but I think I did not do it the best way ... the code is great and not very smart, lots of manual work, I would like your opinion and help to make this component better

GridLayout.vue

<template>

    <slot />

</template>

using component on any page.vue

<template>
  <GridLayout
    columns="1fr 1fr 1fr 1fr"
    rows="auto"
    gap="10px"
    :medium="{
      columns: '1fr 1fr',
      rows:'auto auto'
    }"
    :small="{
      columns: '1fr',
      rows: 'auto auto auto auto',
    }"
  >

1

2

3

3

  </GridLayout>
</template>

problems

  1 - the style tag


texts:
I wrote a program to test AV engines against encryption. When it runs, it will compute some key, decrypt an executable it has in its data section and copy it to the locations where the executable expects to be. The program has to fill the imports for the payload to run properly.

At first I was filling it from the thunks and it worked fine. Then I downloaded some malware samples and quickly discovered their thunks point to the wrong location, I even checked manually to make sure it wasn't some bug in the code and they really pointed at wrong location in the executable file. So I updated the code to follow the hints table every time it's present and it worked perfectly ever since.

The problem is that I read old Borland compilers didn't include a hints table, and knowing that made me uncomfortable. So I had the code check whether a hints table is present and go with the thunks otherwise.

I'm interested in confirming it's correct for all possible executables assuming you give a location containing an IMAGE_IMPORT_DESCRIPTOR.

; // https://artfulcode.wordpress.com/
; // https://github.com/cmovz/
; // License: use it as you wish, just keep this notice. No liability taken.

#include <windows.h>

static inline BOOL _is_iid_end(IMAGE_IMPORT_DESCRIPTOR* iid)
{
  return !iid->Characteristics && !iid->TimeDateStamp && !iid->ForwarderChain
          && !iid->Name && !iid->FirstThunk;
}

static BOOL _load_from_hints(IMAGE_IMPORT_DESCRIPTOR* iid, DWORD base)
{
  HMODULE dll = LoadLibrary((LPCSTR)(base + iid->Name));
  if(!dll){
    return FALSE;
  }

  // now get the address of each of the functions in the thunks
  DWORD* hints = (DWORD*)(base + iid->Characteristics);
  DWORD* thunks = (DWORD*)(base + iid->FirstThunk);
  while(*hints){
    DWORD r;

    if(*hints & 0x80000000){
      // handle import by ordinal
      r = (DWORD)GetProcAddress(dll, (LPCSTR)(*hints & 0xffff));
    }
    else {
      // handle import by name
      IMAGE_IMPORT_BY_NAME* iibn = (IMAGE_IMPORT_BY_NAME*)(base + *hints);
      r = (DWORD)GetProcAddress(dll, iibn->Name);
    }

    if(!r){
      return FALSE;
    }

    *thunks = r;
    ++thunks;
    ++hints;
  }

  return TRUE;
}

// old Borland compilers don't include hints...
static BOOL _load_from_thunks(IMAGE_IMPORT_DESCRIPTOR* iid, DWORD base)
{
  HMODULE dll = LoadLibrary((LPCSTR)(base + iid->Name));
  if(!dll){
    return FALSE;
  }

  // now get the address of each of the functions in the thunks
  DWORD* thunks = (DWORD*)(base + iid->FirstThunk);
  while(*thunks){
    DWORD r;

    if(*thunks & 0x80000000){
      // handle import by ordinal
      r = (DWORD)GetProcAddress(dll, (LPCSTR)(*thunks & 0xffff));
    }
    else {
      // handle import by name
      IMAGE_IMPORT_BY_NAME* iibn = (IMAGE_IMPORT_BY_NAME*)(base + *thunks);
      r = (DWORD)GetProcAddress(dll, iibn->Name);
    }

    if(!r){
      return FALSE;
    }

    *thunks = r;
    ++thunks;
  }

  return TRUE;
}

/*
  fill_idata() fills the function references in the .idata section. There's no
  cleaning up if it fails because it assumes the program won't be able to run
  anyway and will have to exit. References to modules are also lost because
  the DLLs should be in the address space until the program exits. In short,
  it behaves just like the Windows PE loader.
*/
BOOL fill_idata(DWORD* idata, DWORD base)
{
  IMAGE_IMPORT_DESCRIPTOR* iid = (IMAGE_IMPORT_DESCRIPTOR*)idata;

  while(!_is_iid_end(iid)){
    if(iid->Characteristics){
      if(!_load_from_hints(iid, base)){
        return FALSE;
      }
    }
    else {
      if(!_load_from_thunks(iid, base)){
        return FALSE;
      }
    }

    ++iid;
  }

  return TRUE;
}

Edit

Some assumptions:

32-bit
well-formed import tables


texts:
I have a question about of the performance of using for loops (normal for, for each and for key in object) in JavaScript.

Just now I created this code to test:

var stopwatch = function(){
    var start;

    this.Start =function(){
        this.start = new Date().getTime();
    }

    this.getDifference= function(){
        return new Date().getTime() - this.start;
    }
}

var stopwatch = new stopwatch();
var length = 1000000;
var array = new Array(length);
for(var i = 0; i<length; i++){
    array[i]=1;
};

stopwatch.Start();
for(var i = 0; i<length; i++){
    array[i]+1;
};
var time = stopwatch.getDifference();
console.log("Time of normal for: "+time);
stopwatch.Start();
array.forEach(function(entry){
    entry+1;
});
time = stopwatch.getDifference();
console.log("Time of for each: "+time);
stopwatch.Start();
for(key in array){
    array[key]+1;
}
time = stopwatch.getDifference();
console.log("Time of for key in array: "+time);

The result is the following

Time of normal for: 29
Time of for each: 151
Time of for key in array: 803

It seems like the normal for is faster than the others implementations.  Is it right?


texts:
I'm looking for feedback on ways to improve the maintainability and readability of my code.  I'm especially interested in hearing about ways I could improve the code's adherence to good object oriented practices.  Thank you!

Purpose of the code:

Reject a client's requests if that client has already made 100 requests in the last second.  The client who sent a request is identified on the request with a clientID.

Usage:

let rateLimiter = new RateLimiter();

let request = { clientID: 1, time: 0 };

let isRequestAllowed = rateLimiter
  .addRequestAndCheckIsAllowed(request);

Implementation:

const MAX_REQUESTS_IN_TIME_FRAME = 100;
const REQUEST_MAX_AGE = 1000;

class RateLimiter {
  constructor () {
    this._clientRequests = {};
  }

  addRequestAndCheckIsAllowed (request) {
    this._storeRequest(request);

    return this._clientRequestCount(request.clientID) <=
      MAX_REQUESTS_IN_TIME_FRAME;
  }

  _storeRequest (request) {
    const clientID = request.clientID;

    this._clientRequests[clientID] =
      this._clientRequests[clientID] ||
      new RequestBuffer(REQUEST_MAX_AGE);

    this._clientRequests[clientID].store(request);
  }

  _clientRequestCount(clientID) {
    if (this._clientRequests[clientID] === undefined) {
      return 0;
    }

    return this._clientRequests[clientID].count();
  }
};

class RequestBuffer {
  constructor (requestMaxAge) {
    this._requestMaxAge = requestMaxAge;
    this._requests = [];
  }

  store (request) {
    this._requests.push(request);

    const maxTime = Date.now() - this._requestMaxAge;

    this._requests =
      this._requests.filter(request => request.time > maxTime);
  }

  count () {
    return this._requests.length;
  }
};


texts: Can I simplify my phone look-up program?

texts:
I needed to make a phone number look-up program with 10 contacts. I feel like I can shorten the program up a bit, it seems very long, but I don't know how. Any suggestion? Do I need all of the Java imports?

package phoneLookUp;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class phoneLookUp
{
static HashMap<String,String> contact = new HashMap<String, String>();

// Method getName() will return the name for given number if it is exist in the contact

public static String getName(String number)
{
Set set = contact.entrySet();
Iterator it = set.iterator();

while(it.hasNext())
{
Map.Entry me = (Map.Entry)it.next();

String tNum = (String)me.getValue();

if(tNum.equals(number))
{
return (String)me.getKey();
}

}

//if given number is not found

return "";
}

// Method getNumber() will return the Name of the given phone number if it is exist in the contact

public static String getNumber(String name)
{
Set set = contact.entrySet();
Iterator it = set.iterator();

while(it.hasNext())
{
Map.Entry me = (Map.Entry)it.next();

String tName = (String)me.getKey();

if(tName.equals(name))
{
String formattedNumber = outputFormat((String)me.getValue());
return formattedNumber;
}

}

// if name if not found in the contact

return "";
}

// Formatting the given phone number

public static String outputFormat(String phone)
{
String temp = "(";

for(int i = 0; i < phone.length(); i++)
{
if(i < 2)
temp += phone.charAt(i);

else if(i == 2)
temp += phone.charAt(i)+") ";

else if(i < 5)
temp += phone.charAt(i);

else if(i == 5)
temp += phone.charAt(i)+" - ";

else
temp += phone.charAt(i);
}

return temp;

}

public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

// contacts

contact.put("Tom","6037571122");
contact.put("Alice","6037779057");
contact.put("George","6037779103");
contact.put("Ben", "6031234322");
contact.put("Jack","6037764522");
contact.put("Greg","6039985434");
contact.put("Franklin","60344578993");
contact.put("Sam", "6033458765");
contact.put("Mike","6036673322");
contact.put("Alex", "6035561199");

System.out.println("Welcome to the Phone Look up Program ");

char ch = ' ';

do
{
System.out.print("please enter the name or phone number ( no delemeters please) (q to quit) : ");
String input = sc.next();

ch = input.charAt(0);

if(ch == 'q')
break;

// Finding whether given input is Name or Phone Number

if(Character.isDigit(ch))
{
String name = getName(input);

if(!name.equals(""))
System.out.println("Number : "+outputFormat(input)+" belongs to : "+name);

else
System.out.println("There is no listing for : "+outputFormat(input));
}

else
{
String phone = getNumber(input);

if(!phone.equals(""))
System.out.println(input+"'s"+" phone number is : "+phone);

else
System.out.println("There is no listing for : "+input);
}

}while(true);

}

}

This is my output:

  Welcome to the Phone Look up Program
  please enter the name or phone number ( no delemeters please) (q to quit) : Alice
  Alice's phone number is : (603) 777 - 9057
  please enter the name or phone number ( no delemeters please) (q to quit) : Tom
  Tom's phone number is : (603) 757 - 1122
  please enter the name or phone number ( no delemeters please) (q to quit) : Sally
  There is no listing for : Sally
  please enter the name or phone number ( no delemeters please) (q to quit) : q


texts:
How can I shorten this class method (currently 10 lines long)?

class DoubleSeries
  def self.generate_sequences(seq1_start, seq2_start, seq1_step, seq2_step, iterations)
    seq1,seq2=seq1_start,seq2_start
    result=[]
    (1..iterations).each do
      result << seq1 << seq2
      seq1+=seq1_step
      seq2+=seq2_step
    end
    result
  end
end

I tried doing:

class DoubleSeries
  def self.generate_sequences(seq1_start, seq2_start, seq1_step, seq2_step, iterations)
    seq1,seq2=seq1_start,seq2_start
    result=
    (1..iterations).each do
      self << seq1 << seq2
      seq1+=seq1_step
      seq2+=seq2_step
    end
    result
  end
end

but self is the class at this point (as this is a class method), not the result= variable.


texts:
As an exercise to improve my coding ability in C, I have attempted to write a simple and safe file reader. I believe this should be portable as well to major platforms (correct me if I'm wrong). For simplicity's sake I assume the file will fit in memory which is mostly true for my use case.

Please let me know where I can improve.

(Note: I've used goto because I think it makes the code flow better)

int read_file(const char* filename, char** buffer) {
    FILE* fp = fopen(filename, "r");
    if (!fp) {
        goto f_read_error;
    }

    ssize_t file_len;
    if (fseek(fp, 0L, SEEK_END) == 0) {
        file_len = ftell(fp);
        if (file_len == -1) {
            goto f_read_error;
        }
        if (fseek(fp, 0L, SEEK_SET) != 0) {
            goto f_read_error;
        }
        *buffer = (char*) malloc(sizeof(char) * (file_len + 1));

        int output = fread(*buffer, sizeof(char), file_len, fp);

        if (output != file_len) {
            goto f_read_error;
        };
        (*buffer)[file_len] = '\0';
    } else {
        f_read_error: ;
               char error_msg[1024];
               // let's trunc filenames larger than 256, to not overflow error_msg buffer
               char safe_filename[256];
               if (strlen(filename) > 256) {
                   memcpy(safe_filename, filename, 256);
               }
               sprintf(error_msg, "Unable to read file : %s", safe_filename);
               perror(error_msg);
               if (buffer) {
                   free(buffer);
               }
               if (fp) {
                   fclose(fp);
               }
               return -1;
     }
     if (fp) {
        fclose(fp);
     }
     return 1;
}

int main(int argc, char** argv)  {
      char* source = NULL;
      int success = read_file("test.txt", &source);
      if (success) {
            //read_file("test.txt", &source); - a copy paste error, edited as a comment
            printf("%s\n", source);
            free(source);
      }
}


texts: Generating bounded & unique random numbers in the Linux kernel

texts:
I recently needed to generate a series of unique random numbers (non-repeated) within a bounded range inside of the Linux kernel. The code I came up with is below. I'd appreciate any feedback -- again, please keep in mind that it's within the Linux kernel, so the standard C library is out of the question.

#include <linux/kernel.h>
#include <linux/random.h>
#include <linux/slab.h>

static int mod(int, int);
static int _is_repeated_int(int *, int, int);

/* proj2_create_randints - creates a buffer of random integers
 * @dstruct_size: number of random integers
 * @max_range: maximum range of values to generate
 *
 * Allocates a buffer that can hold @dstruct_size random integers. If
 * @max_range is greater than 0, mods all values by @max_value to ensure
 * they fall within the range. If @dstruct_size is greater than @max_range,
 * returns NULL. The buffer returned is guaranteed to have no duplicate values.
 *
 * On successs, it fills the buffer and returns a pointer to the buffer;
 * otherwise returns NULL.
 */
int *proj2_create_randints(int dstruct_size, int max_range)
{
    int *randint;
    int tmp, idx;

    if ((max_range != 0) && (dstruct_size > max_range))
        return NULL;

    randint = kmalloc(dstruct_size * sizeof(*randint), GFP_KERNEL);
    if (randint != NULL) {
        idx = 0;
        while (idx < dstruct_size) {
            tmp = get_random_int();
            if (max_range > 0)
                tmp = mod(tmp, max_range);
            /* Check if 'tmp' is already in array */
            if (!_is_repeated_int(randint, idx, tmp)) {
                randint[idx] = tmp;
                idx++;
            }
        }

    }
    return randint;
}

/* mod - returns x modulo m
 * @x: value to reduce
 * @m: modulo value
 *
 * Guaranteed to be positive.
 */
static int mod(int x, int m)
{
    return (x%m + m)%m;
}

/* _is_repeated_int - checks array against repeated values
 * @array: array of integers to check
 * @size: size of @array
 * @new_value: value to check array for
 */
static int _is_repeated_int(int *array, int size, int new_value)
{
    int i;

    if (size == 0)
        return 0;

    for (i = 0; i < size; i++) {
        if (array[i] == new_value) {
            return 1;
        }
    }

    return 0;
}


texts:
I have created a class for reading data from an Excel sheet and holding on the variable.  I am not sure if my code is optimized, meaning I will be reading heavily from Excel.

Is there a room to further optimized this code?  I will be using this class heaving in my code, and I wanted to get some opinions/feedback.

I will be calling something like this:

ExcelReader xl = new ExcelReader();
string sss = xl.ExcelOpenSpreadsheets("mysheet");
//etc...

public class ExcelReader
{
    Application _excelApp;

    public ExcelReader()
    {
        _excelApp = new Application();
    }

    public string ExcelOpenSpreadsheets(string sheetName)
    {
        string _txt = string.Empty;
        try
        {
            Workbook workBook = _excelApp.Workbooks.Open("filename_here",....);
            _txt = ExcelScanIntenal(workBook, sheetName);
        }

        catch
        {
            //
            // Deal with exceptions.
            //
        }
        return _txt;
    }

    private string ExcelScanIntenal(Workbook workBookIn, string sheetName)
    {
        Worksheet sheet = workBookIn.Sheets[sheetName] as Worksheet;

        Range a1 = sheet.get_Range("A1", "B2");
        if (a1 != null)
        {
            string formattedText = r.Text;
        }

        return formattedText;
    }


texts: Dynamic adding and removing div elements using event streams (eventlistners)

texts:
I has div block feedList which contains feedItems. Now to fill feedList with data (feedItems) i am using while loop. In future it will js which get data from backend dynamically.
I created 2 buttons, which is used to border num of feedItems in feedList. One is "5", another is "10". To border num of feedItems i use function which called on each event of adding feedItem div in feedList. You can see that this function check how much feedItems now in feedList: if it more than 5 - it remove old feedItem from feedList.

var removeIf5 = function (event) {
    alert("last div removed if length more than 5");
};
var removeIf10 = function (event) {
    alert("last div removed if length more than 10");
};

document.getElementById("list5Items")
  .addEventListener("click" , function(e){
    alert("1");
    feedList.removeEventListener("DOMNodeInserted", removeIf5, false);
    feedList.removeEventListener("DOMNodeInserted", removeIf10, false);
    feedList.addEventListener("DOMNodeInserted", removeIf5, false);
});

document.getElementById("list10Items")
  .addEventListener("click" , function(e){
    alert("2");
    feedList.removeEventListener("DOMNodeInserted", removeIf5, false);
    feedList.removeEventListener("DOMNodeInserted", removeIf10, false);
    feedList.addEventListener("DOMNodeInserted", removeIf10, false);
});
<!DOCTYPE html>

    <meta charset="UTF-8">

            <input type="submit" id="list10Items" value="10"/>
            <input type="submit" id="list5Items" value="5"/>

itemA

itemB

itemC

Problem in that i create 2 functions for same work: they used to remove elements, and different only in border number. One remove if feedList length is more than 5, another - more than 10.
How i can rewrite my code?


texts:
I have been writing my own Bash Scripts for a little while now. I am getting a better comprehension of it and I would like to start refining my code to be more elegant. I have recently developed this code to take a PHP file and comment out the code and add new code in.

If you could let me know how I could do better I would greatly appreciate it.

Bash Script:

## Set included files ## START ##

source /scripts/_inc/siteList.sh ## Description: Loads $siteList Array

## Set included files ## END ##

## Set Variables ## START ##

## Files in Use ## START ##
useFile='deferred.php'
tempFile='/scripts/_inc/deferredTextTemplate.php'
## Files in Use ## END ##

## File Contents ## START ##
newTop=$(head -n 15 $tempFile)
newBottom=$(tail -n 4 $tempFile)
## File Contents ## END ##

## Set Variables ## END ##

## Set Functions ## START ##

changeFile () {

    ## Info About Action to be intered into File.
    workInfo="\n// Edited: $(date)\n// Directory: $2"
    logTag="$(date): [$3 @ $2]"

    if [ -f "$1" ] ## Description: Does the file exist?
    then
        if grep -q F8kR8ikBiF "$1"; ## Description: Does the file contain this marker?
        then
            printf "%s Marker exists no changes necessary.\n" "$logTag" ## Description: Marker Exists!
        else
            ## Description: Print to Files that exist without Marker.
            orgFileCont=$(tail -n +2 $1 | sed -r 's/\/\*+ (.*) \*+\//\/\/ \1/')
            printf "%s\n%s\n%s\n%s\n" "$newTop" "$workInfo" "$orgFileCont" "$newBottom" > $1
            printf "%s File edited.\n" "$logTag"
        fi
    else
        printf "%s File not found.\n" "$logTag" ## Description: File does not exist.
    fi

}

## Set Functions ## END ##

## Set actions ## START ##

## Loop though all direcotries listed in $siteList array and perform action
for siteDirectory in "${siteList[@]}"
do
   fileLocation="/site/$siteDirectory/$useFile"
   changeFile "$fileLocation" "$siteDirectory" "$useFile"
done

## Set actions ## END ##

##EOF

Here is the Template File that is called:

<?php

/* Marker: F8kR8ikBiF */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* File Altered By Automated SH script via Cron: overwriteDeferred.sh
* script created by xxxxxxxxxxxxxxxxxxxx 10-24-14 in order to disable
* the built in cron functioanlity of Xxxxxxxx. Cron functionality will
* now be triggered by a System Cron Script: manCronTrigger.sh to run
* once per minute.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

{"moreDeferred":false}

/* Oringinal content * START *

* Oringinal content * END */

// EOF


texts: ASP.net proper login - logout classes - control login status

texts:
Would you have any suggestions improvements for the below functions classes ?

Ok here how do i make a registered member login

    HttpCookie LoginInfo = new HttpCookie("LoginInfo");
    LoginInfo.Values["UserName"] = srUserName;
    LoginInfo.Values["Password"] = srPassword;
    LoginInfo.Values["selectedLanguage"] = srSelectedLanguage;
    Response.Cookies.Add(LoginInfo);

Here how do i check visitor is logged in or not

public static void controlOfLoginStatus()
{
    string srQuery = "";
    string srUserName = "";
    string srPassword = "";
    string srLang = "";

    if (HttpContext.Current.Session["UserId"] == null)
    {
        if (HttpContext.Current.Request.Cookies["LoginInfo"] != null)
        {
            try
            {
                srUserName = HttpContext.Current.Request.Cookies["LoginInfo"]["UserName"].ToString();
                srPassword = HttpContext.Current.Request.Cookies["LoginInfo"]["Password"].ToString();
                srLang = HttpContext.Current.Request.Cookies["LoginInfo"]["selectedLanguage"].ToString();
            }
            catch
            {

            }
        }
        string srUserIdTemp = csPublicFunctions.ReturnUserIdUsernamePassword(srUserName, srPassword);
        if (srUserIdTemp == "0")
        {
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Redirect("Login");
        }
        else
        {
            csPublicFunctions.insertIntoOnlineUsers(srUserIdTemp, HttpContext.Current.Session.SessionID);
            HttpContext.Current.Session["UserId"] = srUserIdTemp;
            if (HttpContext.Current.Session["lang"] == null)
                HttpContext.Current.Session["lang"] = srLang;
        }
    }

    srQuery = "SELECT UserId " +
     " FROM BannedUsers" +
     " WHERE UserId = " + HttpContext.Current.Session["UserId"].ToString();
    using (DataTable dtTemp = DbConnection.db_Select_DataTable(srQuery))
    {
        if (dtTemp.Rows.Count > 0)
        {
            HttpContext.Current.Response.Redirect("exit.aspx");
        }
    }
}

Here how do i log-out

public static void exitLogout()
{
    string srQuery = "delete from OnlineUsers where UserId=" + HttpContext.Current.Session["UserId"].ToString();
    DbConnection.db_Update_Delete_Query(srQuery);

    try
    {
        HttpContext.Current.Session["UserId"] = "0";
        HttpContext.Current.Session.Clear();
        HttpContext.Current.Session.Abandon();
    }
    catch
    {

    }

    try
    {
        HttpCookie LoginInfo = new HttpCookie("LoginInfo");
        LoginInfo.Values["UserName"] = "21412zxcvzxc343245243vvc";
        LoginInfo.Values["Password"] = "21412zxcvzxc343245243vvc";
        LoginInfo.Values["selectedLanguage"] = "en";
        HttpContext.Current.Response.Cookies.Add(LoginInfo);
    }
    catch
    {
    }
}

csPublicFunctions.ReturnUserIdUsernamePassword uses parametrized queries so no possible risk of SQL injection


texts: Python script takes input of four elements and outputs a valid 4 × 4 Sudoku grid in O(n) time, but only when given non-repeating elements

texts:
Introduction

I've found a clever and fun thing to do after solving a n2 × n2 sudoku puzzle. I can take
a grid as such as this one and hard-code its indices as constraints to output other 4 × 4 latin squares in poly-time

Now, I took each successive row and hardcoded as indices with successive print statements.

Indices constraints

0123
3210
1032
2301

Working Code

print('enter with [1,2,3...] brackets')
text = input()[1:-1].split(',')
print(text[0], text[1], text[2], text[3])
print(text[3], text[2], text[1], text[0])
print(text[1], text[0], text[3], text[2])
print(text[2], text[3], text[0], text[1])

Question

Being a novice at python I'm asking is there a better way of hardcoding the Sudoku's pattern with fewer lines of code?

Because it would be daunting to have to write larger constraints for larger latin squares.

I would appreciate it to keep it O(n) time because I have a desire to input integers besides just elements 1-4. But, 100-104 and so on..


texts:
I built a search bar that will filter an array of objects. But I feel like I can improve it. When I filter, I want to filter the first and last name case insensitive, then sort the names and then map them to be rendered.

I'm using typescript so ignore SelectedProps:

return contacts
    .filter((item: SelectedProps) => (item.firstName + item.lastName).toLowerCase().includes(search.toLowerCase()))
    .sort((a: SelectedProps, b: SelectedProps) => a.firstName > b.firstName ? 1 : -1)
    .map((item: SelectedProps, index: number) => (
     // IGNORE OUTCOME
    ));