texts: Making a Pong ball reflect off the paddle

texts:
I am currently making Pong in C++/SDL2 and after a while of tinkering, I have come up with a solution!

This function gets the hit position and returns the necessary direction change:

MoveDirection Ball::getHitPos(const Player& player) const
{
    MoveDirection dir; //Direction of movement

    //If ball is moving left
    if (m_dir == MoveDirection::LEFT)
    {
        std::cout << "Yes";
        int hitPos = m_pos.y - player.getPos().y; //Get hit position
        int playerSize = player.getPos().h / 2;
        int offSet = 25; //Enables to split up positions into three seperate parts
        //Calculate dir change
        if (hitPos <= playerSize - offSet) {
            dir = MoveDirection::RIGHTUP;
        }
        else if (hitPos >= playerSize + offSet) {
            dir = MoveDirection::RIGHTDOWN;
        }
        else {
            dir = MoveDirection::RIGHT;
        }
    }

    //If Ball is moving right
    if (m_dir == MoveDirection::RIGHT)
    {
        int hitPos = m_pos.y - player.getPos().y; //Get hit position
        int playerSize = player.getPos().h / 2;
        int offSet = 25; //Enables to split up positions into three seperate parts
        //Calculate dir change
        if (hitPos <= playerSize - offSet) {
            dir = MoveDirection::LEFTUP;
        }
        else if (hitPos >= playerSize + offSet) {
            dir = MoveDirection::LEFTDOWN;
        }
        else {
            dir = MoveDirection::LEFT;
        }
    }

    return dir;
}

Here are all of the possible movement directions:

enum class MoveDirection
{
    UP,
    DOWN,
    LEFT,
    RIGHT,
    LEFTUP, //Ball diagonal movement
    LEFTDOWN, //Ball diagonal movement
    RIGHTUP, //Ball diagonal movement
    RIGHTDOWN //Ball diagonal movement
};

And here is the height of the racket:

static constexpr int SIZE_HEIGHT = 75;

I must also note that m_pos is SDL_RECT and player.getPos().y is getting the y element of SDL_RECT.


texts: Hackerrank challenge - Dictionaries and Maps in Erlang

texts:
This question is really similar to an existing one in Ruby. So the task is also the same: Day 8: Dictionaries and Maps!

The problem is that on Hackerrank my solution only passes the first and last testcases. All the other ones between them are timing out (>12s!). I tried to use map instead of dict and also read the queries first into a list and process them separately as was suggested in the discussion. I have a feeling it goes to infinite recursion because I'm doing the line read/strip wrong.

-module(solution).
-export([main/0]).

main() ->
    { ok, [N]} = io:fread("", "~d"),
    Dict = read_dictionary(N, dict:new()),
    queries(Dict).

read_dictionary(0, D) -> D;
read_dictionary(N, D) ->
    Name = stripped_next_line(),
    Number = stripped_next_line(),
    read_dictionary(N-1, dict:store(Name, Number, D)).

queries(Dict) ->
    queries(Dict, io:get_line("")).
queries(_, eof) -> true;
queries(Dict, Name) ->
    find_number_of(strip_line(Name), Dict),
    Next = io:get_line(""),
    queries(Dict, Next).

find_number_of(Name, Dict) ->
    out(dict:find(Name, Dict), Name).

out({ok, Number}, Name) -> io:format("~s=~s~n", [Name, Number]);
out(error, _) -> io:format("Not found~n").

strip_line(Line) -> string:strip(Line, both, $\n).
stripped_next_line() -> strip_line(io:get_line("")).


texts:
It takes around 5-8 seconds for me to retrieve a previously-closed stock price and a dividend rate from US Yahoo! Finance. If I wanted to retrieve 10+ stock prices, it would take me more than a minute with the below VBA code.

Is there any other way to speed up or improve the code?

I input multiple stock code on column B and retrieve data on column C & D:

Column B = stock code (e.g. HPQ, IBM, AAPL)
Column C = previous closed price
Column D = dividend rate

Sub Button1_Click()

Dim ie As Object
Dim r As Integer
Dim prevClose As String
Dim div As String
Dim Doc As HTMLDocument

With Application
 .DisplayAlerts = False
 .ScreenUpdating = False
 .Calculation = xlCalculationManual
 .EnableEvents = False
 .StatusBar = "Retrieving data from internet explorer"
End With

Dim time1 As Double, time2 As Double
time1 = Timer

Set ie = CreateObject("InternetExplorer.Application")

For r = 2 To Range("B65535").End(xlUp).Row

With ie
  .Visible = 0

  .navigate "http://finance.yahoo.com/q?s=" & Cells(r, "B").Value

   While .Busy Or .readyState <> 4 'add do or not
   DoEvents
   Wend

End With

 Set Doc = ie.document

 prevClose = Trim(Doc.getElementById("table1").getElementsByTagName("td")(0).innerText)
 Cells(r, "C").Value = prevClose

 div = Trim(Doc.getElementById("table2").getElementsByTagName("tr")(7).getElementsByTagName("td")(0).innerText)
 Cells(r, "D").Value = div

Next r

ie.Quit: Set ie = Nothing

With Application
 .DisplayAlerts = True
 .ScreenUpdating = True
 .Calculation = xlCalculationAutomatic
 .EnableEvents = True

End With

time2 = Timer
MsgBox Format(time2 - time1, "0.00 \s\ec")

End Sub


texts: Finding the first two numbers that sum to a given number

texts:
Task aim: Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of
  appearance that add up to form the sum.

I've been trying to make my implemented function below run faster (less than 7000ms) and taking into account records upwards of 10,000,000 items.

While it works for basic tests such as these:

sum_pairs( [1, 4, 8, 7, 3, 15], 8 ) == [1, 7]
sum_pairs( [1, -2, 3, 0, -6, 1], -6 ) == [0, -6]
sum_pairs( [20, -13, 40], 7 ) == undefined
sum_pairs( [1, 2, 3, 4, 1, 0], 2 ) == [1, 1]
sum_pairs( [10, 5, 2, 3, 7, 5], 10 ) == [3, 7]
sum_pairs( [4, -2, 3, 3, 4], 8 ) == [4, 4]
sum_pairs( [0, 2, 0], 0 ) == [0, 0]
sum_pairs( [5, 9, 13, -3], 10 ) == [13, -3]

it breaks with some other unseen tests (which presumably have some tricky 'edge cases' and thus, breaks my implementation which I suspect isn't an optimal solution.

It's been weeks now and I really would appreciate some guidance or signpost to some helpful resource to set me on the right track.

var sum_pairs = function (ints, s) {
    //your code here
    var i = 0,
    j = 0,
    len = ints.length,
    min = undefined,
    count = 0;

    for (i; i < len; i++) {
        j = i + 1;
        while (j < len) {
           if (s - ints[i] === ints[j]) {
               if ( !min || (j < min[1]) ) {
                   min = [i, j];

                   // Check if worth continuing
                   close = (i+1===j);
                   if ( close ) break;
                }
            }
            j++;
        }
    }

    if (min !== undefined){
        min[0] = parseInt(ints[min[0]]);
        min[1] = parseInt(ints[min[1]]);
    }
    return min
}


texts: Identify duplicate characters in a String and replace them

texts:
Found a JavaScript assignment on Codewars.com:

  The goal of this exercise is to convert a string to a new string where
  each character in the new string is '(' if that character appears only
  once in the original string, or ')' if that character appears more
  than once in the original string. Ignore capitalization when
  determining if a character is a duplicate.

  Examples:

"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("

I did the assignment in Java, and came up with below code. I want to know is this the write way to code or is there a better way? If so please let me know.

private static String duplicateEncode(String word) {
    String encodeString = "";
    String decodedString = word.toLowerCase();
    for (int i = 0; i < decodedString.length(); i++) {

        if (decodedString.substring(i + 1, decodedString.length())
                .contains(String.valueOf(decodedString.charAt(i)))
                || decodedString.substring(0, i).contains(String.valueOf(decodedString.charAt(i)))) {
            encodeString += ")";
        } else {
            encodeString += "(";
        }

    }
    return encodeString;
}


texts: Codeforces problem Java code optimization

texts:
The problem says:

You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p,q)=∑i=1ⁿ|xi−yi|.
Find the sum of f(p,q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input:
The first line contains a single integer n (1≤n≤150000).
The second line contains 2n integers a1,a2,…,a2n (1≤ai≤10^9) — elements of array a.
Output:
Print one integer — the answer to the problem, modulo 998244353.

My solution generates all combinations of size n from a, then goes through each pair of combinations that complement each other, sorts them, and finally calculates the cost. Here is the code:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class Main {

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

        // reads the values
        int k = in.nextInt();
        int[] input = new int[2 * k];
        for (int i = 0; i < 2 * k; i++) {
            input[i] = in.nextInt();
        }

        List<int[]> combinations = new ArrayList();
        int[] indices = new int[k];

        //generates all valid combinations of size k, choosing k
        for(int i = 0; (indices[i] = i) < k - 1; i++);
        combinations.add(getCombination(input, indices));
        for (;;) {
            int i;
            for (i = k - 1; i >= 0 && indices[i] == input.length - k + i; i--);
            if (i < 0) {
            break;
            }
            indices[i]++;
            for (++i; i < k; i++) {
                indices[i] = indices[i - 1] + 1;
            }
            combinations.add(getCombination(input, indices));
        }
        //for depugging
        //combinations.forEach(e -> System.out.println(Arrays.toString(e)));
        //int[] temp1, temp2;

        //goes through all pairs that complement each other and calculates the cost for each
        int theSum = 0;
        for (int i = 0, j = combinations.size() - 1; i < combinations.size() && j >= 0; i++, j--) {
          //  temp1 = combinations.get(i);
          //  temp2 = combinations.get(j);
            Arrays.sort(combinations.get(i));
            Arrays.sort(combinations.get(j));
            reverse(combinations.get(j));
            //for debugging
            //System.out.println(Arrays.toString(temp1) + ", " + Arrays.toString(temp2));
            theSum += cost(combinations.get(i), combinations.get(j));
        }
        System.out.println(theSum % 998244353);
    }
    public static int[] getCombination(int[] input, int[] indices) {
         int[] result = new int[indices.length];
        for (int i = 0; i < indices.length; i++)
            result[i] = input[indices[i]];
        return result;
    }
    public static int cost(int[] x, int[] y) {
        int sum = 0;
        for (int i = 0; i < x.length; i++) {
            sum += Math.abs(x[i] - y[i]);
        }
        return sum;
    }
    public static void reverse(int[] array) {
        for(int i = 0; i < array.length / 2; i++) {
            int temp = array[i];
            array[i] = array[array.length - i - 1];
            array[array.length - i - 1] = temp;
        }
    }
}

The memory usage exceeded 512 MB and I don't know if I should change the data structures, or the algorithms, or both. I would appreciate any suggestions.


texts: Implementing parser combinators in a functional manner

texts:
I am just starting on my journey of learning clojure (I have just read to the end of chapter 3 in clojure for the brave and true). So for practice, I wrote some parser combinator functions. I am quite familiar with several imperative and object oriented languages, but this is my first time using a lisp language, and my first time programming in the functional paradigms.

How can this code be improved to be more idiomatic clojure code?

How can I condense the sequential parser function? I can write it in 6 lines of python, here it's close to 40 lines.

Also, I am not really sure the commonly accepted way of formatting code, like indentation and bracket placement- is this style commonly used?

Anyways, I welcome any and all feedback.

(ns main.core
  (:gen-class))

; the error message for the parser functions
(def error false)

; Parses a single charactor
(defn lit[c]
  (fn [stream]
    (if (= (first stream) (first (seq c)))
      (list (seq c) (rest stream))
      error
      )
    )
  )

; returns first successful parse
(defn alt[& ps]
  (fn [stream]
    (reduce #(or %1 %2) error (map #(% stream) ps))
    )
  )

; Tries to parse in series, error if any have an error
; This is the python code this function was based on

; It takes in a list of parser functions, tries to run all of them in a row,
; and if any of them fail, returns an error, otherwise it returns the stream,
; which changes each time a parser is run, as well as the results of all the successful parses in a list.

; def SequenceParser(*parsers):
;     def parser(stream):
;         res = []
;         for p in parsers:
;             r, stream = p(stream)
;             res.append(r)
;         return (res, stream)
;     return parser

(defn seqn[& ps]
  (fn [stream]
    (apply
      (defn inner
        ([stm p0]
         (p0 stm)
         )
        ([stm p0 p1]
         ((fn [r0]
            (if r0
              ((fn [r1]
                 (if r1
                   (list (list (nth r0 0) (nth r1 0)) (nth r1 1))
                   error
                   )) (p1 (nth r0 1)))
              error
              )) (p0 stm))
         )
        ([stm p0 p1 & p]
         (def r0 (p0 stm))
         (if r0
           ((fn [r1]
              (if r1
                ((fn [res]
                   (list (list (nth r0 0) (nth r1 0) (nth res 0)) (nth res 1))
                   ) (apply inner (nth r1 1) p))
                error
                ))(p1 (nth r0 1)))
           error
           )
         )
        )
      stream ps)
    )
  )

; Parser that parses as many times as it can, at least once though, or it is an error
(defn many [p0]
  (fn [stream]
    ((fn inner [stm]
       ((fn [res]
          (if res
            ((fn [r1]
               (if r1
                 (list (concat (nth res 0) (nth r1 0)) (nth r1 1))
                 res
                 )
               ) (inner (nth res 1)))
            res
            )) (p0 stm))
       ) stream
     )
    )
  )

; parser that applys a function to the result of another parser
(defn func [p0 f]
  (fn [stream]
    ((fn [res]
       (list (f (nth res 0)) (nth res 1))
       ) (p0 stream))
    )
  )

(defn num-to-int [n]
  (Integer/parseInt (apply str n))
  )

(defn get-val [[res remains]]
  res
  )

(defn -main
  "Main function, this computes the number 1904 from the string '34*56'"
  [& args]

  (def digit (alt (lit "1") (lit "2") (lit "3") (lit "4") (lit "5") (lit "6") (lit "7") (lit "8") (lit "9") (lit "0")))
  (def number (func (many digit) num-to-int))
  (def mul (func (seqn number (lit "*") number), (fn [[a b c]] (* a c))))
  (println (get-val(mul "34*56")))

  )

For reference parser contaminators are functions that generate functions that parse string data. The results of the parser combinators can be combined, hence the name to easily produce complex parsing functions.

http://theorangeduck.com/page/you-could-have-invented-parser-combinators
This is a great read that explains them well if anyone is interested.


texts: Redirect http to https, non-www to www and "/index.php" to "/"

texts:
Is this htaccess code the best/proper way to:

Send all http traffic to https
Send any visits to index.php to the URL that doesn't show "index.php"
Send all non-www traffic to www

This code works to do those things I mentioned, I just want to make sure it's the most proper/efficient way to do it and/or it's ordered correctly...

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ https://www.example.com/$1 [R=301,L]
rewritecond %{http_host} ^example.com [nc]
rewriterule ^(.*)$ https://www.example.com/$1 [r=301,nc]


texts:
Let me know if the given code can be improved or optimized:

public static String getFileNameWithoutExtensiotn(File file) {
    String fileName = null;
    if (file.getName().startsWith(".")) {//if starts with "." like .htaccess
        fileName = file.getName();
    } else {
        try {
            fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
        } catch (Exception e) {
            fileName = file.getName();
        }
    }

    return fileName;
}


texts:
I have a class that I'm using to find the shortest word ladder between two words. Each "Step" in that ladder is returned as a String element in a LinkedList. If it can't find one, it returns an empty LinkedList. The class is only intended to work with capital letters.

A step can only be formed from a word in the HashSet<String> dictionary variable.

I haven't made anything like this before, and I'm posting here because I'd appreciate help making it run faster and advice regarding how to make the code itself more easily read by other humans.

public class WordLadder {

private HashSet<String> dictionary;

public WordLadder(HashSet<String> dictionary) {

   this.dictionary = dictionary;
}

/**
 * This method finds the shortest word ladder between two words and returns
 * it as a LinkedList of Strings.
 *
 * @return LinkedList of Strings.
 */
@SuppressWarnings("unchecked")
public LinkedList<String> findLadder(String input) {

   // this method relies on deleting entries from a HashSet
   HashSet<String> tempDict = (HashSet<String>) this.dictionary.clone();

   // create LinkedLists
   LinkedList<Integer> distances = new LinkedList<>();
   LinkedList<LinkedList<String>> ladders = new LinkedList<>();
   LinkedList<String> words = new LinkedList<>();

   // split the input line into the starting and ending words
   String startWord = input.substring(0, input.indexOf(" "));
   String endWord = input.substring(input.indexOf(" ") + 1);

   // holds the shortest ladder found
   LinkedList<String> shortestLadder = new LinkedList<>();

   words.add(startWord);
   distances.add(1);

   ladders.add(new LinkedList<>(Arrays.asList(startWord)));

   while (!words.isEmpty()) {
      Integer distance = distances.pop();
      LinkedList<String> ladder = ladders.pop();
      String word = words.pop();

      // has the shortest ladder been found?
      if (word.equals(endWord)) {
            shortestLadder = ladder;
      }

      for (int i = 0; i < word.length(); i++) {

         char[] currCharArr = word.toCharArray();

         for (char c = 'A'; c <= 'Z'; c++) {
            currCharArr[i] = c;
            LinkedList<String> currentPathQueueTemp = new LinkedList<>(ladder);

            String newWord = new String(currCharArr);

            if (tempDict.contains(newWord)) {
               words.add(newWord);
               ladders.add(currentPathQueueTemp);
               tempDict.remove(newWord);
               distances.add(distance + 1);
               currentPathQueueTemp.add(newWord);
            }
         }
      }
   }

   return shortestLadder;
}

}


texts:
I have this vbs file to check if a remote server is accessible. Can I simplify or refactor to make it more robust/efficient?

const forReading = 1, forWriting = 2, forAppending = 8
public maxWaitTime
maxWaitTime = 60 '1800 '30mins
public connLogFileName
connLogFileName = "connectionLog.txt"
public pathToRemoteServer
pathToRemoteServer = "c:\"
public errMessage
public fs
set fs = createObject("scripting.fileSystemObject")

pathToRemoteServer = "c:\"

'::::::::::::::::::::::::::::::
call mainSub()

'::::::::::::::::::::::::::::::
sub mainSub()
  call createLogFile()

  errMessage = ""
  dim curDir
  curDir = fs.GetAbsolutePathName(".")
  dim logName
  logName = curDir & "\" & connLogFileName
  Dim aFile
  set aFile = fs.openTextFile(logName, forAppending, True)

  if (checkFolderPath(pathToRemoteServer)) then
    aFile.WriteLine lineToWrite & " ok"
  else
    aFile.WriteLine lineToWrite & " " & errMessage

    dim downTime
    downTime = 0
    do Until (checkFolderPath(pathToRemoteServer)) or downTime => maxWaitTime
      WScript.Sleep 500  'half second
      downTime = downTime + 0.5
    loop

    aFile.WriteLine lineToWrite & " back after seconds: " & downTime

  end if

  aFile.close
  if not aFile is nothing then set aFile = nothing
end sub

'::::::::::::::::::::::::::::::
sub createLogFile()
  dim logName
  logName = fs.GetAbsolutePathName(".") & "\" & connLogFileName
  If not fs.FileExists(logName) Then
    fs.createTextFile logName, false
  End If
end sub

':::::::::::::::::::::::::::::::::::::::::
function lineToWrite()
  dim curUser
  curUser = createObject("WScript.Network").userName
  lineToWrite = curUser & ": " & Now()     '& vbCrLf
end function

':::::::::::::::::::::::::::::::::::::::::
function checkFolderPath(folder_path)
  checkFolderPath = false
  On Error Resume Next

  dim fn
  fn = folder_path & "testfile." & myDateFormat(Now())

  dim aFile
  set aFile = fs.createTextFile(fn, True)
  if err.Number <> 0 Then
    errMessage = "Error on crt: " & err.description
    err.clear
    checkFolderPath = false
    exit function
  end if

  aFile.WriteLine ("This is a test file " & fn)
  if err.Number <> 0 Then
    errMessage = "Error on wrt: " & err.description
    err.clear
    checkFolderPath = false
    exit function
  end if

  aFile.Close
  if err.Number <> 0 Then
    errMessage = "Error on cls: " & err.description
    err.clear
    checkFolderPath = false
    exit function
  end if

  fs.DeleteFile fn
  if err.Number <> 0 Then
    errMessage = "Error on del: " & err.description
    err.clear
    checkFolderPath = false
    exit function
  end if

checkFolderPath = true
if not aFile is nothing then set aFile = nothing
end function

':::::::::::::::::::::::::::::::::::::::::
function myDateFormat(aDate)
  sc = second(aDate)
  mn = minute(aDate)
  hr = hour(aDate)
  dy = day(aDate)
  mt = month(aDate)
  yr = year(aDate)
  myDateFormat= yr & mt & dy & hr & mn & sc
end function


texts: Running a simulation for all unique combinations of a range of parameters

texts:
I have written a script which is supposed to call the function at the bottom for each unique combination of values in the parameter vectors. That function is a simulation which I intend to run over all the unique combinations of those parameters. The simulation is run on a cluster, and the sim_ind for each of these jobs is pulled from the environment.

Currently, my solution is to build a matrix with each row corresponding to a unique set of parameters. Then the sim_ind value (passed from the environment) is used to determine which unique set of parameters will be used in that iteration by indexing the matrix.

The following is the code that I am using, which works:

% getting sim_ind from env
AI = getenv('PBS_ARRAYID');
sim_ind = str2num(AI);

time_slots = 40000;

% parameter vectors
up_down_ratio_arr = [1];
traffic_load_arr = [ 0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10, 100, Inf ];
blocked_modes_ind_arr = [1 2 3];
traffic_model_arr = [1 2];

% total number of unique combinations
uniq = length(up_down_ratio_arr) * length(traffic_load_arr) * length(blocked_modes_ind_arr) * length(traffic_model_arr);
parameters = zeros(uniq, 4);

% propagating the parameter list matrix
counter = 0;
for i = up_down_ratio_arr
    for j = traffic_load_arr
        for k = blocked_modes_ind_arr
            for l = traffic_model_arr
                counter = counter + 1;

                parameters(counter, 1) = i;
                parameters(counter, 2) = j;
                parameters(counter, 3) = k;
                parameters(counter, 4) = l;
            end
        end
    end
end

% wrapping the sim_ind
ind = mod(sim_ind, uniq);

% mod maps all multiples of the largest index to zero
if ind == 0
    ind = uniq;
end

% retrieving a parameter set
up_down_ratio = parameters(ind,1);
traffic_load = parameters(ind,2);
blocked_modes_ind = parameters(ind,3);
traffic_model = parameters(ind,4);

% call the routine
MainCode_Single_Backahul_Cell_Sch(time_slots, up_down_ratio, traffic_load, blocked_modes_ind, traffic_model, ceil(sim_ind/uniq) );

Is there a better way?

I have a version in which I use mod to map each value of the sim_ind parameter to a value that exists in the range of each vector. The problem with this solution was that not all the combination were unique. For example, in the following code traffic_load_arr is of size 10, and traffic_model_arr is of size 2. Therefore, whenever the 8th element of traffic_load_arr is selected; i.e. mod(sim_ind, 10) == 8, then the 2nd element of traffic_model_arr must also be selected. As a results, the parameter combination of traffic_load == 10 and traffic_model == 2 will never be formed.

I would appreciate for all code to be cross compatible with MATLAB and Octave.


texts: Sum of HList (where all elements are Nat's)

texts:
I wrote the following to output, at the type level, the sum, Nat, of an input HList:

trait HListSum[L] {
  type Out
}
object HListSum {

  type Aux[L, O] = HListSum[L] { type Out = O }

  def apply[L <: HList](implicit ev: HListSum[L]): ev.type = ev

  implicit def hListSumInductive[H <: Nat, L <: HList, S <: Nat, T <: Nat](
    implicit rest: HListSum.Aux[L, T],
             all: Sum.Aux[H, T, S]): HListSum.Aux[H :: L, S] = new HListSum[H :: L] {
    type Out = S
  }

  implicit val hlistSumHNil: HListSum.Aux[HNil, _0] = new HListSum[HNil] {
    type Out = _0
  }
}

Testing:

import net.HListSum
import shapeless._
import nat._

scala> HListSum[_1 :: _2 :: _3 :: HNil]
res0: net.HListSum.Aux[shapeless.::[shapeless.nat._1,shapeless.::[shapeless.nat._2,shapeless.::[shapeless.nat._3,shapeless.HNil]]],this.Out] = net.HListSum$$anon$4@132c4879

scala> val expected: res0.Out = _6
expected: res0.Out = Succ()

scala> HListSum[_0 :: _0 :: _1 :: HNil]
res1: net.HListSum.Aux[shapeless.::[shapeless.nat._0,shapeless.::[shapeless.nat._0,shapeless.::[shapeless.nat._1,shapeless.HNil]]],this.Out] = net.HListSum$$anon$4@a7b83a8

scala> val expected2: res1.Out = _1
expected2: res1.Out = Succ()

scala> val expected2: res1.Out = _3
<console>:19: error: type mismatch;
 found   : shapeless.nat._3
    (which expands to)  shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]
 required: res1.Out
    (which expands to)  shapeless.Succ[shapeless._0]
       val expected2: res1.Out = _3
                                 ^

Please critique my code. Also, am I using induction to determine the sum for the non-HNil case?


texts: Group inner properties from an array of objects to a map

texts:
I have an array of object and I want to group/order some inner properties in a map according to a key.
I did this code but I would like to know if there was a way to optimize the code ?

const myArray = [{
    getValue: () => {
      return {
        country: 'France',
        city: 'Toulouse',
      };
    },
  },
  {
    getValue: () => {
      return {
        country: 'England',
        city: 'London',
      };
    },
  },
  {
    getValue: () => {
      return {
        country: 'France',
        city: 'Paris',
      };
    },
  },
];
const myMap = new Map();
myArray.forEach(item => {
  const key = item.getValue().country;
  const value = item.getValue().city;
  if (myMap.has(key)) {
    myMap.get(key).push(value);
  } else {
    myMap.set(key, [value]);
  }
});

for (const [key, value] of myMap) {
  console.log(`${key} = ${value}`);
}


texts:
I am styling my react native component according to some conditions, here the code, The question is how do I make this cleaner? functional style?
const configColors = (isSingle, isDarkMode) => {
  let colors = {};

  if (isDarkMode){
    colors = {
      ...colors,
      configAxisLabelColor : Colors.white,
      configAxisGridColor : Colors.gridLineGray
    }
  }else{
    colors = {
      ...colors,
      configAxisLabelColor : Colors.lineGray,
      configAxisGridColor : Colors.transparent
    }
  }

  if (isSingle && !isDarkMode) {
    return colors = {
      ...colors,
      configAxisColor: Colors.transparent,
      configLineColor: Colors.lineGreen,
      configTooltipBackground: Colors.lineGreen,
    }
  }
  if (isSingle && isDarkMode) {
    return colors = {
      ...colors,
      configAxisColor: Colors.white,
      configLineColor: Colors.lineBlue,
      configTooltipBackground: Colors.lineBlue,
    }
  }
  if (!isSingle && !isDarkMode) {
    return colors = {
      ...colors,
      configAxisColor: Colors.lightBarGray,
      configLineColor: Colors.lineGray,
      configTooltipBackground: Colors.lineBlue,
    }
  }

}

Thanks in advance!


texts:
I currently have this bit of code, but I need to repeat it for red green and blue.  Is there a way I can do it without copying and pasting the code 3 times?

yellow.setOnClickListener(new View.OnClickListener() {
    public void onClick (View v)   {

        switch (buttonCount) {
        case 1:
            empty1.setImageResource(R.drawable.yellow);
            buttonCount++;
            guess1= Colour.YELLOW;
            break;
        case 2:
            empty2.setImageResource(R.drawable.yellow);
            buttonCount++;
            guess2=Colour.YELLOW;
            break;
        case 3:
            empty3.setImageResource(R.drawable.yellow);
            buttonCount++;
            guess3=Colour.YELLOW;
            break;
        case 4:
            empty4.setImageResource(R.drawable.yellow);
            buttonCount++;
            guess4=Colour.YELLOW;
            break;
        case 5:
            empty5.setImageResource(R.drawable.yellow);
            buttonCount++;
            guess5=Colour.YELLOW;
            break;

        }
    }
});


texts:
Let me know if it seems right to you and if anything can be optimized. My concern is that I'm unsure if circular linked lists are supposed to have a tail. I've implemented it just using a head. Is that wrong? If so, how would you change it to make it proper?

/*
 * Circular Linked List
 *
 */

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

typedef struct Node {
    int data;
    struct Node *next;
} Node;

void insert_beg_of_list(Node *current, int data);
void delete(Node *current, int data);
void print_list(Node *current);
int find_in_a_list(Node *current, int data);

void insert_beg_of_list(Node *current, int data) {
    //keep track of first node
    Node *head = current;

    while(current->next != head) {
        current = current->next;
    }
    current->next = (Node*)malloc(sizeof(Node));
    current = current->next;
    current->data = data;
    current->next = head;

}

void delete_from_list(Node *current, int data) {

    Node *head = current;
    while(current->next != head && (current->next)->data != data) {
        current = current->next;
    }
    if(current->next == head) {
        printf("%d element is not found\n\n", data);
        return;
    }
    Node *tmp;
    tmp = current->next;
    current->next = tmp->next;
    free(tmp);
    return;
}

void print_list(Node *current) {

    Node *head = current;
    current = current->next;
    while(current != head){
        printf(" %d ", current->data);
        current = current->next;
    }

}

int find_in_a_list(Node *current, int data) {

    Node *head = current;
    current = current->next;
    while(current != head) {
        if(current->data == data) {
            // Key found
            return 1;
        }
        current = current->next;
    }
    // Key is not found
    return 0;
}

int main() {

    Node *head = (Node *)malloc(sizeof(Node));
    head->next = head;

    int data = 0;
    int usr_input = 0;

    while(1){
        printf("0. Exit\n");
        printf("1. Insert\n");
        printf("2. Delete\n");
        printf("3. Print\n");
        printf("4. Find\n");

        scanf("%d", &usr_input);

        // can also use a switch instead
        if( usr_input == 0) {
            exit(0);

        } else if(usr_input == 1) {
            printf("\nEnter an element you want to insert: ");
            scanf("%d", &data);
            insert_beg_of_list(head, data);

        } else if(usr_input == 2) {
            printf("\nEnter an element you want to delete: ");
            scanf("%d", &data);
            delete_from_list(head, data);

        } else if( usr_input == 3) {
            printf("The list is ");
            print_list(head);
            printf("\n\n");

        } else if( usr_input == 4) {
            printf("\nEnter an element you want to find: ");
            scanf("%d", &data);
            int is_found = find_in_a_list(head, data);
            if (is_found) {
                printf("\nElement is found\n\n");
            } else {
                printf("\nElement is NOT found\n\n");
            }
        }
    }
    return 0;
}


texts:
I'm trying to make a drop down menu with click event. I have this HTML structure:

            Menu 1

Submenu 1

Submenu 1

            Menu 2

Submenu 2

            Menu 3

Submenu 3

Submenu 3

I want to avoid the double drop down, so I made this script:

$(document).ready(function(){
            $('li.submenu1').hide();
            $('li.menu1').click(function(e){
                $(this).find('li.submenu1', this).slideToggle('fast');
                $('li.submenu2').hide();
                $('li.submenu3').hide();
                e.stopPropagation();
            })
            $('li.submenu2').hide();
            $('li.menu2').click(function(e){
                $(this).find('li.submenu2', this).slideToggle('fast');
                $('li.submenu1').hide();
                $('li.submenu3').hide();
                e.stopPropagation();
            })
            $('li.submenu3').hide();
            $('li.menu3').click(function(e){
                $(this).find('li.submenu3', this).slideToggle('fast');
                $('li.submenu1').hide();
                $('li.submenu2').hide();
                e.stopPropagation();
            })
        })

Is there any way to simplify the code? Perhaps some auto-increment tricks will help.


texts: A Python Tkinter GUI which you can flick between images

texts:
I am new to Python and following tutorials.
This one I came across was for TKinter, and throughout I felt I re-wrote the same lines of code time and time again which I wondered if it could be better written.

I am interested to know how you would improve this code.

Thanks.

(First time posting, hope it's ok).

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.title("Learn to code")
root.iconbitmap("C:\\palmTree.ico")

#random images
my_img1 = ImageTk.PhotoImage(Image.open("C:\\mountainLake.jpg"))
my_img2 = ImageTk.PhotoImage(Image.open("C:\\freedom.jpg"))
my_img3 = ImageTk.PhotoImage(Image.open("C:\\streetCoffee.jpg"))
my_img4 = ImageTk.PhotoImage(Image.open("C:\\surfBoarding.jpg"))
my_img5 = ImageTk.PhotoImage(Image.open("C:\\oldFence.jpg"))

image_list = [my_img1, my_img2, my_img3, my_img4, my_img5]

my_label = Label(image=my_img1)
my_label.grid(row=0,column=0,columnspan=3)

def forward(image_number):
    global my_label
    global button_forward
    global button_back

    my_label.grid_forget()
    my_label = Label(image=image_list[image_number-1])
    button_forward = Button(root, text=">>", command=lambda: forward(image_number+1))
    button_back = Button(root, text="<<", command=lambda: back(image_number-1))

    if image_number == 5:
        button_forward = Button(root, text = ">>", state=DISABLED)

    my_label.grid(row=0,column=0,columnspan=3)
    button_back.grid(row=1, column=0)
    button_forward.grid(row=1, column=2)

def back(image_number):
    global my_label
    global button_forward
    global button_back

    my_label.grid_forget()
    my_label = Label(image=image_list[image_number-1])
    button_forward = Button(root, text=">>", command=lambda: forward(image_number+1))
    button_back = Button(root, text="<<", command=lambda: back(image_number-1))

    if image_number == 1:
        button_back = Button(root, text = "<<", state=DISABLED)

    my_label.grid(row=0,column=0,columnspan=3)
    button_back.grid(row=1, column=0)
    button_forward.grid(row=1, column=2)

button_back = Button(root, text="<<", command=back, state=DISABLED)
button_quit = Button(root, text="Quit", command=root.quit)
button_forward = Button(root, text=">>", command=lambda: forward(2))

button_back.grid(row=1, column=0)
button_quit.grid(row=1, column=1)
button_forward.grid(row=1, column=2)

root.mainloop()
```


texts: Extracting sleep quality scores from periodic readings

texts:
How can I optimize the next function to work faster? The function must prepare a list to put in a CSV file. The list must contain values of average percentage of sleep per minute counted from scores - a list of the form [[stage, time]], where stage could be 'S', 'R' or 'W' and time is in '%d %H:%M:%S' format; it's something like this:

scores = [['S', '01 12:11:00'], ['S', '01 12:11:20'], ['W', '01 12:11:40'], ['S', '01 12:12:00'], ...]

The function also must group counted values by hour and day, so the output should be like this:

quantities = [[1, 12, 11, 0.66], [1, 12, 12, 0.33], [1, 12, 13, 1], ...]

from itertools import product
import datetime

def sleep_quantity(scores):
    global quantities
    quantities = []
    for day, hour, minute in product(range(1,4), range(24), range(60)):
        sleep = 0
        total = 0
        quantity = []
        for line in scores:
            time = datetime.datetime.strptime(line[1], '%d %H:%M:%S')
            stage = line[0]
            if time.hour == hour and time.day == day and time.minute == minute:
                total += 1
                if stage == 'S' or stage == 'R':
                    sleep += 1
        if total != 0:
            sleep_per_minute = sleep / total
            quantity.append(hour)
            quantity.append(day)
            quantity.append(minute)
            quantity.append(sleep_per_minute)
            quantities.append(quantity) #for export to CSV
    return quantities


texts:
First ever code review post, so I hope I'm doing it right. My understanding of this site is that it is a place to post stuff like this for feedback and criticism. If that isn't the case, I apologise for my misunderstanding.

I'm teaching myself Python 3 and I'm pretty near the start. I couldn't find a simple description of a file parser, so I spent a frankly embarrassing amount of time trying to craft one, and this is the result:

def parse(file, startTag, endTag):
    bears=[]
    bearFile = open(file, 'r')
    for bearLine in bearFile:
        if startTag in bearLine:
            bear = bearFile.readline()
            while not (endTag in bear):
                bears.append(bear.strip())
                bear = bearFile.readline()
    return bears

I tested it using:

print(parse("bears.txt", "==start==", "==end=="))

...on a file which looked like this:

This file contains a list of bears.

Bears are below, between the start and end tags.

==start==
Grizzly
Polar
Koala
Panda
Spectacled
Sun
==end==

These are some more tags, listing some false bears:

==start==
Purple
Hairless
Aquatic
Flying
==end==

...and it works! The output is:

['Grizzly', 'Polar', 'Koala', 'Panda', 'Spectacled', 'Sun', 'Purple', 'Hairless', 'Aquatic', 'Flying']

With some obvious flaws, including:

1 - I can't work out how to ignore empty lines between the tags without using another if. I wondered if it might be better to do this later, and strip out all the '' entries, perhaps as an argument option.

2 - It depends on new lines because of the readline method, so using something else like a comma as a delimiter is currently beyond me.

3 - If there is no end tag, it loops forever. try and except are quite new to me right now.

I hope I'm not just wasting everyone's time by being here...


texts: "Log in", extract number from a map, increment it, and log out

texts:
Basically, you just run main and it allows the client to "log in", and extract their number from a map, increment their own number, and log out.

It all compiles and works fine, but how can I decouple this code, and make it more composable?  I'm finding it's difficult to separate concerns, ex between the logic, and the IO + State effects.

What would be a better, more idiomatic way to right this, which would allow me to add features, such as a password, or decrement option?

Possible Actions: login <ENTER> name, inc, get, logout

{-# LANGUAGE FlexibleContexts #-}

import System.IO
import Data.Map
import Control.Monad.State

import Control.Lens.Tuple
import Control.Lens.Setter
import Control.Lens.Getter

import Prelude hiding (lookup) -- Data.Map has one I want

-- Features:
--   User can login, see their number, increment it ad lib, and log out
--
--   login
--     new username --> new map entry
--     old username --> display map entry
--   inc - increment current user's entry in map
--   logout - empties the current username
--   stop - close IO
--   bad input - just ask for another action

type DB       = Map String Int
type Username = String
type AppState = (Username, DB)

db = fromList [("a", 0),
               ("b", 99),
               ("c", 152)] :: DB

-- increment a key in a map
incDB ::  String -> DB -> DB
incDB k = (update (\x -> Just (x + 1)) k)
-- λ> inc "a" $ inc "a" $ inc "a" db

-- increment current user in a State Monad
--  (Num a, Ord k, MonadState (k, (Map k a)) m) => m x
incUser :: (MonadState AppState m) => m ()
incUser = do user <- gets $ view _1
             modify $ over _2 (incDB user)
-- λ> runState incUser ("b", db)

-- 1. update logged-in user name, 2. add new entry to db if it's a new user
login :: (MonadState AppState m) => String -> m ()
login newuser = do modify $ set _1 newuser
                   modify $ over _2 $ insertWithKey (\k new old -> old) newuser 0 -- inserts new user if necessary
-- λ> runState (login "d") ("", db)
--    ((),("d",fromList [("a",0),("b",99),("c",152),("d",0)]))

-- get the number of the currently-logged-in user
getNum ::(MonadState AppState m) => m (Maybe Int)
getNum = do user <- gets $ view _1
            db <- gets $ view _2
            return $ lookup user db
-- λ> runState (do login "b"; incState; getNum) ("", db)
--    (Just 100,("b",fromList [("a",0),("b",100),("c",152)]))

-- remove the currently logged-in user from the appstate (not the db though, of course)
logout :: (MonadState AppState m) => m ()
logout = modify $ set _1 ""
-- λ> runState (do login "b"; getNum; logout ) ("", db)
--    ((),("",fromList [("a",0),("b",99),("c",152)]))
-- λ> runState (do login "b"; incUser; incUser; logout ) ("", db)
--    ((),("",fromList [("a",0),("b",101),("c",152)]))

run :: StateT AppState IO ()
run = do liftIO $ putStr "next action: "
         liftIO $ hFlush stdout
         action <- liftIO $ getLine
         case action of
           "inc"    -> do incUser
           "login"  -> do liftIO $ putStr "enter username:"
                          user <- liftIO $ getLine
                          login user
           "get"    -> do n <- getNum
                          liftIO $ putStr $ "current num: " ++ (show n) ++ "\n"
                          -- liftIO $ hFlush stdout

           "logout" -> logout
           otherwise -> return ()
         if action == "stop"
         then
             return ()
         else
             run

main = do execStateT run ("", db)


texts:
How do you list your referenced solution assemblies for IoC registration? I was really tired of typing something strange as new [] { typeof(SomeType).Assembly, … }. What do you think about the following approach?

Use case:

class Program
{
    static void Main(string[] args)
    {
        foreach (var a in Solution.Assemblies)
            Console.WriteLine(a);
    }
}

Where Solution.Assemblies is:

public static class Solution
{
    static IEnumerable<string> AssemblyNames => new[] {
        "ValueCache", "ValueCache.Tests", "LazyProxies", "ConsoleApplication1", "ClassLibrary1"
    };

    public static IEnumerable<Assembly> Assemblies => AssemblyNames
        .Select(an => Load(an))
        .Where(a => a != null);

    [DebuggerHidden]
    static Assembly Load(string assemblyName)
    {
        try
        {
            return Assembly.Load(new AssemblyName(assemblyName));
        }
        catch
        {
            return null;
        }
    }
}

… being generated by Solution.tt file:

<#@ template debug="false" hostSpecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDte" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Diagnostics;

namespace SolutionConfiguration
{
    public static class Solution
    {
        static IEnumerable<string> AssemblyNames => new[] {
            <#= String.Join(", ", from name in new SolutionAssemblyNames(Host)
                                  select $"\"{name}\"") #>
        };

        public static IEnumerable<Assembly> Assemblies => AssemblyNames
            .Select(an => Load(an))
            .Where(a => a != null);

        [DebuggerHidden]
        static Assembly Load(string assemblyName)
        {
            try
            {
                return Assembly.Load(new AssemblyName(assemblyName));
            }
            catch
            {
                return null;
            }
        }
    }
}

<#+

    class SolutionAssemblyNames : IEnumerable<string>
    {
        public SolutionAssemblyNames(ITextTemplatingEngineHost host)
        {
            Host = host;
        }

        public IEnumerator<string> GetEnumerator() => Assemblies.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        IEnumerable<string> Assemblies => Projects
            .Select(p => p?.Properties?.Item("AssemblyName")?.Value as string)
            .Distinct().Where(a => !string.IsNullOrWhiteSpace(a));

        IEnumerable<Project> Projects => VisualStudio.Solution.Projects.OfType<Project>();
        DTE VisualStudio => (Host as IServiceProvider).GetService(typeof(DTE)) as DTE;
        ITextTemplatingEngineHost Host { get; }
    }
#>


texts:
I wrote some code for a course:

  Create a program that takes two numbers from the user then find out if the first is divisible by the second. If not divisible, let the user know what the remainder is.

Here is what I currently have. Is this right? If so, how could I improve it?

puts "Enter number one"
num1 = gets.chomp.to_i

puts "Enter number two"
num2 = gets.chomp.to_i

if num1 % num2 != 0
    p num1 % num2
else p "The numbers are divislbe."
end


texts:
Euler problems (projecteuler.net) often invites to quick and dirty solutions.

While hurrying through Problem 32 I found myself in want of the std:: toolkit. Not sure what it is though.

The problem description is included in the first comment.

I would really appreciate any suggestions as for the usage of the tools provided by standard c++ (11 if need be, lambdas might make it more succinct/elegant).

/*
 * File:   main.cpp
 * Author: cpt_giraffe
 *
 *

 * We shall say that an n-digit number is pandigital if it makes use of all the
 * digits 1 to n exactly once; for example,
 * the 5-digit number, 15234, is 1 through 5 pandigital.

 * The product 7254 is unusual, as the identity, 39 × 186 = 7254,
 * containing multiplicand, multiplier, and product is 1 through 9 pandigital.

 * Find the sum of all products whose multiplicand/multiplier/product
 * identity can be written as a 1 through 9 pandigital.

 * HINT: Some products can be obtained in more than one way
 * so be sure to only include it once in your sum.

 * Created on November 27, 2013, 9:41 PM
 */

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <numeric>
#include <sstream>

using namespace std;

// store the products, a set is ideal because of the HINT:
set<unsigned> products;

/**
 * Insert to products if string arguments is a proper product
 */
void insert_if_product(string factor1, string factor2, string product) {
    stringstream values(factor1 + " " + factor2 + " " + product);

    // is this a valid product.  (Most cases says no)
    unsigned f1, f2, p;
    values >> f1 >> f2 >> p;
    if (f1 * f2 == p) {
        products.insert(p);
    }

}

/**
 * magnitudes needs to add up: I'm checking
 * 9 digits total
 * m1 * m3 = m5
 * m1 * m4 = m4
 * m2 * m3 = m4
 * Is this all?
 *
 * @param check this permutation
 */
void check_products(string perm) {
    // all permutations are coming from perm, so no need to perm stuff here.
    string factor1 = perm.substr(0, 1);
    string factor2 = perm.substr(1, 3);
    string product = perm.substr(4, 5);

    insert_if_product(factor1, factor2, product);

    factor1 = perm.substr(0, 1);
    factor2 = perm.substr(1, 4);
    product = perm.substr(5, 4);

    insert_if_product(factor1, factor2, product);

    factor1 = perm.substr(0, 2);
    factor2 = perm.substr(2, 3);
    product = perm.substr(5, 4);

    insert_if_product(factor1, factor2, product);

}

int main(int argc, char** argv) {
    string s = "123456789";
    do {
        check_products(s);

    } while (next_permutation(s.begin(), s.end()));

    // Test case
    if (products.find(7254) != products.end()) {
        cout << "found 7254" << endl;
    } else {
        cout << "did not find 7254" << endl;
    }
    unsigned sum = 0;

    sum = accumulate(products.begin(), products.end(), 0);
    cout << "Sum:" << sum << endl;
    return 0;
}


texts:
This function tells that elements of content either (maybe) match regexes that you like or match regexes that you don't like.

This messy code requires Data.Text.Lazy but internally shuffles around internal and strict versions. Also list Monad code looks fishy to me.

How can it be made simpler, faster, more general (especially work with any Text and String)?

{-# LANGUAGE OverloadedStrings #-}

module Search (analyze) where

import qualified Data.Text.Lazy as T
import Data.Maybe()
import Text.Regex.TDFA
import Text.Regex.Base.Context()
import Text.Regex.Base.RegexLike()
import Text.Regex.TDFA.Text
import Data.Function (on)
import Data.Maybe (maybeToList)

matches :: [T.Text] -> T.Text -> [T.Text]
matches patterns content = map (T.fromStrict) $ concat $ do
  pattern <- patterns
  return $ maybeToList $ (on (=~~) T.toStrict) content pattern

analyze :: [T.Text] -> [T.Text] -> T.Text -> Either [T.Text] [T.Text]
analyze likes dislikes text =
    case matches likes text of
      liked@(_:_) ->
        case matches dislikes text of
             [] -> Right liked
             disliked@(_:_) -> Left disliked
      _ -> Left []


texts: Project Euler Question #2: Sum of even Fibonacci numbers under 4 million

texts:
The question is:

  Each new term in the Fibonacci sequence is generated by adding the previous two terms.
    By starting with 1 and 2, the first 10 terms will be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not exceed four
   million, find the sum of the even-valued terms.

#Problem 2
P2 = 0
fib= 0
f1 = 1
f2 = 0
debugP2 = []
while fib < 4000000:
    fib = f1 + f2
    f2 = f1
    f1 = fib
    if fib % 2 == 0:
        P2 += fib
        debugP2.append(fib)
print(debugP2)
print(P2)

This script can

Give me all Fibonacci numbers up to 4000000
Give the sum of all even numbers up to 4000000
It satisfies Project Euler Question #2.

Is there a way to make this shorter or more efficient?


texts: String find and replace method optimization

texts:
I am trying to find a specific header string from different Maps (LEDES1998Bheaders, LEDES98BIheaders and LEDES98BI_V2headers) in an errorMessage depends on the parcel type and if the errorMessage has the specific header string I need to replace it with the corresponding value.

public class ErrorMessageConverter {

    private static Map<String, String> LEDES1998Bheaders = new HashMap<>();
    private static Map<String, String> LEDES98BIheaders = new HashMap<>();
    private static Map<String, String> LEDES98BI_V2headers = new HashMap<>();

    static {
                LEDES1998Bheaders.put("(\\binv_date\\b|\\bINVOICE DATE\\b)", "INVOICE DATE");
    LEDES1998Bheaders.put("\\binv_id\\b", "INVOICE NUMBER");
    LEDES1998Bheaders.put("\\bcl_id\\b", "CLIENT ID");
    LEDES1998Bheaders.put("\\blf_matter_id\\b", "LAW FIRM MATTER ID");
    LEDES1998Bheaders.put("\\bUNITS\\b", "LINE ITEM NUMBER OF UNITS");
    LEDES1998Bheaders.put("(\\bBaseRate\\b|\\bRate\\b|\\btk_rate\\b)", "LINE ITEM UNIT COST");

    LEDES98BIheaders.put("\\blf_address/address_info/address_1\\b", "LAW FIRM ADDRESS 1");
    LEDES98BIheaders.put("\\blf_address/address_info/city\\b", "LAW FIRM CITY");
    LEDES98BIheaders.put("\\btax_rate\\b", "LINE ITEM TAX RATE");
    LEDES98BIheaders.put("\\btax_on_charge\\b", "LINE ITEM TAX TOTAL");
    LEDES98BIheaders.put("\\btax_type\\b", "LINE ITEM TAX TYPE");

    LEDES98BI_V2headers.put("\\binv_reported_tax_total\\b", "INVOICE REPORTED TAX TOTAL");
    LEDES98BI_V2headers.put("\\binv_reported_tax_currency\\b", "INVOICE TAX CURRENCY");

    }

    public static String toUserFriendlyErrorMessage(String parcelType, String message) {

        if (parcelType.equals("LEDES1998B")) {
            return updateErrorMessage(message, LEDES1998Bheaders);
        }
       else if (parcelType.equals("LEDES98BI")) {
            message = updateErrorMessage(message, LEDES1998Bheaders);
            return updateErrorMessage(message, LEDES98BIheaders);
        }
       else if (parcelType.equals("LEDES98BI V2")) {
            message = updateErrorMessage(message, LEDES1998Bheaders);
            message = updateErrorMessage(message, LEDES98BIheaders);
            return updateErrorMessage(message, LEDES98BI_V2headers);
        }
        return message;

    }

    private static String updateErrorMessage(String msg, Map<String, String> invHeaders) {
        Pattern pattern;
    for (String key : invHeaders.keySet()) {
        pattern = Pattern.compile(key);
        if (pattern.matcher(msg).find()) {
            msg = msg.replaceAll(key, invHeaders.get(key));
        }
    }
    return msg;
    }
}

Below are couple of sample error messages:

String errorMesage1 = "Line 3 : Could not parse inv_date value"
String errorMesage2 = "Line : 1 BaseRate is a required field"

Can this method simplified further in java 8 using filters/lambda expressions?


texts:
I'm trying to construct something which would work a bit like Zip for two tasks, but I'm a bit worried about race conditions in this code.

public static Task<R> ContinueWhenBoth<T1, T2, R>(this TaskFactory<R> factory, Task<T1> t1,
                                                 Task<T2> t2, Func<T1, T2, R> f)
{
    var result = new TaskCompletionSource<R>();

    t1.ContinueWith(t => { if(t2.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });
    t2.ContinueWith(t => { if(t1.IsCompleted) result.TrySetResult(f(t1.Result, t2.Result)); });

    return result.Task;
}

Is this a good way to go?

public static Task<R> ContinueWhenBoth<T1, T2, R>(this TaskFactory<R> factory, Task<T1> t1,
                                                 Task<T2> t2, Func<T1, T2, R> f)
{
    var result = new TaskCompletionSource<R>();

    int tasksLeft = 2;
    t1.ContinueWith(t =>
                    {
                    if(Interlocked.Decrement(ref tasksLeft) == 0 && t2.IsCompleted)
                        result.TrySetResult(f(t1.Result, t2.Result));
                    });
    t2.ContinueWith(t =>
                    {
                    if(Interlocked.Decrement(ref tasksLeft) == 0 && t1.IsCompleted)
                        result.TrySetResult(f(t1.Result, t2.Result));
                    });

    return result.Task;
}


texts: Method that concatenates strings, some of which may be null, with several different separators

texts:
I'd like to refactor a Java method I've created, making it cleaner and more beautiful. The method concatenates some strings, which may be empty or not. I'm new on java so i'm not sure how to do that, especially because between the strings I may have separators.

Here is my method:

private String createString(String modeloVotacao, String tipoProposicao, String ordemNumero, String ordemAno) {

    String modeloDescricao = "";
    if(modeloVotacao != null) {
        modeloDescricao = modeloVotacao + " - ";
    }

    if(tipoProposicao != null) {
        modeloDescricao += tipoProposicao + " ";
    }
    modeloDescricao += ordemNumero != null?ordemNumero:"";

    if(ordemNumero != null && ordemAno != null) {
        modeloDescricao += "/"+ordemAno;
    } else {
        if(ordemAno != null) {
            modeloDescricao += ordemAno;
        }
    }

    return modeloDescricao;
}

Here is some results that this method returns:

All filled: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR Nº 16/2018
modeloVotacao = null: PROJETO DE LEI COMPLEMENTAR Nº 16/2018
tipoProposicao = null: 1ª DISCUSSÃO - Nº 16/2018
ordemNumero = null: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR 2018
ordemAno = null: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR Nº 16
all null: empty string
modeloVotacao  and tipoProposicao  = null: Nº 16/2018
ordemNumero and ordemAno  = null: 1ª DISCUSSÃO - PROJETO DE LEI COMPLEMENTAR


texts: Accept either a existing stream or a filename (to be opened) in a constructor

texts:
Context:

In a larger project, I am trying to build an utility class to encapsulate the parsing of input data. And I want it to be able to process either an already existing input stream, or a file given by its name.

The general idea is to build a stream converter. The input file contains a variable number of (possibly multi-line records). The program parses the file, retrieves one item, convert it and write it to the output file. So the structure of the program (pseudo code here) is:

Parser parser(input_stream);
Writer writer(output_stream);

while (StopRecord != (record = parser.getRecord())) {
    writer.write(record);
}

My first idea was to have a ref to a std::istream as a class member, and initialize it in constructor, either from an existing ref or to a newly opened file

class Parser {
    std::istream &in;
public:
    Parser(std::istream& in): in(in) {}   // fine
    Parser(std::string file): in(std::ifstream(file)) {}   // compile error

    Record getRecord();
};

The problem is that std::ifstream(file) is a temporary, and can only initialize a const lvalue reference or a rvalue reference. A const istream would be pretty useless, so I tried a rvalue ref.

class Parser {
    std::istream &&in;
public:
    Parser(std::istream& in): in(in) {}   // compile error
    Parser(std::string file): in(std::ifstream(file)) {}   // fine

    Record getRecord();
};

But now a std::istream& cannot be used to initialize a std::istream&&, and I would not dare to use Parser(std::istream&& in): in(in) {} and later p = Parser(std::cin); with a move from a standard stream!

Current code:

I finally decided to dynamically allocate a std::ifstream in my class when I have to process a file to have an lvalue to initialize my ref:

class Parser {
    std::ifstream *fin;
    std::istream& in;   // MUST be after fin declaration!
public:
    Parser(std::istream& in): fin(nullptr), in(in) {}
    Parser(std::string file): fin(new std::ifstream(file)), in(*fin) {}
    ~Parser() {
        if (fin) {
            fin.close();
            delete fin;
        }
    }

    Record getRecord();
};

It seems to work (even if in case of copies all will share the same underlying stream), but requires fin to be declared before in, and the raw pointer initialization looks rather ugly.

Question:

As this design come from my former C experience, I wonder whether this follows modern C++ best practices and how I could make it better, more robust and easier to maintain


texts: Optimal code without using for, while and if

texts:
I presented a code solution to a startup as part of their interview polity.

The problem statement is to find the frequency of words occurring in a sentence.  I got the code rejected saying, "Evaluating code is always subjective, but people generally leave a "fingerprint" with their design approach and the nature of their code (comments, tests, multiple solution paths, validation). The hiring manager has a high bar, and has rejected many working solutions because he didn't like the approach or the number of trees used or linear scaling vs. ^2 scaling."

I have pasted my solution.  The hiring manager specified not to use collection API.  I would like some opinions as to how I would have improved the code.

import java.io.*;
import java.util.*;

class FreqWord {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new
        InputStreamReader(System. in ));
        String str[] = new String[30];
        StringTokenizer st;
        int i = 0, j, k, ctr, size = 0;
        System.out.println(" Enter the String :");
        String str1 = br.readLine();
        st = new StringTokenizer(str1, " \n");
        while (st.hasMoreTokens()) {
            str[i] = st.nextToken();
            size++;
            i++;
        }
        System.out.println("\n-------------");
        System.out.println("\nWord" + "\t" + "freq");
        System.out.println("\n-------------");
        for (i = 0; i < size; i++) {
            ctr = 0;
            for (j = i; j < size; j++) {
                if (str[j].equals(str[i])) ctr++;
            }
            for (k = i - 1; k >= 0; k--) {
                if (str[k].equals(str[i])) {
                    ctr = 0;
                    break;
                }
            }
            if (ctr != 0) {
                System.out.println(str[i] + "\t" + ctr);
            }
        }
        System.out.println("\n------------");
    }
}


texts: Using Linq syntax, how can I remove the select n+1 issue in this method?

texts:
I have the following code in a validation module. It works the way I want it to, but it has an obvious select n+1 problem. I would like to refactor this code to make a single call to the db to perform this validation.

Is there a way I can do it using linq or do I need to perform more major surgery? I am trying to avoid sprocs at this point, but am willing to listen to arguments for it.

private void EnsureIdentifiersAreNotInUse(AddOrEditClientCommand request)
        {
            var identifiers = request.Editor.Identifiers;

            for (var i = 0; i < identifiers.Count; i++)
            {
                var identifier = identifiers[i];
                var exists = dbContext.ClientIdentifers
                    .Any(x => x.Client.Id != request.Editor.ClientId
                        && x.ClientIdentifierType.Id == identifier.TypeId
                        && x.Value.Equals(identifier.Value, StringComparison.InvariantCultureIgnoreCase));
                if(exists)
                    request.ModelState.AddModelError("Identifiers[{0}].Value".FormatWith(i), "System Id ({0}) is already in use".FormatWith(identifier.Value));
            }
        }


texts: Take a desired string, iterate through objects to see if it exists in a given field and append a number until a unique string is found

texts:
I wanted to in the most generic way possible write a method in C# to achieve the following.

Take in a string, a set of objects, and a function to access the field of a given object
Look at all of the strings from the fields of these objects to match against provided string
If provided string is not unique in a case insensitive manner, append _x to the end, where x is an incrementing integer until a unique string is found

With that in mind, I created this.

private string GetUniqueStringForModel<T>(string originalString, IEnumerable<T> enumerableObjects, Func<T, string> stringFieldFunction) where T : class
{
    var uniqueString = originalString;
    var duplicateCount = 1;

    while (enumerableObjects.Select(stringFieldFunction).ToList().Any(currentString => string.Equals(currentString, uniqueString, StringComparison.InvariantCultureIgnoreCase)))
    {
        uniqueString = originalString + "_" + duplicateCount++;
    }

    return uniqueString;
}

I would rather have not put the ToList() in but when working with Entity Framework it was complaining about doing the string comparison in LINQ (presumably because it couldn't compile it SQL).

Any thoughts or ideas for improvement?


texts:
The index file:

<?php
require_once 'app/run.php';

$_action = (isset($_GET['cmd']) && ctype_alnum($_GET['cmd'])) ? $_GET['cmd'] : 'index';

switch ($_action) {

    case 'index':
    case 'default':
    case 'home':
        include $con_dir . '/index.php';
    break;
    default:
        include $con_dir . '/404.php';

}

The run.php file:

<?php
session_start();

require_once 'config.php';

$app_dir = realpath(dirname(__FILE__));
$lib_dir = $app_dir . '/lib';
$con_dir = $app_dir . '/controllers';

require_once($app_dir . '/lib.php'); //Include libraries

//Database Connection
try {
  # MySQL with PDO_MYSQL
  $db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
}
catch(PDOException $e) {
    echo $e->getMessage();
}
unset($password);

//Smarty
$tpl = new Smarty();
$tpl->template_dir = $app_dir . '/Smarty/templates/';
$tpl->compile_dir  = $app_dir . '/Smarty/templates_c/';
$tpl->config_dir   = $app_dir . '/Smarty/configs/';
$tpl->cache_dir    = $app_dir . '/Smarty/cache/';

The lib.php file

<?php
require_once($lib_dir . '/Smarty/Smarty.class.php');

The config.php file

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'engine';

I think I can improve  this by doing the switch() more dynamic, let's say it, would it be possible to have that the ?cmd=filename would be appropriate, how would I do it? And how do I do it secure?

Else way what do you think about my basic structure, how should improve it? What would you change etc.


texts: Add two signed integers, given in stdin(space separated) in i386 ASM Linux ABI

texts:
.global _start
_start:
    mov $0x1000,%edx
    mov %edx,%eax
    neg %eax
    and %eax,%esp
    mov %esp,%ecx
    xor %ebx,%ebx
    mov $3,%eax
    int $0x80
    add %edx,%esp
    mov %ecx,%edi
    mov $label00,%ebp
    jmp parse_eax_load_constants
label00:
    push %eax
    inc %edi
    mov $label01,%ebp
    jmp parse_eax
label01:
    mov %edi,%ebp
    mov %esi,(%edi)
    dec %edi
    pop %edx
    add %edx,%eax # finally
print_eax: # %edi: where to print %eax
    xor %edx,%edx
    div %esi
    or %cl,%dl
    mov %dl,(%edi)
    dec %edi
    test %eax,%eax
    jnz print_eax

    mov %ebp,%edx
    sub %edi,%edx
    inc %edi
    mov %edi,%ecx
    xor %ebx,%ebx
    inc %ebx
    mov $4,%eax
    int $0x80
    mov %ebx,%eax
    int $0x80

parse_eax_load_constants:
    mov $10,%esi
    mov $0x30,%ecx
parse_eax: # %edi: the string to parse
    xor %eax,%eax
    movb (%edi),%al
    mov %edi,%ebx
    inc %ebx
    cmpb $0x2d,%al
    cmovz %ebx,%edi
    setz %bl
    push %ebx
    mov (%edi),%al
    xor %ebx,%ebx
    xor %cl,%al
parse_eax_loop:
    inc %edi
    movb (%edi),%bl
    xor %cl,%bl
    cmp %esi,%ebx
    jae parse_eax_end
    mul %esi
    add %ebx,%eax
    jmp parse_eax_loop
parse_eax_end:
    pop %ebx
    mov %eax,%edx
    neg %edx
    test %bl,%bl
    cmovnz %edx,%eax
    jmp *%ebp


texts: Optimizing a script that switches function arguments in code files

texts:
I made a quick script, that inputs file paths(made for C files), function names and 2 indexes. The script goes over all of the files and switches the indexes of the 2 functions. e.g.:
Running the following code:
python switch_args.py temp_funct 0 1 tmp.c

If tmp.c contains this code:
int my_func(a, b, c, d)

after the execution of the script it would have this code:
int my_func(b, a, c, d)

Code:
https://github.com/martin-varbanov96/toolboxz/blob/master/switch_function_args/switch_args.py:
import argparse
import re

parser = argparse.ArgumentParser()
parser.add_argument("function_name", type=str,
                    help="function name whose arguments will be switched")
parser.add_argument("index", type=int,
                    help="first argument to be switched")
parser.add_argument("destination", type=int,
                    help="second argument to be switched")
parser.add_argument('files', metavar='files', type=str, nargs='+',
                    help='files in which function arguments will be switched')

args = parser.parse_args()
def switch_function_args(func_name, args, index=0, destination=1, ):
    function_call_pattern = "{}[^\)]+".format(func_name)
    for file in args:
        has_function = False
        file_content = ""
        with open(file, "r") as f:
            file_content = f.read()
            if(func_name in file_content):
                has_function = True
        if(has_function):
            for current_function_structure in re.findall(function_call_pattern, file_content):
                current_arguments = re.split("\(", current_function_structure)[1]
                current_arguments = re.split(",", current_arguments)

                # switch arguments
                current_arguments[index], current_arguments[destination] = current_arguments[destination], current_arguments[index]
                fixed_arguments = ",".join(current_arguments)
                fixed_function_structure = "{}({}".format(func_name, fixed_arguments)
                old_struct_pattern = current_function_structure.replace("(", "\(")
                file_content = re.sub(old_struct_pattern, fixed_function_structure, file_content)
            with open(file, "w") as f:
                f.write(file_content)

switch_function_args(args.function_name, args.files, index=args.index, destination=args.destination)

Question:
How can this code be optimized for performance?
EDIT:
what is the consistency of the following code and is it a good idea to ignore it?
with open(file, "r") as f_read:
    # code
    with open(file, "w") as f_write:
        # code


texts:
Due to software constraints, I cannot use the standard libraries, math.h, algorithm, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.

I need to duplicate the Matlab any function in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size.

Is it possible to write just one any function without using templates?
How can I improve performance?

I am striving for const correctness, performance/efficiency, and avoiding implicit type casting.

bool any(bool* array, const int N){
    // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
    bool val;
    val = array[0] == true;
    int i = 0;
    while (val == false && i < N){
        val = array[i++] == true;
    }
    return val;
}

bool any(bool** array, const int nRow, const int nCol){
    // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
    bool val;
    val = array[0][0] == true;
    int i = 0;
    while (i < nRow && val == false){
        int j = 0;
        while (j < nCol && val == false){
            val = array[i][j++] == true;
        }
        i++;
    }
    return val;
}


texts:
I wrote a simple neural network simulator (the biophysical kind) from scratch, and was hoping to get some feedback on how I can speed things up, or any C++ / compilation best practices that I can improve on.

The code is at this repository.

Main Problem:

OpenMP doesn't seem to be conferring speedup.

The performance-critical section of the code is in src/networks/spikingnet.cpp, but for additional context, see the rest of the code in the repository.

#pragma omp parallel for
for (size_t li=0; li < nL; ++li) {
    SpikingLayer *layer = net->layers[li];
    Stim *stim = rs->stimuli[li];
    boolvec doSpike = stim->yield();
    conn_vec pre_arr = net->pre[li];
    updateLayer(layer, pre_arr, doSpike, t);
    recordSpikes(results.mutable_spikes(li), layer, i);
}

// update transmission & stdp
#pragma omp parallel for
for (size_t li=0; li < nL; ++li) {
    SpikingLayer *layer = net->layers[li];

    // transmission
    for (SpikingConnection *conn : net->post[li]) {
        for (SpikingSynapse* syn : conn->synapses) {
            updateTransmission(syn, layer->units[syn->s]);
        }
    }

    // STDP
    for (SpikingConnection *conn : net->pre[li]) {
        SpikingLayer *source = net->layers[conn->s];
        SpikingLayer *target = net->layers[conn->t];
        if (conn->stdp_enabled) {
            #pragma omp parallel for
            for (SpikingSynapse* syn : conn->synapses) {
                updateSTDP(syn, source->units[syn->s], target->units[syn->t]);
            }
        }
    } // end STDP

} // end for

GProf Trace

Architectural details:

The network consists of L=9 "layers", each with 100-900 units. There are on the order of L^2 "connections" (bundles of synapses between layers), and 2000 synapses per "connection" (synapses are sparse).

During each update cycle, all the layers (neurons) are updated (conditioned on connections), and then all the connections (synapses) are updated (conditioned on layers). That is to say, layer updating is independent conditioned on connections, and connection updating is independent conditioned on layers.

Given that there are so many neurons and synapses, the program naturally spends most of its time updating layers and synapses (line 133). I thought that using OpenMP over the per-layer loop, or even per-neuron/synapse, would really speed things up, but that does not seem to be the case at all.

If it's of any interest to the reader, my machine has a 4.0Ghz CPU with 8 cores. 12K steps run in approximately 30 seconds on either single-threaded or OpenMP-enabled builds.

I'm aware that I should be using smart pointers, but memory management is fairly straightforward in this simple simulator, so I chose to live dangerously.

General C++ programming style tips / pointing out my bad practices are also welcome!


texts: Hash password and verify password with Node's Crypto

texts:
I would like to make a safe way to store hashes of user passwords and verify them later. Here is crypt.js:

'use strict'

const crypto = require('crypto')

module.exports = {

    keyLength: 512,
    hashAlg: 'sha512',
    rounds: 10000,

    randHex(length) {
        return crypto.randomBytes(length / 2).toString('hex')
    },

    hashPassword(plainText) {
        let salt = this.randHex(64)
        let pbkdf2 = crypto.pbkdf2Sync(
            plainText,
            salt,
            this.rounds,
            this.keyLength,
            this.hashAlg
        ).toString('hex')

        return `${this.hashAlg}:${this.keyLength}:${this.rounds}:${salt}:${pbkdf2}`
    },

    verifyPassword(givenPassword, hashedPassword) {
        let splits = hashedPassword.split(':')
        let hashAlg = splits[0]
        let keyLength = parseInt(splits[1])
        let rounds = parseInt(splits[2])
        let salt = splits[3]
        let pbkdf2 = splits[4]

        let testPbkdf2 = crypto.pbkdf2Sync(
            givenPassword,
            salt,
            rounds,
            keyLength,
            hashAlg
        ).toString('hex')

        return testPbkdf2 === pbkdf2
    }

}

I have some questions.

It seems that pbkdf2 might be the best that Node's Crypt offers. Is this true? If so, is there a good reason to avoid pbkdf2Sync and use pbkdf2 instead?
I am adding in a lot of info such as the salt, rounds, hashing algorithm, etc. so that I can change this stuff and still be able to verify passwords hashed the old way. The database will have someone's password as sha512:512:10000:d15...d5k:a6a...1b9e Is it okay to do this?
What other dangers are there with crypt.js?


texts: Median Calculation of List of Integers without using heap

texts:
References

Using those references:

rolling median implementations benchmark
FAST RUNNING MEDIAN USING AN INDEXABLE SKIPLIST
Calculate the median of a billion numbers
Find running median from a stream of integers

Code

A code was written to calculate the Median with the SortedContainers library:

from itertools import islice
from sortedcontainers import SortedList
import random
import time

start_time = time.time()

class Median(object):

    def __init__(self, iterable):
        self._iterable = islice(iterable, None)
        self._sortedlist = SortedList(self._iterable)

    def __iter__(self):
        self_sortedlist = self._sortedlist
        # print(self_sortedlist)
        length = len(self_sortedlist)
        half = length // 2
        if length % 2 == 0:
            yield (self_sortedlist[half] + self_sortedlist[half - 1]) // 2
        elif length % 2 == 1:
            yield self_sortedlist[half]

def main():
    m, n = 1000, 1500000
    data = [random.randrange(m) for i in range(n)]
    # print("Random Data: ", data)
    result = list(Median(data))
    print("Result: ", result)

if __name__ == "__main__":

    main()
    print("--- %s seconds ---" % (time.time() - start_time))

Explanation

Random Number Generator

The following code generates data within the Range m and quantity n.

m, n = 1000, 15000000
data = [random.randrange(m) for i in range(n)]

Median

The Median class sorts the list of numbers and if n is odd, returns the middle item with yield self_sortedlist[half]. Or if n is even, returns the mean of two middle itens of the list with yield (self_sortedlist[half] + self_sortedlist[half - 1]) // 2

Question

How do I improve the code performance? Because for a large list (100 milion), it takes --- 186.7168517112732 seconds--- on my computer.


texts:
I'm currently developping an MVC framework on which I will be writing my websites. This is done through the usage of a starter kit.

In standard MVC, your routes are registered like the following:

/// <summary>
///     Registers the routes.
/// </summary>
/// <param name="routes">The <see cref="RouteCollection" /> to which the routes will be added.</param>
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // All the required routes are placed here.
    routes.MapRoute("Website", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

But since it's a framework, there's a need to add routes to the collection, so I started with an interface:

public interface IMvcRouteExtender
{
    #region Methods

    /// <summary>
    ///     Register routes for the application.
    /// </summary>
    /// <param name="routes">The <see cref="RouteCollection"/> that contains all the required routes.</param>
    void RegisterRoutes(RouteCollection routes);

    #endregion
}

Now, in an implementation class, I can do the following:

public class CustomRouteConfiguration : IMvcRouteExtender
{
    #region IMvcRouteExtender

    /// <summary>
    ///     Registers the routes.
    /// </summary>
    /// <param name="routes">The <see cref="RouteCollection" /> to which the routes will be added.</param>
    public void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute("Default", "pensions/save-and-pension", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
    }

    #endregion
}

In order to be sure there available, the original routeconfig is changed so that it searches for those interfaces and register them.

/// <summary>
///     Registers the routes.
/// </summary>
/// <param name="routes">The <see cref="RouteCollection" /> to which the routes will be added.</param>
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Get all the types in the references assembly that implement the 'IMvcRouteExtender' interface.
    var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                .SelectMany(a => a.GetTypes())
                .Where(t => typeof(IMvcRouteExtender).IsAssignableFrom(t) && !t.IsInterface);

    // Register all the routes.
    types.Select(type => Activator.CreateInstance(type) as IMvcRouteExtender).Each(x => x.RegisterRoutes(routes));

    // All the required routes are placed here.
    routes.MapRoute("Website", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

As you'll see above, I'm using reflection to load the types in which the routes are defined. This is working fine, but I don't like the overhead of using reflection.

Is there anyone who has an idea on how to make this more efficient? AKA, remove the dynamic type loading?

Since I'm writing a framework I cannot have a reference between routeConfig and CustomRouteConfig.

Also: Don't look at code semantics here, I'm just talking about a general idea to make the code more performant.


texts: Improving performance of moving arrays into an array

texts:
I am loading a bunch of arrays and putting them into a single array.  The loading of the data is negligible, but putting it into combinedArray takes significant time (as in this code).

import time
import numpy as np
start_time = time.time()

   st,en = 0,0
   combinedArray = np.empty(shape = (30000*30000))
   #Get the array that each process wrote to
   for i in range(10):
       #load the array
       #ex loading
       X_np = np.empty(shape = (30000*30000)/10)
       st = en
       en += np.shape(X_np[:])[0]
       #add to the array list
       combinedArray[st:en] = X_np[:]

   print("Array Calc:",time.time()-start_time)

What I have found is often someone talking about not using append, so I tried with creating the array first, but just moving it is time consuming.  Any advice on how to optimize this is appreciated.


texts: Splitting uppercase letters based on a dictionary

texts:
A few days ago I learned about the dynamic programming approach to problem-solving; the thing is, I'm still not sure I am fully grasping the concept.

I decided to write an algorithm that takes a single String of uppercase letters, s, and split it into substrings based on a dictionary I have provided. My algorithm works as expected, although I'm not sure if i'm using the dynamic programming approach correctly. From what I understand, DP uses an array which holds solutions to the subproblems of a larger problem. This was my goal with the result array. Here is my simple program to demonstrate a solution to the problem:

import java.util.Scanner;

class WordBreak
{

    static String[] result;
    static String[] dictionary = {"I", "THE", "ABORT", "PLAN", "MEET", "CONFIRM", "AT",
                                  "DARK", "CABIN", "PROCEED", "MISSION", "MISS",
                                  "CHOCOLATE", "ALIENS", "CANNIBALS", "SAUCE"};

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String str = in.next();
        int size = str.length();
        result = new String[size];
        print(str, 0);
    }
    //method which recursively breaks input string into substrings
    //which are stored in an array and, if they are English words, then printed
    static void print(String str, int ind)
    {
        //each recursive call shortens the input string until length is 0
        int length = str.length();
        //if length is 0, then print the resulting substrings to decode
        //the message
        if(length == 0)
        {
            for(int i = 0; i < ind; i++)
            {
                System.out.print(result[i] + " ");
            }
            System.out.println();
            return;
        }
        //if a valid substring of the dictionary, add it to result array and recur
        for(int i = 1; i <= length; i++)
        {
            if(valid(str.substring(0, i)) == true)
            {
                result[ind] = str.substring(0, i);
                print(str.substring(i), ind + 1);
            }
        }
    }
    //valid function returns true iff string s is an English word (in the dictionary)
    static boolean valid(String s)
    {
        boolean result = false;

        for(int i = 0; i < dictionary.length; i++)
        {
            if(s.equals(dictionary[i]))
            {
                result = true;
                break;
            }
        }
        return result;
    }
}

Given the input string of "ABORTTHEPLANMEETATTHEDARKCABIN" the algorithm does accurately print out "ABORT THE PLAN MEET AT THE DARK CABIN".

My question is, is this a proper dynamic programming approach? If not, what potential changes could I make to implement DP? My main goal here is to make sure I am effectively grasping the concept.

Lastly (kind of off topic), what would the big O of this algorithm be? My analysis tells me either \$O(n^2)\$ or \$O(n^3)\$ depending on how you look at the substring(i, j) method call. This is for my own curiosity to see if I'm analyzing it correctly.


texts:
I have written code for generating all the permutations in C as explained here. How can the code be optimized? Are there any memory leaks?

int factorial(int n) {
    int fact = 1;
    for(int i = 2; i <= n; i++)
        fact *= i;
    return fact;
}

int main(){
    int len = 4, i, j;
    int **p;
    int **q = (int**) malloc(sizeof(int*));
    q[0] = (int*) malloc(sizeof(int));
    q[0][0] = 1;
    for(i = 0; i < len; i++){
        p = (int**) malloc(sizeof(int*) * factorial(i + 1));
        for(j = 0; j < factorial(i + 1); j++)
            p[j] = (int*) malloc(sizeof(int) * (i + 1));
        int y=0;
        for(j = 0; j < factorial(i); j++){
            for(int k = 0; k < i + 1; k++){
                int added = 0;
                for(int l = 0; l < i + 1; l++){
                    if(k == l){
                        p[y][l] = i + 1;
                        added = 1;
                    }
                    else
                        p[y][l] = q[j][l-added];
                }
                y++;
            }
        }
        for(j = 0; j < factorial(i); j++)
            free(q[j]);
        free(q);
        q = p;
    }
    for(i = 0; i < factorial(len); i++){
        for(j = 0; j < len; j++)
            printf("%d\t", p[i][j]);
        printf("\n");
        free(p[i]);
    }
    free(p);
}


texts: An iterator returning all possible permutations of a list in Java

texts:
I have this class that iterates over all permutations of an input list:

PermutationIterable.java:

package net.coderodde.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * This class implements an {@code Iterable} returning all possible permutations
 * of a list.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Feb 14, 2016) :*
 */
public class PermutationIterable<T> implements Iterable<List<T>> {

    final List<T> allElements = new ArrayList<>();

    public PermutationIterable(List<T> allElements) {
        this.allElements.addAll(allElements);
    }

    @Override
    public Iterator<List<T>> iterator() {
        return new PermutationIterator<>(allElements);
    }

    private static final class PermutationIterator<T>
    implements Iterator<List<T>> {

        private List<T> nextPermutation;
        private final List<T> allElements = new ArrayList<>();
        private int[] indices;

        PermutationIterator(List<T> allElements) {
            if (allElements.isEmpty()) {
                nextPermutation = null;
                return;
            }

            this.allElements.addAll(allElements);
            this.indices = new int[allElements.size()];

            for (int i = 0; i < indices.length; ++i) {
                indices[i] = i;
            }

            nextPermutation = new ArrayList<>(this.allElements);
        }

        @Override
        public boolean hasNext() {
            return nextPermutation != null;
        }

        @Override
        public List<T> next() {
            if (nextPermutation == null) {
                throw new NoSuchElementException("No permutations left.");
            }

            List<T> ret = nextPermutation;
            generateNextPermutation();
            return ret;
        }

        private void generateNextPermutation() {
            int i = indices.length - 2;

            while (i >= 0 && indices[i] > indices[i + 1]) {
                --i;
            }

            if (i == -1) {
                // No more new permutations.
                nextPermutation = null;
                return;
            }

            int j = i + 1;
            int min = indices[j];
            int minIndex = j;

            while (j < indices.length) {
                if (indices[i] < indices[j] && indices[j] < min) {
                    min = indices[j];
                    minIndex = j;
                }

                ++j;
            }

            swap(indices, i, minIndex);

            ++i;
            j = indices.length - 1;

            while (i < j) {
                swap(indices, i++, j--);
            }

            loadPermutation();
        }

        private void loadPermutation() {
            List<T> newPermutation = new ArrayList<>(indices.length);

            for (int i : indices) {
                newPermutation.add(allElements.get(i));
            }

            this.nextPermutation = newPermutation;
        }
    }

    private static void swap(int[] array, int a, int b) {
        int tmp = array[a];
        array[a] = array[b];
        array[b] = tmp;
    }

    public static void main(final String... args) {
        List<String> alphabet = Arrays.asList("A", "B", "C", "D");
        int row = 1;

        for (List<String> permutation : new PermutationIterable<>(alphabet)) {
            System.out.printf("%2d: %s\n", row++, permutation);
        }
    }
}

What can I improve here? Please, tell me anything that comes to mind.


texts: Safe implementation for extending authentication cookie with user data

texts:
After searching around and reading through articles and answers I came up with this implementation for extending the cookie for Forms Authentication. I am not sure that I did not introduce any vulnerabilities and now I provide it here for review.

    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
//... other code
        // old implementation
        FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
        string userData = "userdata";
        var cookie = ExtendAuthCookie(FormsAuthentication.GetAuthCookie(model.Username, model.RememberMe), userData);
        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
//... other code
    }

    private HttpCookie ExtendAuthCookie(HttpCookie authCookie, string userData)
    {
        var originalTicket = GetOriginalTicket(authCookie);
        System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
           2,
           originalTicket.Name,
           originalTicket.IssueDate,
           originalTicket.Expiration,
           originalTicket.IsPersistent,
           userData, // Extending with user data
           originalTicket.CookiePath
           );

        String strTicket = FormsAuthentication.Encrypt(ticket);
        if (string.IsNullOrEmpty(strTicket))
        {
            throw new HttpException("Unable to encrypt cookie ticket.");
        }

        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strTicket);

        cookie.HttpOnly = true;
        cookie.Secure = true;

        return cookie;
    }

    private FormsAuthenticationTicket GetOriginalTicket(HttpCookie authCookie)
    {
        var cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (cookie == null)
        {
            throw new ArgumentNullException("cookie");
        }

        var ticket = FormsAuthentication.Decrypt(cookie.Value);
        if (ticket == null)
        {
            throw new ArgumentNullException("ticket");
        }

        if (ticket.Expired)
        {
            throw new InvalidOperationException("ticket");
        }

        return ticket;
    }


texts:
This script updates a settings in ssl config file for Nginx. I generate DHEC key and then update the Nginx SSL file to that location.  I also give an option for the user through arguments if they want to change the bit size of the key and if they want more conservative or hardened SSL cipher suites.

I don't know how to deal with the long wait on a large key because the user might think the program froze because it takes a long time generate. Its dependent on the environment of course how long you wait. How would you deal with this, through a percentage output? I'm using a spinner at the moment which does the same thing as the 'openssl' command does. So I will probably not use it if I can't find something uses a line or two at most instead of continuous outputting and pushing everything off screen.

#!/bin/bash

source /etc/global.conf # load global vars
source setup/functions.sh #functions

apt_install openssl

nginx_ssl_conf=/etc/nginx/nginx-ssl.conf
DEFAULT_BIT_SIZE=2048
isHardened="false"
hardened_ciphers="'ECDH+AESGCM256:DH+AESGCM256:ECDH+AES256:SH+AES256:RSA+AESGCM256:RSA+AES256:!aNULL:!MD5:!kEDH';"
hardened_protocol="TLSv1.2;"

DHEC_path=$STORAGE_ROOT/ssl/dhparam.pem

# Functions
update_config()
{
    lineNUM=$(grep -n "$2" $1 | tail -n1 | sed 's/:.*//')
    [ "$lineNUM" ] || lineNUM="$"
    sed -i -r "$lineNUM s|#?(.*)|#\1\n$4\n$2 $3|" "$1"
}

ok()
{
    echo -e '\e[32m'$1'\e[m';
}

spinner()
{
    local pid=$1
    local delay=0.75
    local spinstr='|/-\'
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf " [%c]  " "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b\b\b\b"
    done
    printf "    \b\b\b\b"
}

# Usage info
usage()
{
    cat << EOF
    Usage: ${0##*/} [-h] [-p DIR_DHEC_KEY] [-b BIT_SIZE]  [-c DIR_NGINX_SSL]...
    This script generates and enables DHEC for Nginx.  Defaulted to 2048 key.
    Hardened mode will generate 4096 key and the following cipher suites:
    'ECDH+AESGCM256:DH+AESGCM256:ECDH+AES256:SH+AES256:RSA+AESGCM256:RSA+AES256:!aNULL:!MD5:!kEDH'

    -h          Enable hardened ciphers and 4096 bit key.
    -p          Specify dir to generate the DHEC key.
    -c          Specify dir nginx ssl conf is.
    -b          Specify the bit size to generate which will override any other default.
EOF
    exit 1
}

while getopts "hb:c:p:" opt ; do
    case "${opt}" in
        b)
            BIT_SIZE=${OPTARG}
            if [ -z "${OPTARG}" ]; then
               usage
            fi
            ;;
        h)
            isHardened=true
            BIT_SIZE=4096
            ;;
    p)
            DHEC_path=${OPTARG}
        if [ -z "${OPTARG}" ]; then
               usage
            fi
            ;;
        c)
            nginx_ssl_conf=${OPTARG}
            if [ -z "${OPTARG}" ]; then
               usage
            fi
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${BIT_SIZE}" -a "true" == ${isHardened} ]; then
    BIT_SIZE=4096
elif [ -z "${BIT_SIZE}" ]; then
    BIT_SIZE=$DEFAULT_BIT_SIZE
fi

ok "â¯â¯â¯ Generating DH elliptic curve key.  It might take a while, grab a coffee!"
ok "Seriously, $BIT_SIZE takes forever!"

if [ ! -f $DHEC_path ]; then
  # Generate a 4096 bit random parameter for DH elliptic curves.
  # Generated by OpenSSL with the following command:
  #   openssl dhparam -outform pem -out dhparam.pem 2048
  #   openssl dhparam -outform pem -out dhparam.pem 4096
   ( openssl dhparam -outform pem -out $DHEC_path $BIT_SIZE) &
    spinner $!
fi
        update_config $nginx_ssl_conf ssl_dhparam $DHEC_path';' "#Path to DHEC key"

if [ $isHardened == "true" ]; then
    update_config $nginx_ssl_conf ssl_ciphers $hardened_ciphers "#Hardened SSL Ciphers DHEC"
        update_config $nginx_ssl_conf ssl_protocols $hardened_protocol "#Hardened SSL Protocol"
fi

service nginx reload


texts:
I used the jQuery UI plugin Dialog to ask a user for "name" and to show it in a subsequent dialog.

Is there the better way to add a function to the option "buttons" to get the data and to go to a new dialog?

    $("#message").dialog({autoOpen: false});
    $("#form").dialog({
        autoOpen: false,
        modal: true,
        title: "What is your name?",
        buttons:{
            "Submit": function(){
                $( this ).dialog( "close" );
                $("#message").dialog("open");
                var str = $("input").val();
                $("span").text(str);
            }
        }
    });
    $("#btn").click(function(){
        $("#form").dialog("open");
    });

    <button id="btn">Click me</button>
    <form id="form">
        <input type="text" name="">
    </form>

Hello, !