texts: Recursive program for generating and printing all permutations of the numbers 1, 2, ..., n for given integer number n

texts:
I've just written code for generating all permutations of the numbers from 1 to n in Java. It seems to work, but I think it's a bit more complex than it needs to be.

import java.util.*;

public class ProblemFour {
    private static int n;

    private static void printResult(int[] result) {
        Set<Integer> set = new HashSet<>();
        // I am using Hashset<> to avoid repetitions
        Integer[] nums = new Integer[result.length];
        for (int i = 0; i < n; i++) {
            nums[i] = result[i];
        }

        Collections.addAll(set, nums);
        if(set.size() == n) System.out.println(Arrays.toString(nums));
    }

    private static void permute(int[] result, int index) {
        if (index == result.length) {
            printResult(result);
            return;
            // Recursion bottom
        }
        for (int i = 1; i <= n; i++) {
            result[index] = i;
            permute(result, index+1);
        }
    }

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

        System.out.print("From 1 to: ");
        n = input.nextInt();

        int[] result = new int[n];

        permute(result, 0);
    }
}


texts:
The aim is to guess a four letter string. Each letter can be tried four times. If the letter cannot be guessed, we go to the next letter until the fourth letter is reached.

I looked at my code and even though I'm satisfied because I've done everything by myself, I'm wondering how I can improve it. I'm probably relying too much on if but so far. I do not have ideas on what I can do to make it leaner.

# -*- coding: utf-8 -*-

def typeYourword():
  global yourword
  yourword= raw_input("type your word \n")
  while len(yourword)<4 or len(yourword)>4:
    yourword= raw_input("type your word again \n")
  else:
    print("Now your word : ",yourword," has the correct format")
    return yourword

#yourword='tata'

def monMot(tonmot):
    global var_glob
    var_glob=list(tonmot)
    return var_glob

def comptage(monmot):
    global var_comptage
    var_comptage = 0
    for cpte in range(0,(len(monmot))):
      print("this is your " + str(cpte+1) + " letter")
      for count in range(1,5):
        comptage_mot=cpte+1
        b = raw_input("Type your letter \n")
        while len(b)>1 or len(b)==0:
          b=raw_input("type your letter again \n")
        else:
          if var_glob[cpte] == b and comptage_mot<4:
            var_comptage+=1
            print ("yes")
            break
          elif var_glob[cpte] == b and comptage_mot==4:
            var_comptage+=1
            print ("You won. End of game")
            break
          else:
            if count == 4 and comptage_mot<4:
              print("this was your "+str(count)+ " last try for the "+str(comptage_mot)+" letter. let's go to the next letter")
            elif count == 4 and comptage_mot==4:
              print("this was your last try for the word. You guessed "+str(count)+ " letters. End of game.")
            else:
              print("wrong letter, try again" + " ,this was your " + str(count) + " try. Now your " +str(count+1) + " try")
    print(var_comptage)

typeYourword()
monMot(yourword)
comptage(var_glob)


texts:
This is my take for constexpr big / little endian conversions.

The code supports only little and big endian; mixed endian such PDP is not supported.

#include <cstdio>
#include <cstdint>

namespace myendian_impl_{

    template<typename UINT>
    UINT byteswap(UINT const a);

    template<>
    constexpr uint16_t byteswap(uint16_t const a){
        constexpr uint8_t b[] = {
            8 * (2 - 1)
        };

        auto const x =
            (0x00ffULL & a) << b[0] |
            (0xff00ULL & a) >> b[0]
        ;

        return static_cast<uint16_t>(x);
    }

    template<>
    constexpr uint32_t byteswap(uint32_t const a){
        constexpr uint8_t b[] = {
            8 * (2 - 1),
            8 * (4 - 1)
        };

        auto const x =
            (0x000000ffULL & a) << b[1] |
            (0x0000ff00ULL & a) << b[0] |
            (0x00ff0000ULL & a) >> b[0] |
            (0xff000000ULL & a) >> b[1]
        ;

        return static_cast<uint32_t>(x);
    }

    template<>
    constexpr uint64_t byteswap(uint64_t const a){
        constexpr uint8_t b[] = {
            8 * (2 - 1),
            8 * (4 - 1),
            8 * (6 - 1),
            8 * (8 - 1)
        };

        auto const x =
            (0x00000000000000ffULL & a) << b[3] |
            (0x000000000000ff00ULL & a) << b[2] |
            (0x0000000000ff0000ULL & a) << b[1] |
            (0x00000000ff000000ULL & a) << b[0] |
            (0x000000ff00000000ULL & a) >> b[0] |
            (0x0000ff0000000000ULL & a) >> b[1] |
            (0x00ff000000000000ULL & a) >> b[2] |
            (0xff00000000000000ULL & a) >> b[3]
        ;

        return static_cast<uint64_t>(x);
    }

    // ==============================

    class isBE{
        constexpr static uint32_t u4 = 1;
        constexpr static uint8_t  u1  = (const uint8_t &) u4;
    public:
        constexpr static bool value = u1 == 0;
    };

    // ==============================

    template<bool b>
    struct be_tag{};

    // ==============================

    template<typename UINT>
    constexpr UINT htobe(UINT const a, be_tag<true>){
        return a;
    }

    template<typename UINT>
    constexpr UINT htobe(UINT const a, be_tag<false>){
        return byteswap(a);
    }

} // namespace myendian_impl_

constexpr inline uint16_t htobe16(uint16_t const a){
    using namespace  myendian_impl_;
    return htobe(a, be_tag<isBE::value>{});
}

constexpr inline uint32_t htobe32(uint32_t const a){
    using namespace  myendian_impl_;
    return htobe(a, be_tag<isBE::value>{});
}

constexpr inline uint64_t htobe64(uint64_t const a){
    using namespace  myendian_impl_;
    return htobe(a, be_tag<isBE::value>{});
}

int main(){
    printf("%16x %16x\n",   0x1122,         htobe16(0x1122)         );
    printf("%16x %16x\n",   0x11223344,     htobe32(0x11223344)     );
    printf("%16lx %16lx\n", 0x1122334455667788, htobe64(0x1122334455667788) );
}


texts: Split a list into two parts with a given length

texts:
I'm learning Common Lisp as a hobby and am trying tasks from L-99: Ninety-Nine Lisp Problems, but I'm not sure how good my code is. Here is one of the tasks which I solved:

GitHub solution

;;; (*) Split a list into two parts; the length of the first part is given.
;;; Do not use any predefined predicates.
;;;
;;; Example:
;;; * (split '(a b c d e f g h i k) 3)
;;; ((A B C) (D E F G H I K))

(defun split (given-list cnt &optional (result-left nil))
  (if (= cnt 0)
    (if (null result-left)
      given-list
      (cons result-left (list given-list)))
    (if (null given-list)
      result-left
      (split (cdr given-list) (- cnt 1) (append result-left (list (car given-list)))))))


texts:
I Have the below code that gets urls of PDF files, send them to a convert function and returns them as images, is there a way to make this code more readable?
Is there a way to avoid functions chaining?
import PDFtoImages from '../PDFtoImages'

export async function convertPDF(file, category) {
const images= await PDFtoImages(file.data)
return {
   category: category ? [category] : [],
    images
  }
}

export function fetchBlob(url, opts = {}) {
  return fetch(url, opts).then(res => {
    if (!res.ok) return Promise.reject(new Error(res.statusText))
      return res.blob()
    })
}

export async function fetchFilesAsImages(filesUrls) {
  const pdfAsImages= []
  await Promise.all(
    filesUrls.map(async file=> {
      pdfAsImages.push(
        await convertPDF(
          {data: await fetchBlob(file.url)},
          file.category
        )
      )
    })
  )
  return pdfAsImages
}


texts: Find sum of 3 that total a target from a List

texts:
A related Java question got me curios.

All unique combinations (not permutations) of 3 values that sum to a target from a list of integers.

Values can duplicate in the list but are only used once.

By sorting the input the evaluation is able to take shortcuts.

Feedback on both code and speed please.

Assume all input and sum >= 0.

public static List<List<int>> FindThreeSum(List<int> input, int sum = 24)
{
    //cannot have default on a list to my knowledge
    if(input.Count < 3)
    {
        input = new List<int> { 8, 12, 6, 18, 4, 3, 8, 1, 6, 3, 8, 9, 0 };
        //in real life throw an error
    }
    List<int> sortedInput = input.OrderBy(x => x).ToList();
    Debug.WriteLine(string.Join(", ", sortedInput));
    int sortedCount = sortedInput.Count;
    int maxInput = sortedInput[sortedCount - 1];
    List<List<int>> findSum = new List<List<int>>();
    if (3 * (long)maxInput < (long)sum || sortedInput[0] < 0 || sum < 0 || 3 * sortedInput[0] > sum)
    {
        return findSum;
    }
    int sumSoFar;
    int sumI = int.MaxValue;
    int sumJ = 0;
    int sumK = 0;
    for (int i = 0; i < sortedCount - 2; i++)
    {
        if(sortedInput[i] == sumI)
        {
            continue;
        }
        sumI = sortedInput[i];
        if(3 * sumI > sum)
        {
            break;  //sumSoFar is only going to get bigger
        }
        for (int j = i + 1; j < sortedCount - 1; j++)
        {
            if (sortedInput[j] == sumJ)
            {
                continue;
            }
            sumJ = sortedInput[j];
            sumSoFar = sumI + sumJ;
            if (sumSoFar + sumJ > sum)
            {
                break;
            }
            else if(sumSoFar + maxInput < sum)
            {
                continue;
            }
            for (int k = j + 1; k < sortedCount; k++)
            {
                if (sortedInput[k] == sumK)
                {
                    continue;
                }
                sumK = sortedInput[k];
                sumSoFar = sumI + sumJ + sumK;
                if (sumSoFar > sum)
                {
                    break;
                }
                else if(sumSoFar == sum)
                {
                    findSum.Add(new List<int> { sumI, sumJ, sumK });
                    Debug.WriteLine($"{sumI} {sumJ} {sumK}");
                }
            }
        }
    }
    Debug.WriteLine("daDone");
    return findSum;
}


texts: Simple Gradient Descent Algorithm In Haskell

texts:
After becoming interested in various bits of functional programming provided by non-functional languages, I've recently decided to start learning Haskell.  As I'm fairly experienced with conventional imperative programming languages,  I decided to make my "hello world" something a little more complex - an implementation of gradient descent with 2 variables.

The idea with this code is that you fill in the training set for the algorithm in the code, and then run the code something similar to this:

descentFunc = singleDescend trainingSet 0.1
deltas = descend descentFunc ( 100, 1 ) 100000

Where 0.1 is the learning rate (referred to as lr in the code) 100000 is the number of iterations for the loop, and ( 100, 1 ) is an initial guess for the coefficients.

The actual code that's running is below.  As I'm entirely new to Haskell, I was wondering whether code such as this is acceptable?  And whether there's any obvious idioms I'm missing/misusing or any glaring style errors I've made.

Any comments on my implementation of the algorithm are welcome also.

import Data.List

trainingSet = [ (1.0,10.0),(2.0,20.0),(3.0,30.0),(4.0,40.0) ]

hypothesis (d1,d2) x = d1 + (d2 * x)

squareDiff d (x,y) = diff * diff
    where diff = ( hypothesis d x ) - y

costFunc ts d = scaleFactor * sum squares
    where scaleFactor = 1.0 / (2 * genericLength ts)
          squares = map (squareDiff d) ts

diff d (x,y) = (hypothesis d x) - y

descendTheta thetaFunc deltaFunc ts lr deltas =
    deltaFunc deltas - (scaleFactor * sum scaledDiffs)
    where scaleFactor = lr / genericLength ts
          diffs = map (diff deltas) ts
          scaledDiffs = map (\(x,y) -> x * thetaFunc y) $ zip diffs ts

descendThetaZero = descendTheta (\_ -> 1) fst
descendThetaOne = descendTheta (fst) snd

singleDescend ts lr deltas = (thetaZero,thetaOne)
    where thetaZero = descendThetaZero ts lr deltas
          thetaOne = descendThetaOne ts lr deltas

descend func deltas i
    | i == 0 = deltas
    | otherwise = descend func ( func deltas ) ( i - 1 )


texts: "ACM ICPC Team" challenge on Hackerrank... Easy?

texts:
This challenge took me awhile to figure out, and it's characterized as "easy," so I'm sorta wondering what I missed.

Problem Statement
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.
N = number of people = number of lines of input. 2 ≤ N ≤ 500
M = number of topics = number of bits per line. 1 ≤ M ≤ 500

Sample Input

4 5
10101
11100
11010
00101

Sample Output

5
2

My solution below uses a BitArray object, because all of the test cases except one have more than 32 topics.
I'm wondering if HackerRank wasn't expecting something a little more fundamental... Maybe some clever string twiddling hack that I don't know about?
Most of the test cases took about .86 seconds to execute, which seems quite slow to me.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Solution {
    static void Main(String[] args)
    {
        string input = Console.ReadLine();
        string[] inputs = input.Split(new char[] {' '});

        int numberOfMembers = int.Parse(inputs[0]);
        int numberOfTopics = int.Parse(inputs[1]);

        var bitArray = new BitArray[numberOfMembers];
        for (int n = 0; n < numberOfMembers; n++)
        {
            bitArray[n] = new BitArray(numberOfTopics);

            string memberTopics = Console.ReadLine();
            for(int m = 0; m < numberOfTopics; m++)
                bitArray[n].Set(m, memberTopics[m] == '1');
        }

        // Find the maximum number of topics that all the teams know.
        int maxTopics = 0;
        for(int i = 0; i < numberOfMembers - 1; i++)
            for (int j = i + 1; j < numberOfMembers; j++)
            {
                int numberOfTeamTopics = NumberOfSetBits(new BitArray(numberOfTopics).Or(bitArray[i]).Or(bitArray[j]));
                if (numberOfTeamTopics > maxTopics)
                    maxTopics = numberOfTeamTopics;
            }

        // Find the number of teams that know the maximum number of topics.
        int maxTeams = 0;
        for(int i = 0; i < numberOfMembers - 1; i++)
            for (int j = i + 1; j < numberOfMembers; j++)
            {
                int numberOfTeamTopics = NumberOfSetBits(new BitArray(numberOfTopics).Or(bitArray[i]).Or(bitArray[j]));
                if (numberOfTeamTopics == maxTopics)
                    maxTeams++;
            }

        Console.WriteLine(maxTopics);
        Console.WriteLine(maxTeams);
    }

    static int NumberOfSetBits(BitArray b)
    {
        int count = 0;
        for (int i = 0; i < b.Length; i++)
            if (b.Get(i))
                count++;
        return count;
    }
}


texts:
There is an article where the author tries to compare performance of different web stacks. The result looks pretty controversial.
I try to prove that in real use case the difference between scores of different stacks will be not so significant(under "real" I mean something which relies on database) .

For this purpose I take two stacks: one from the top side(node+express) and the looser(python+flask). And now I'm trying to implement a little bit more realistic use case for both platforms.

This is the code for the flask application:

#app.py
from flask import render_template
from flask import Flask
import sqlite3

conn = sqlite3.connect('data.db')
app = Flask(__name__)
c = conn.cursor()
if c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='data'").fetchone() is None:
    c.execute("CREATE TABLE data (value TEXT)")
    conn.commit()
conn.close()

@app.route('/<int:number>')
def index(number=1):
    conn = sqlite3.connect('data.db')
    c = conn.cursor()
    c.executemany("INSERT INTO data VALUES (?)",   [(fib(number),)] * 10);
    list = c.execute("select * from data limit 100").fetchall()
    conn.commit()
    conn.close()
    return render_template('template.html', list=list)

def fib(n):
    if n == 0: return 0
    elif n == 1: return 1
    else:
        return fib(n - 1) + fib(n - 2)

if __name__ == '__main__':
    app.run(debug=False)

#template.html

{% for l in list %}

{{ l[0] }}

{% endfor %}

And the code for node application:

// app.js
var express = require("express");
var jade = require('jade');
var db = new (require('sqlite3').verbose()).Database('data.db');
var app = express();

var fib = function (n) {
  if (n === 0) {
    return 0;
  } else if (n == 1) {
    return 1;
  } else {
    return fib(n - 1) + fib(n - 2)
  }
};

var getApp = function () {
    app.get("/:number", function (req, res) {
      var number = req.param("number");
      query = db.prepare("INSERT INTO data VALUES (?)")
      for(var i=0; i<10; i++) {
        query.run((fib(number)))
      };
      db.all("select * from data limit 100", function(err, rows){
        var rendered = jade.renderFile('template.jade', {list: rows})
        res.send(rendered);
      });
    });
    app.listen(3000);
}

db.get(
  "SELECT name FROM sqlite_master WHERE type='table' AND name='data'",
  function (err, row) {
    if(err !== null) {
      throw new Error();
    }
    if(row === undefined) {
      db.run('create table data (value text)', getApp)
    } else {
      getApp()
    }
  }
);

# template.jade
ul
    each l in list
        li=l.value

Questions

Some advice about node code. How can I make it more idiomatic and beautiful?
There is some strange behavior in the node app. Benchmark results proposed below should describe it. What I'm doing wrong?

I would be glad to achieve any piece of advice about improving these code samples.

Running 30s test @ http://localhost:3000/10
2 threads and 64 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    26.19s     4.89s   28.93s    77.14%
    Req/Sec     0.87      1.46     4.00     86.67%
  64 requests in 30.01s, 81.25KB read
  Socket errors: connect 0, read 0, write 0, timeout 896


texts:
I had to create a report for a customer by most sold products in the last month and sorted by parameters they have assigned.

We have three parameters on products: Colour, Type and Collection.

The desired result is to sort products by most sold Collection, then most sold Colour, then most sold Type. The query I have written is monstrous, and I am sure it could be written efficiently.

SELECT a.ID, collection.value as title, colour.value as colour, type.value as type
FROM orderrows oa
JOIN order o ON o.ID = oa.orderID
JOIN products a ON oa.productid = a.ID
JOIN productparameter as collection ON collection.productid = a.ID AND collection.parameterid = 'collection_id'
JOIN productparameter as type ON type.productid = a.ID AND type.parameterid = 'type_id'
JOIN productparameter as colour ON colour.productid = a.ID AND colour.parameterid = 'colour_id'
JOIN
(
    SELECT @rowId:=@rowId+1 AS rowId, collection.title
    FROM
    (
        SELECT collection.value as title
        FROM orderrows oa
        JOIN order o ON o.ID = oa.orderID
        JOIN products a ON oa.productid = a.ID
        JOIN productparameter as collection ON collection.productid = a.ID AND collection.parameterid = 'collection_id'
        WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
        GROUP BY collection.value
        ORDER BY SUM(oa.productprice * oa.productamount) DESC
    ) collection,
    (
        SELECT @rowId:=0
    ) t2
) as collection_sort ON collection.value = collection_sort.title
JOIN
(
    SELECT @rowId:=@rowId+1 AS rowId, colour.title
    FROM
    (
        SELECT colour.value as title
        FROM orderrows oa
        JOIN order o ON o.ID = oa.orderID
        JOIN products a ON oa.productid = a.ID
        JOIN productparameter as colour ON colour.productid = a.ID AND colour.parameterid = 'colour_id'
        WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
        GROUP BY colour.value
        ORDER BY SUM(oa.productprice * oa.productamount) DESC
    ) colour,
    (
        SELECT @rowId:=0
    ) t2
) as colour_sort ON colour.value = colour_sort.title
JOIN
(
    SELECT @rowId:=@rowId+1 AS rowId, type.title
    FROM
    (
        SELECT type.value as title
        FROM orderrows oa
        JOIN order o ON o.ID = oa.orderID
        JOIN products a ON oa.productid = a.ID
        JOIN productparameter as type ON type.productid = a.ID AND type.parameterid = 'type_id'
        WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
        GROUP BY type.value
        ORDER BY SUM(oa.productprice * oa.productamount) DESC
    ) type,
    (
        SELECT @rowId:=0
    ) t2
) as type_sort ON type.value = type_sort.title
WHERE o.orderdate > NOW() - INTERVAL 1 MONTH
GROUP BY a.ID
ORDER BY collection_sort.rowId ASC, colour_sort.rowId ASC, type_sort.rowId ASC


texts: Correcting punctuation spacing in a string

texts:
I'm working on a program that corrects all punctuation spacing in a String.

Examples:

// "Hello ,World"  ->  "Hello, World"
// "9 :00 A .M ."  ->  "9:00 A.M."
// "can 't even."  ->  "can't even."

Here's how it works:

My process is to first add a space between all punctuation and then remove any unnecessary spaces. This allows me to tokenize both punctuation and words/numbers correctly.

For example, the acronym String s = " A .M ." is transformed into "A . M .".

When split by a space, it returns the list ["A", ".", "M", "."].

I then attempt to "fix" the remaining line spacing in the String, so the result will become "A.M.".

Here's an example of what the code looks like for correcting acronyms:

In FixAcronym.java:

/**
 * Fix acronyms.
 */
private static String fix(String line, SubtitleObject so) {
    StringBuilder builder = new StringBuilder();
    String[] split = so.split(RegexEnum.SPACE, line); // same as line.split(" ") but cached
    String prevPrevPrev = null, prevPrev = null, prev = null, current = null;
    boolean addSpace;
    for (int i = 0; i < split.length; ++i) {
        prevPrevPrev = prevPrev;
        prevPrev = prev;
        prev = current;
        current = split[i];
        addSpace = true;
        if (prevPrevPrev != null && prevPrevPrev.length() == 1
            && Character.isLetter(prevPrevPrev.charAt(0))) {
            if (prevPrev.equals(".")) {
                if (prev.length() == 1 && Character.isLetter(prev.charAt(0))) {
                    if (current.equals(".")) {
                        StringBuilderUtil.deleteSpaceAt(builder, builder.length() - 2);
                        StringBuilderUtil.deleteOnlyIfSpaceAt(builder, builder.length() - 3);
                        addSpace = false;
                    }
                }
            }
        }

        if (i > 0 && addSpace) {
            builder.append(' ');
        }
        builder.append(current);
    }

    return builder.toString();
}

In StringBuilderUtil.java:

/**
 * Delete space at index within StringBuilder.
 */
public static void deleteSpaceAt(StringBuilder builder, int index) {
    assert builder.charAt(index) == ' ';
    builder.deleteCharAt(index);
}

/**
 * Delete only if space at index within StringBuilder.
 */
public static void deleteOnlyIfSpaceAt(StringBuilder builder, int index) {
    if (builder.charAt(index) == ' ') {
        builder.deleteCharAt(index);
    }
}

Here's the problem: Because of all the different grammatical rules, there are a lot of different "fix" methods, and each subsequent "fix" uses the same technique.

line = FixTime.fix(line, this);
line = FixContractions.fix(line, this);
line = FixAcronym.fix(line, this);
// etc...

Each fix splits the line by a space, iterates through the tokens, deletes the space(s) in the StringBuilder when necessary, and appends the space and/or token.

The problem with this process is hypothetically I only need to iterate through the split line once to get the corrected String. This also makes the continuous creations, deletions, and appendings of the StringBuilder extraneous.

So the question is: Is there a better way to generalize this process while still preserving modularity, or is this as good as it gets?


texts:
I have just started to learn programming with Python. I have been going through several online classes for the last month or two. Please bear with me if my questions are noobish.

One of the classes I am taking asked us to solve this problem.

# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.

# A valid sudoku square satisfies these
# two properties:

#   1. Each column of the square contains
#       each of the whole numbers from 1 to n exactly once.

#   2. Each row of the square contains each
#       of the whole numbers from 1 to n exactly once.

# You may assume the the input is square and contains at
# least one row and column.

After a while of trying to come up with the best code I can, this is what I ended up with.

def check_sudoku(sudlist):
    x = range(1, len(sudlist)+1) # makes a list of each number to be found
    rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list
    z = range(len(sudlist))
    for num in x:
        for pos in z:
            if num not in sudlist[pos] or num not in rows[pos]:
                return False
    return True

This code does work and passed all checks the class asked for.  I just wonder what problems could the code have or how would you improve it?

I am just trying to improve by getting input from others.  I appreciate any suggestions.


texts:
Here I am trying to post a company view-model and update and insert according. But I feel I am writing it in wrong way or maybe there's a better approach.

Here's my code

[Route("Master/Company/Post"), HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> CompanyPostAsync(CompanyViewModel model)
    {
        model.CountryList = GetCountries();

        //System.Threading.Thread.Sleep(3000);
        var _viewName = "Companies";
        if (!ModelState.IsValid)
            return View(_viewName, model);

        try
        {
            var find = await con.Companies.FirstOrDefaultAsync(x => x.ID == model.ID);
            var currentUser = CurrentUser();
            if (find != null)
            {
                find.Name = model.Name;
                find.Alies = model.Alies;
                find.Line1 = model.Line1;
                find.Line2 = model.Line2;
                find.City = model.City;
                find.State = model.State;
                find.CountryId = model.CountryId;
                find.ZipCode = model.ZipCode;
                find.POBoxNo = model.POBoxNo;
                find.Telephone = model.Telephone;
                find.Mobile = model.Mobile;
                find.Email = model.Email;
                find.Website = model.Website;
                find.IncorporatedNumber = model.IncorporatedNumber;
                find.IncorporatedDate = model.IncorporatedDate;
                find.IsTaxApplicable = model.IsTaxApplicable;
                find.IsLogoPrintInReport = model.IsLogoPrintInReport;
                find.LogoPath = model.LogoPath;
                find.IsActive = model.IsActive;
                find.SaveCount += 1;

            }
            else
            {
                var company = new Company
                {
                    Name = model.Name,
                    Alies = model.Alies,
                    Line1 = model.Line1,
                    Line2 = model.Line2,
                    City = model.City,
                    State = model.State,
                    CountryId = model.CountryId,
                    ZipCode = model.ZipCode,
                    POBoxNo = model.POBoxNo,
                    Telephone = model.Telephone,
                    Mobile = model.Mobile,
                    Email = model.Email,
                    Website = model.Website,
                    IncorporatedNumber = model.IncorporatedNumber,
                    IncorporatedDate = model.IncorporatedDate,
                    IsTaxApplicable = model.IsTaxApplicable,
                    IsLogoPrintInReport = model.IsLogoPrintInReport,
                    LogoPath = model.LogoPath,
                    IsActive = model.IsActive,
                    SaveCount = 1
                };
                con.Companies.Add(company);
            }

            await con.SaveChangesAsync();
            CallSaved(true);
            return RedirectToAction("Companies", "Master", new { id = find?.ID });
        }
        catch (Exception ex)
        {
            CallSaved(false, ex.Message);
            return View(_viewName, model);
        }

    }


texts:
This phonebook application has a menu, which sorts by name or category. I do it like this in MainActivity:

Bundle bundle = new Bundle();
Fragment lvFragSortBy = new ListViewFragment();

switch (item.getItemId()) {

    case R.id.menuSortOrderName:
        item.setChecked(true);

        bundle.putString("sortBy", "name");

        lvFragSortBy.setArguments(bundle);
        getFragmentManager()
        .beginTransaction()
        .replace(R.id.fragContainer, lvFragSortBy)
        .commit();
        return true;

    case R.id.menuSortOrderCategory:
        item.setChecked(true);

        bundle.putString("sortBy", "category");
        lvFragSortBy.setArguments(bundle);
        getFragmentManager()
        .beginTransaction()
        .replace(R.id.fragContainer, lvFragSortBy)
        .commit();

        return true;

In ListViewFragment:

Bundle sortBundle = getArguments();
if (sortBundle != null) {
    orderBy = sortBundle.getString("sortBy");
}

And then:

protected ArrayList<Contact> doInBackground(Void... params) {
    try {
        db = new DbWorker(ctx);
        contacts = (ArrayList<Contact>) db.selectAllContacts(orderBy);
    } catch (Exception e) {
        Log.e(TAG, "Exception in AsyncTask.doInBackground");
    }
    return contacts;
}

This code works fine but I would like to know if it can be done better.


texts: Script for copying files to the appropriate directory

texts:
In the book Real World Haskell, the author writes in the first line of every file that uses, for example the following: file: ch05/PrettyJSON. The chapter slash and the name of a module.

I wanted to create a script which reads the first line and copies the files to the appropriate directory. In the above example we should copy the file to the directory ch05. I wanted to write this in Haskell in order to use it for "real world" applications.

But before starting writing to Haskell I wrote it in Python:

import os
import shutil

current_dir = os.getcwd()
current_files=os.listdir(current_dir)
haskell_files=filter(lambda x:x.find(".hs")!=-1,current_files)

for x in haskell_files:
 with open(x,"r") as f:
     header=f.readline()
    try:
        chIndex=header.index("ch")
    except ValueError as e:
        continue

    number=header[chIndex:chIndex+4]
 try:
    os.mkdir(number)
    shutil.copy2(x,number)
except OSError as e:
    shutil.copy2(x,number)

And then I tried to write the same code in Haskell:

f x = dropWhile (\x-> x/='c') x
g x = takeWhile (\x-> x=='c' || x=='h' || isDigit x) x
z= do
   y<-getCurrentDirectory
   e<-getDirectoryContents y
   let b=findhs e
   mapM w b
findhs filepaths = filter (isSuffixOf ".hs") filepaths
w filename= do
           y<-readFile filename
           let a=(g.f) y
           if "ch" `isPrefixOf` a
           then do
                 createDirectoryIfMissing False a
                 g<-getCurrentDirectory
                 writeFile (g ++"/"++ a ++ "/" ++ filename) y
            else
                return ()
main=z

Haskell code should be more elegant and more compact but it is not. Can you give me suggestions on making the above program more Haskellish?


texts: Perl script to match case law references

texts:
I am very new to Perl and decided to work on a simple script that could solve a problem I encounter in my day to day work. The purpose of the code that follows is to search over a body of text and extract English case law publication references. There are quite a few flavours of reference style, so I have several expressions looking for different reference structures.

I'm very much at the "hooray, I've managed to make it work"-stage on the Perl learning curve, but know enough to recognise that this code is pretty hideous.

There are two main areas I'm aiming to improve:

Getting the source text from a file, rather than plonking it
directly into the code.
Getting the output to write to a output.txt file.

An examples of obvious poor practice is that I have used strict or warnings. The interpreter didn't like various aspects of the code.

I'd be really grateful for some feedback on this very modest first attempt to use Perl in an applied way. It is pretty hideous and I'm sure there are endless ways in which this could be achieved more elegantly.

The Code

#!/usr/bin/perl

# Paste text to review below

$search_text = <<EOD;

    In Salomon v A Salomon and Co Ltd [1897] AC 22, the House of Lords held that these principles applied as much to a company that was wholly owned and controlled by one man as to any other company. In Macaura v Northern Assurance Co Ltd [1925] AC 619, the House of Lords held that the sole owner and controller of a company did not even have an insurable interest in property of the company, although economically he was liable to suffer by its destruction. Lord Buckmaster, at pp 626-627 said:

EOD

print "\n-----------------------------\n";
print "Case References Found in Text";
print "\n-----------------------------\n";

# Find NCits

print "\n***** NCits...\n\n";

while ($search_text =~ m/((\(|\[)\d{4}(\)|\]))(\s+((EWHC)|(EWHC\s+Admin)|(CAT)|(EWCA)|(EWCA\s+Civ)|(EWCA\s+Crim)|(EWCOP)|(EWFC)|(EWFC\s+B)|(EWPCC)|(UKHL)|(UKIAT)|(UKPC)|(UKSC)|(CSOH)|(CSIH)|(NICA)|(IESC)|(IECCA)|(IECA)|(IEHC)|(UKUT))\s+\d+)/ig) {

    print "$1$4\n";
}

# Find WLR

print "\n***** WLR references...\n\n";

    while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+\d+\s+((WLR))\s+\d+)/ig) {

        print "$1$4\n";

}

# Find AC with vol number

print "\n***** Appeal Cases references...\n\n";

    while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+\d+\s+((AC))\s+\d+)/ig) {

        print "$1$4\n";

}

# Find AC with no vol number

    while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+((AC))\s+\d+)/ig) {

        print "$1$4\n";
}

# Find QB with vol number

print "\n***** Queen's Bench Cases cases...\n\n";

    while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+\d+\s+((QB))\s+\d+)/ig) {

        print "$1$4\n";
}

# Find QB with no vol number

while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+((QB))\s+\d+)/ig) {

    print "$1$4\n";
}

print "\n***** External references...\n\n";

while ($search_text =~ m/((\(|\[)\d{4}(\)|\])){0,1}(\s*\d+\s+((TLR)|(TLR\s+\(Pt\s+1\))|(TLR\s+\(Pt\s+2\))|(LGR)|(Cr\s*App\s*R)|(Cr\s*App\s*R\s*\(S\))|(Ll\s*L\s*Rep)|(LlLR)|(TC)|(FLR)|(BCLC))\s+\d+)/ig) {

    print "$1$4\n";
}

# Find NIQB

print "\n***** NI Queen's Bench Cases cases...\n\n";

while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+((NIQB))\s+\d+)/ig) {

    print "$1$4\n";
}

# Find NZLR

print "\n***** NZLR references...\n\n";

    while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+\d+\s+((NZLR))\s+\d+)/ig) {

        print "$1$4\n";

}

# Find All ER

while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+\d+\s+((All ER))\s+\d+)/ig) {

    print "$1$4\n";
}

# Find ECR

print "\n***** ECR references...\n\n";

while ($search_text =~ m/((|\[)\d{4}(\)|\]))(\s+((ECR))\s+\d+)/ig) {

    print "$1$4\n";
}

# Old Style ICLR Refs

print "\n***** Older volume references...\n\n";

while ($search_text =~ m/(\d+\s+((App\s*Cas)|(Ch\s*D)|(CPD)|(Ex\s*D)|(P.D.)|(Q.B.D.))\s+\d+)/ig) {

    print "$1$4\n";
}


texts: Using dplyr and pipes for logistic regression plotting

texts:
I have successfully created a plot of a binomial glm using example data. https://sciences.ucf.edu/biology/d4lab/wp-content/uploads/sites/125/2018/11/parasites.txt

The predictors of the model include 3 predictors (one categorical, 2 continuous)

The code works fine but I have been wanting to try and incorporating more dplyr functions and pipes to streamline code. Ultimately, I want to make my block of code into a function that works with any model with the same type and number of predictors for a binomial glm. Are there better ways to carry out my code with more tidyverse/dplyr code?

#import parasites file

df<-parasites
m1<-glm(data=df, infected~age+weight+sex, family = "binomial")
summary(m1)
age_grid <- round(seq(min(df$age), max(df$age), length.out = 15))
weight_grid <- round(seq(min(df$weight), max(df$weight), length.out = 15))
newdat <- expand.grid(weight =weight_grid,
                      age = age_grid, sex = c("female", "male"))

pred <- predict.glm(m1, newdata = newdat, type="link", se=TRUE)
ymin <- m1$family$linkinv(pred$fit - 1.96 * pred$se.fit)
ymax <- m1$family$linkinv(pred$fit + 1.96 * pred$se.fit)
fit <- m1$family$linkinv(pred$fit)
z <- matrix(fit, length(age_grid))
ci.low <- matrix(ymin, length(age_grid))
ci.up <- matrix(ymax, length(age_grid))

x<-data.frame(pred = fit,
              low = ymin,
              high = ymax,
              newdat) %>% mutate(category=cut(age, breaks=c(0, 69, 138, 206), labels =
                                                c("0-69", "70-139", "139-206")))

x$age<-as.factor(x$age)

library(ggplot2)
finalgraph<-ggplot(data=x)+
  geom_line(aes(x = weight, y = pred, color = age))+
  geom_ribbon(aes(x = weight, ymin = low, ymax = high, fill = age), alpha = 0.1) +
  facet_grid(category~sex) +theme(panel.grid.major = element_blank(),
                                  panel.grid.minor = element_blank())+
  ylab(expression(bold(y = "Infection Probability"))) + xlab(expression(bold("Weight"))) +
  theme(legend.position = "right",strip.text.x = element_text(face = "bold", size=12),
        strip.text.y = element_text(size=10),
        axis.text.y = element_text(size=10, face = "bold"), axis.text.x = element_text(size=10),
        axis.title = element_text(size=12),
        legend.text=element_text(size=10), legend.title = element_text(size=12, face="bold"))+
  labs(linetype="Age (months)", colour="Age (months)", fill = "Age (months)")
finalgraph

Code notes:
Essentially I made a model, created a bunch of values from my predictors (age_grid, v_grid) and made all possible combinations of these values along with the categorical variable of sex using expand.grid.

Then I just used the predict.glm function to extract predicted values based off of expand.grid object. I also extracted std. errors and calculated confidence intervals (ci.up and ci. low). Then I used some dplyr functions to create a dataframe with all this information and also made a new column called category. Category breaks down one of my variables (age) into four distinct groups based of  f of breaks I decided on and labelled as decided as well.  Then I plotted all of this data using ggplot2.


texts:
I'm working on an exercise where I"m supposed to display all data contained in a table.  Here's the solution I can up with:

<?php
$result = mysql_query("SELECT * FROM contacts ORDER BY id DESC");
    while($user= mysql_fetch_array($result)) {
        echo $user['first'] . " " . $user['last'] . "
" . $user[phone] . "br />";
    }
?>

Here's the solution the tutorial gave:

<?php
$result=mysql_query("SELECT * FROM contacts ORDER BY id DESC");

$num=mysql_num_rows($result);

$i=0;
while ($i < $num) {

$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");

echo "$first $last
Phone: $phone

";

$i++;
}
?>

The database fields are:

id
first
last
phone

Can someone explain WHY one is better than the other. They both work as far as I can tell.


texts: Fibonacci sequence and nth number with reduce()

texts:
const generateFibonnaciSequence = (n) => {
    return [
        (arr = new Array(n).fill(1).reduce((arr, _, i) => {
            arr.push(i <= 1 ? 1 : arr[i - 2] + arr[i - 1]);
            return arr;
        }, [])),
        arr[n - 1],
    ];
};

const [fibonacciSequence, fibonacciNthNumber] = generateFibonnaciSequence(n);

My idea is to return an array holding fibonacci sequence up to n in index 0 and fibonnaci's n-th value in index 1. Can someone help me with a prettier way of constructing this function. I'd like to avoid holding the array in temp arr variable if possible, but still use a single expression for return statement.


texts:
I've implemented an identity function (well, actually a functor struct) in C++. The goal is that every occurrence of an expression expr in the code can be substituted by identity(expr) without changing the semantics of the program at all.

I make it a struct with a templated operator() instead of simply a function template because this enables us to pass identity as an argument to other functions (say std::transform) without needing to specify the type (e.g., identity<std::pair<std::vector<int>::const_iterator, std::vector<double>::const_iterator>>).

The code is written in C++14.

#include <utility>

static constexpr struct identity_t {
    template<typename T>
    constexpr decltype(auto) operator()(T&& t) const noexcept
    {
        return std::forward<T>(t);
    }
} identity{};

Usage:

int x = 42;
identity(x) = 24;

constexpr int size = 123;
int arr[identity(size)] = {};

vector<int> v1 = {1, 2, 3, 4}, v2;
v2.reserve(v1.size());
transform(v1.cbegin(), v1.cend(),
          back_inserter(v2),
          identity);

template<typename T>
class my_container {
public:
    template<typename F>
    auto flat_map(F&& f) const { ... }

    auto flatten() const { return flat_map(identity); }

    ...
};

Since identity(expr) is nothing more than a cast, performance should not be a problem. I'm concerned whether there are cases in which this implementation fails to keep the program's behavior unchanged. If there are, how can I fix the implementation?

EDIT: I changed "a variable x" in the first paragraph to "an expression expr". The latter is more accurate.


texts:
I'm trying to dry up this Rails post model:

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: [:slugged, :finders]
  validates_presence_of :title
  scope :published, -> { where('hidden = ? AND published_at IS NOT NULL AND published_at < ?', false, DateTime.now).order(published_at: :desc) }
  paginates_per 10
  attr_accessor :published_at_date, :published_at_time
  acts_as_taggable
  mount_uploader :image, ImageUploader

  after_initialize :set_default_values, :if => :new_record?

  def set_default_values
    self.ad ||= false
  end

  def published?
    if self.hidden == true || self.published_at.blank?
      false
    else
      self.published_at < DateTime.now ? true : false
    end
  end

  def not_published?
    if self.hidden == true || self.published_at.blank?
      true
    else
      self.published_at < DateTime.now ? false : true
    end
  end

  def can_publish?
    !published_at.blank? && hidden?
  end
end

The first thing I am removing is the default value section as that can be changed to a database default to set the initial value of the ad attribute to false each time.

after_initialize :set_default_values, :if => :new_record?

def set_default_values
  self.ad ||= false
end

The next part I am struggling with is the published? and not_published? methods. They should return a boolean value. In trying to try up the published? by removing self and the hidden = true for hidden?. In the else part of the conditional, I remove the ? true : false as the evaluation of the published_at < DateTime.now will return boolean from the method.

def published?
  if hidden? || published_at.blank?
    false
  else
   published_at < DateTime.now
  end
end

The not_published? method follows the same, but flipping the greater than sign to >:

 def not_published?
  if hidden? || published_at.blank?
    true
  else
    published_at > DateTime.now
  end
end

Then I realized that I could just call published? with a not !... duh.

def not_published?
  !published?
end

It is starting to look pretty good but I'd like to reduce it further. How can I reduce the published? method such that it does not need to the false ?


texts: Multidimensional Array indexed by integer array

texts:
I am in need of a multidimensional array that can be initialized easily with arbitrary dimensions. I have found this code here, which is beautiful, however poses some difficulties for me. its hard to initialize with arbitrary size and also difficult to access since I have to input each index using a comma to seperate it.

In my application each array 'slot' has the same size. Furthermore it would be easy to work with, if I could index and access everything using an array, instead of having to input every index seperated by a comma. So I wrote the following code which provides something like that, however feels very heavy due to only using one large array. I am basically shifting the 'multidimensional' array layers into one huge array... abusing high valued indices. Is there a way to approve apon the code, making it faster, and using less memory and high value calculations?

#include <iostream>
#include <cmath>
#include <array>

using namespace std;

template <class T, size_t depth, size_t each_size>
class MultiArray
{
    array<T, static_cast<size_t>( pow(each_size, depth) )> multiArray;

public:
    MultiArray()
    { ; }

    void put(array<size_t, depth> indices, T thing_to_put)
    {
        size_t index = 0;
        int dimension_counter = 0;
        for (const size_t& i : indices)
        {
                index += i * nearbyint(pow(each_size, dimension_counter));
                dimension_counter++;
        }

        this->multiArray[index] = thing_to_put;
    }

    void get(array<size_t, depth> indices, T &thing_to_get)
    {
        size_t index = 0;
        int dimension_counter = 0;
        for (const size_t& i : indices)
        {
                index += i * nearbyint(pow(each_size, dimension_counter));
                dimension_counter++;
        }
        thing_to_get = this->multiArray[index];
    }
};

if you would like you can find a slightly longer version of the code above with some debugging, simple testing and very basic error handling here.

EDIT: I would like to find a very fast and efficiant way to do things! I would be happy about input on how to get a fast multidimensional array class :) Thank you all for your help!!!


texts: Modeling data from Excel sheets to parse to Excel sheet

texts:
Background:
I have close to 50 excel files - I cannot change the data source - and I steadily get more.
My task is to make sense of all that data and, lo an behold, save that as another excel file (I asked if I should put it in a local database, but no, I should not).
Asking on SO lead me here, as I thought it might be a better fit here, but my problem, if it even is one, is quite specific.

Code:
In my current code I used a couple of classes to model the data; I read somewhere that data should be data and not a class but are dictionaries helpful in this case?
Assembly Class:
Private pPartnumber As String
Private pDescription As String
Private pLevel As Long
Private pSupplier As Supplier
Private pCustomers As CustomerCollection
Private pSubAssemblies As AssemblyCollection
Private pWarehouse As String
Private pEligibility As String
Private pApprovedData As String
Private pApprovedDataBasedOn As String
Private BuyOrMake As AssemblyBuyMake
Public Enum AssemblyBuyMake
    Buy = 0
    Make = 1
    Both = 2
    Other = 4
End Enum
' Lots of getters and setters
' removed for conciseness

Private Sub SetEligibilityOfSubAssemblies(ByVal Value As String)
    Dim subAssembly As Assembly
    If Not pSubAssemblies Is Nothing Then
        For Each subAssembly In pSubAssemblies
            subAssembly.Eligibility = Value
        Next
    End If
End Sub
Private Sub SetApprovedDataOfSubAssemblies(ByVal Value As String)
    Dim subAssembly As Assembly
    If Not pSubAssemblies Is Nothing Then
        For Each subAssembly In pSubAssemblies
            subAssembly.ApprovedData = Value
        Next
    End If
End Sub

'@Description "Checks if Partnumbers are equal, ignores Description- and other deviations"
Public Function Equals(ByVal Assembly As Assembly) As Boolean
    Equals = (pPartnumber = Assembly.Partnumber)
End Function

As you can see my class has lots of fields; the two setter subs are private as any Subassembly automatically inherits the Topassembly's ApprovedData and Eligibility as per requirement.
AssemblyCollection:
Private pAssemblyCollection As Collection
Private Sub Class_Initialize()
    Set pAssemblyCollection = New Collection
End Sub
Public Sub Add(ByVal Value As Assembly, Optional ByVal Key As String)
    '
End Sub
Public Sub Remove(Optional ByVal Value As Assembly, Optional ByVal Key As String)
    '
End Sub

'@DefaultMember
Public Function Item(Optional ByVal index As Long = -1, Optional ByVal Key As String) As Assembly
    '
End Function

'@MemberAttribute VB_MemberFlags, "40"
'@Enumerator
Public Property Get NewEnum() As IUnknown
    Set NewEnum = pAssemblyCollection.[_NewEnum]
End Property

The CustomerCollection looks the same.
Customer:
Private pName As String
Private pID As String
Private pCountry As String
Private pHTSCode As String
' And its getters and setters

'@Description "Returns True if Name, ID and HTSCode are the same"
Public Function Equals(ByVal Customer As Customer) As Boolean
    Equals = (pName = Customer.Name And pID = Customer.ID And pHTSCode = Customer.HTSCode)
End Function

The HTSCode is currently part of the Customer as the file I found it in contains Customer and sales data and barely enough assembly data to identify an assembly - think "customer has a partnumber for an assembly and my files have a partnumber which don't match" and you are just supposed to know which ones refer to the same assembly.

Question:
Instead of using these classes should I use dictionaries of dictionaries?
And for comparing data of different sheets should I store either these classes or dictionaries with the data in new dictionaries or arrays?
I'm not sure if there's a maximum on how many custom objects I can create (other than memory limits), but I fear I'll end up with a lot of Assembly instances in this case.
Currently I
Dim arr() As Assembly

to collect all the data before parsing it to a sheet.


texts: Generate a Bitcoin Address and the Wif from a phrase

texts:
Is there a way to speed up my Python code?

import scrypt
import binascii
from passlib.utils.pbkdf2 import get_prf, pbkdf2
from coinkit import BitcoinKeypair

def getWallet(phrase, saltPhrase):
    s1 = scrypt.hash(password=phrase+'\x01', salt=saltPhrase+'\x01', N=1<<18, r=8, p=1, buflen=32)
    s2 = pbkdf2(phrase+'\x02', saltPhrase+'\x02', 1<<16, keylen=32, prf='hmac-sha256')

    key = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
    key_hex = binascii.hexlify(key)
    newWallet = BitcoinKeypair(key_hex)
    return {"walletAddress":newWallet.address(), "walletWif":newWallet.wif_pk()}

myWallet = getWallet("ER8FT+HFjk0", "a@b.c")
print "Address: "+myWallet["walletAddress"]+"\nWif: "+myWallet["walletWif"]

To try it you need to install these libraries:

pip install scrypt passlib coinkit

This program generates a Bitcoin Address and the Wif from a phrase, but the problem is that it generates the Output in about 1 second, and that's too long. So i'm looking for a way to speed it up, and if there aren't any solutions, perhaps I could use another programming language?

Thank you.


texts: Given an array of numbers, return array of products of all other numbers

texts:
I was recently asked the following interview question over the phone:

  Given an array of integers, produce an array whose values are the
  product of every other integer excluding the current index.

  Example:

  [4, 3, 2, 8] -> [3*2*8, 4*2*8, 4*3*8, 4*3*2] -> [48, 64, 96, 24]

I came up with below code:

  public static BigInteger[] calcArray(int[] input) throws Exception {
    if (input == null) {
      throw new IllegalArgumentException("input is null");
    }

    BigInteger result[] = new BigInteger[input.length];
    for (int i = 0; i < input.length; i++) {
      result[i] = calculateProduct(input, i);
    }
    return result;
  }

  private static BigInteger calculateProduct(int[] input, int exceptIndex) {
    BigInteger result = BigInteger.ONE;
    for (int i = 0; i < input.length; i++) {
      if (i == exceptIndex) {
        continue;
      }
      result = result.multiply(BigInteger.valueOf(input[i]));
    }
    return result;
  }

Complexity:

Time Complexity: O(n)
Space Complexity: O(n)

Is there any better or efficient way to do this apart from what I have so that complexity can be reduced?


texts: Wrapping WinAPI FindNextVolume as std iterator

texts:
This is my first attempt at creating an STL-style iterator. Is this code ok?

std::set<std::wstring> getVolumeNames()
{
    class FindVolumeWrapper : public std::iterator<std::input_iterator_tag, std::wstring>
    {
        WCHAR        m_curVolName[MAX_PATH];
        HANDLE       m_hFindVol;
        DWORD        m_dwError;
    public:
        // start iterator
        FindVolumeWrapper(bool)
            : m_hFindVol(::FindFirstVolumeW(m_curVolName, ARRAYSIZE(m_curVolName)))
            , m_dwError(::GetLastError())
        {
            if (m_hFindVol == INVALID_HANDLE_VALUE && m_dwError != ERROR_NO_MORE_FILES)
            {
                throw AutoWinError(m_dwError);
            }
            if (m_dwError == ERROR_MORE_DATA)
            {
                m_dwError = ERROR_SUCCESS;
            }
        }

        // end iterator
        FindVolumeWrapper()
            : m_hFindVol(INVALID_HANDLE_VALUE)
            , m_dwError(ERROR_NO_MORE_FILES)
        {
            m_curVolName[0] = L'\0';
        }

        FindVolumeWrapper& GetNextVolume()
        {
            BOOL bSuccess = ::FindNextVolumeW(m_hFindVol,
                                              m_curVolName,
                                              ARRAYSIZE(m_curVolName));
            if (!bSuccess)
            {
                m_dwError = ::GetLastError();
                ::FindVolumeClose(m_hFindVol);
                if (m_dwError != ERROR_NO_MORE_FILES)
                {
                    throw AutoWinError(m_dwError);
                }
            }
            return *this;
        }

        FindVolumeWrapper& operator ++ ()
        {
            return GetNextVolume();
        }

        std::wstring operator * ()
        {
            return m_curVolName;
        }

        // equal if either both good and point to same element, or both faulty
        bool operator == (FindVolumeWrapper const& other)
        {
            return (this->m_dwError == ERROR_SUCCESS
                    && other.m_dwError == ERROR_SUCCESS
                    && wcscmp(m_curVolName, other.m_curVolName) == 0)
                 || (this->m_dwError != ERROR_SUCCESS && other.m_dwError != ERROR_SUCCESS);
        }

        bool operator != (FindVolumeWrapper const& other)
        {
            return !operator == (other);
        }
    };

    std::set<std::wstring> volumeNames(FindVolumeWrapper(true), FindVolumeWrapper());

    return volumeNames;
}


texts: Joins on same table with MAX()/MIN() and corresponding fileds

texts:
I made a query for showing max and min value and dates that are corresponding to those MAXs and MINs.

The idea was to show max/min value and the date when the those values occurred in one row for each ticker
The code is below.

SELECT
    po1.ticker, po1.outermindate as outer_min_date,po1.adj_close as min_adj_close,

    po2.ticker, po2.outermaxdate as outer_max_date,po2.adj_close as max_adj_close
FROM
    (
        SELECT pm1.ticker, pm1.date as outermindate , pm1.adj_close  FROM pricesmem as pm1
            JOIN
            (
                SELECT ticker, date as innermindate, min(adj_close)+1-1 as min_close
                FROM pricesmem
                WHERE date BETWEEN "2017-01-01" and "2017-10-03"
                group by ticker
            )
            as pj1
            ON (
                pj1.ticker=pm1.ticker and pj1.min_close=pm1.adj_close
            )

       WHERE pm1.date BETWEEN "2017-01-01" and "2017-10-03"
    )  as po1
LEFT JOIN
    (
        SELECT pm2.ticker, pm2.date as outermaxdate, pm2.adj_close FROM pricesmem as pm2
        JOIN
        (
            SELECT ticker, date as innermaxdate, max(adj_close)+1-1 as max_close
            FROM pricesmem
            WHERE date BETWEEN "2017-01-01" and "2017-10-03"
            group by ticker
        )
        as pj1
        ON (
            pj1.ticker=pm2.ticker and pj1.max_close=pm2.adj_close
        )

       WHERE pm2.date BETWEEN "2017-01-01" and "2017-10-03"
    ) po2
ON po1.ticker=po2.ticker

and the results are correct:

+--------+----------------+---------------+--------+----------------+---------------+
| ticker | outer_min_date | min_adj_close | ticker | outer_max_date | max_adj_close |
+--------+----------------+---------------+--------+----------------+---------------+
| A      | 2017-01-03     | 46.1764       | A      | 2017-09-19     | 66.0356       |
| AA     | 2017-01-09     | 28.3          | A      | 2017-10-03     | 48.31         |
| etc... |                |               |        |                |               |
+--------+----------------+---------------+--------+----------------+---------------+

This way it seems to me that i just join two separate calls to db (not including most inner joins) and i could do same with two calls with any programming lang instead of one sql command.

So is there a better way to make this query?

EDIT:
The DB engine is InnoDB, MySQL 5.6.17 .


texts:
Using this page for a starting point into comparing MD5 hash values from files in two different folders, I've put something together that outputs either Copied if both files MD5 matches or Check if the MD5 hashes do not match.

I want to find out if there's a better method for accomplishing this.

#Requires -version 4.0
Param
  (
    [parameter(Mandatory=$true,Position=1)][string]$source,
    [parameter(Mandatory=$true,Position=2)][string]$dest
  )
$source = gci $srcfolder -File -Recurse | select FullName,@{Label='Hash'; Expression={(Get-FileHash -Algorithm MD5 $psitem.fullname).hash}}
$dest = gci $destfolder -File -Recurse | select FullName,@{Label='Hash'; Expression={(Get-FileHash -Algorithm MD5 $psitem.fullname).hash}}
#compare $source $dest -Property Hash -PassThru
for ($i=0;$i -lt $dest.Count) {
IF($source.Hash[$i] -match $dest.Hash[$i]){
 "Copied $($source[$i].FullName)"}
Else{
 "Check $($source[$i].FullName)"}
$i++
}


texts: Printing log messages with varying length fit into screen width

texts:
I'm writing a simple sanity tool for a simple USB driver.

The customer is directly facing the output so I have to care about how it looks.
The log messages that I need to print are varying length, and they have "[  SUCCESS ]" and "[  FAIL  ]" trailing part too and the middle is filled with dots.

So what I do is calculate the number of dots that should be in the message.
For a example,

#define SCREEN_SIZE_X            80

void print_message(const char* pMsg, bool isPassed)
{
#define SPRINTF_BUFFER_SIZE    1024
    char* sprintfBuffer=(char*) malloc(SPRINTF_BUFFER_SIZE);
    int iLengthMsg = strlen( pMsg);
    const char* strTrailingPart= isPassed?"[  PASSED  ]":\
                     "[  FAILED  ]";
    int iLengthTrailingPart=strlen(strTralingPart);
    int iNumDots= SCREEN_SIZE_X - iLengthMsg - iLengthTrailingPart;

    sprintf( sprintfBuffer,pMsg);

    for(int i=0; i< iNumDots; i++)
    {
        sprintf( sprintfBuffer+strlen( sprintfBuffer),\
                  "%c" , '.');
    }

    sprintf(sprintfBuffer+strlen(sprintfBuffer), \
                 strTrailingPart);
    printf( sprintfBuffer);
    free (sprntfBuffer);
}

Any better way to do this thing?


texts: Find all occurrences of the word "the" without using regex

texts:
I have an assignment to find all occurrences of the word "the" without using regex:

  Use the indexOf method to do this. The word "the" could also appear in a larger word, such as "Theresa" or "other".

Please confirm if this is the best way to do that.

import java.util.Scanner;

public class TheFinder
{
    public static void main(String[] args)
    {
        int theCounter;
        int indexOfThe = 0;

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentence with a word \"the\" or type \"quit\" to quit: ");
        String sentence = input.nextLine();

        while(!(sentence.equalsIgnoreCase("quit")))
        {
            theCounter = 0;
            sentence = sentence.toLowerCase();

            while(sentence.contains("the"))
            {
                ++theCounter;
                sentence = sentence.substring((sentence.indexOf("the") + 3), sentence.length());
            }
            if(theCounter > 0)
            {
                System.out.println("The number of times \"the\" appears in the sentence is " + theCounter + ".");
            }
            else
            {
                System.out.println("There is no word \"the\" in the sentence");
            }

            System.out.print("Please enter a sentence with a word \"the\" or type \"quit\" to quit: ");
            sentence = input.nextLine();
        }
    }
}


texts: Duplicate code in similar classes where I cannot add more inheritance

texts:
I'm building a .NET Linq-esc query builder for my application and I'm wondering about my implementation and code structure when it comes a few classes.

Basically I'm creating a query builder for SQL, and I need for my classes to be able to using the following behavior:

query.Select(...).From(...).Join(...).Where(...);

I have created 6 Interfaces that contain one method each that donates what can be done to that class E.G the Select class would implement IFromAble which contains the method From(..). This allows the behavior above.

This is the same for all of the other classes above and a few more. Some classes, like Join will implement a few of the interfaces E.g IJoinAble, IWhereAble, IOrderAble, IGroupAble, IHavingAble.

This, as you can imagine will lead to a lot of duplicated code throughout each of my classes.

Each of the classes also implement a common base abstract class, which means I cannot use abstracts to solve the issue.

Is there another way I can implement my intended behavior without all of the duplicated code? Or is this just one of those cases I'm once again tripped up by C#'s single inheritance?

The Join Class

public class ModuleJoin : QueryModule, IJoinAble, IWhereAble, IOrderAble, IGroupAble
{
    public JoinType JoinType { get; set; }
    public QueryField JoinFrom
    {
        get { return (QueryField)this.Fields[0]; }
        set { this.Fields[0] = value; }
    }
    public QueryField JoinTo
    {
        get { return (QueryField)this.Fields[1]; }
        set { this.Fields[1] = value; }
    }

    public ModuleJoin(Query query, JoinType joinType, QueryField joinFrom, QueryField joinTo)
    {
        this.PerentQuery = query;
        this.Fields.Clear();
        this.Fields.Add(joinFrom);
        this.Fields.Add(joinTo);
        JoinType = joinType;
    }

    public ModuleJoin Join(JoinType joinType, QueryField joinFrom, QueryField joinTo)
    {
        ModuleJoin join = new ModuleJoin(this.PerentQuery, joinType, joinFrom, joinTo);
        this.PerentQuery.ModuleJoins.Add(join);
        return join;
    }

    public ModuleWhere Where(IFieldPart itemOne, Comparator comparator, IFieldPart itemTwo)
    {
        ModuleWhere where = new ModuleWhere(this.PerentQuery, itemOne, comparator, itemTwo);
        this.PerentQuery.ModuleWheres.Add(where);
        return where;
    }

    public ModuleGroupBy GroupBy(params IFieldPart[] fields)
    {
        ModuleGroupBy groupBy = new ModuleGroupBy(this.PerentQuery, fields);
        this.PerentQuery.ModuleGroupBy = groupBy;
        return groupBy;
    }
}

QueryModule (The interface on this just has those properties)

public abstract class QueryModule : IQueryModule
{
    public Query PerentQuery { get; set; }
    public FieldCount FieldCount { get; set; }
    public List<IFieldPart> Fields { get; set; }
    public IFieldPart Field
    {
        get { return Fields[0]; }
        set
        {
            if (Fields.Count == 1)
                Fields[0] = value;
            else
                Fields.Add(value);
        }
    }

    public QueryModule()
    {
        this.Fields = new List<IFieldPart>();
    }
}

IJoinAble (An example of one of the interfaces)

interface IJoinAble
{
    ModuleJoin Join(JoinType joinType, QueryField joinFrom, QueryField joinTo);
}


texts:
There are things that I am not 100% sure.
Is it possible that dangling references can be create in add_task method?
Is it possible that this implementation will deadlock?
I had to use shared_ptr in order to store packaged_task in the queue. Is there a better way to do it?
class ThreadPool {
public:
    ThreadPool(int number_of_workers) {
        for (int i=0; i<number_of_workers; ++i) {
            worker_threads.push_back(std::thread{std::bind(&ThreadPool::thread_func, this)});
        }
    }

    ~ThreadPool() = default;

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool(ThreadPool&&) = delete;
    ThreadPool& operator=(const ThreadPool&) = delete;
    ThreadPool& operator=(ThreadPool&&) = delete;

    template<typename Func, typename... Args>
    decltype(auto) add_task(Func&& func, Args... args) {
        using ReturnType = decltype(func(args...));
        auto ptask = std::make_shared<std::packaged_task<ReturnType()>>(
            std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
        auto fut = ptask->get_future();
        {
            std::unique_lock lk{pool_mutex};
            task_queue.push([pt = std::move(ptask)]() { (*pt)(); });
        }
        cond.notify_one();
        return fut;
    }

    void stop() {
        {
            std::unique_lock lk{pool_mutex};
            stopped = true;
        }
        cond.notify_all();
        for (auto& th : worker_threads) {
            if (th.joinable()) {
                th.join();
            }
        }
    }

private:
    void thread_func() {
        while(true) {
            std::unique_lock lk{pool_mutex};
            if (task_queue.empty() && stopped) {
                break;
            }

            if (task_queue.empty()) {
                cond.wait(lk, [this]() { return !task_queue.empty() || stopped; });
            }

            if (!task_queue.empty()) {
                auto callable = std::move(task_queue.front());
                task_queue.pop();
                lk.unlock();
                callable();
            }
            else if (stopped) {
                break;
            }
        }
    }

private:
    std::mutex pool_mutex;
    std::vector<std::thread> worker_threads;
    bool stopped = false;
    std::condition_variable cond;
    std::queue<std::function<void()>> task_queue;
};

Note, that add_task returns a future that can be used to wait for a specific task to complete.


texts:
I am new to c#, and rather new to design-patterns. I want to create a simple and a most elegant solution for loading and validating a xml file and later on extracting its fields.
I've started with a generic IData interface, that gets implemented by a XmlFileData class, but I feel that there is much more to be improved upon, but I lack the knowledge to do it (from design, to naming variables and methods and so on).

So please, have no mercy !!

public interface IData
{
     String GetDataString();
}

class XMLValidator
    {
        private StringBuilder verificationErrorsList = new StringBuilder();
        public string ValidationSchema { get; set; }
        public String ValidationErrors
        {
            get { return verificationErrorsList.ToString(); }
        }
        public bool HasErrors
        {
            get {return (verificationErrorsList.Length > 0);}
        }

        public void Validate(IData xmlData)
        {
            try
            {
                XmlWriterSettings ws = new XmlWriterSettings();
                ws.Indent = true;

                XmlReaderSettings rs = new XmlReaderSettings();
                rs.ValidationType = ValidationType.Schema;
                rs.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(rs_ValidationEventHandler);
                rs.Schemas.Add(null, ValidationSchema);
                rs.CloseInput = true;

                rs.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings |  XmlSchemaValidationFlags.ProcessIdentityConstraints |
                               XmlSchemaValidationFlags.ProcessInlineSchema |  XmlSchemaValidationFlags.ProcessSchemaLocation;

                StringReader r = new StringReader(xmlData.GetDataString());
                using (XmlReader reader = XmlReader.Create(r, rs))
                {
                    try
                    {
                        while (reader.Read()) { }
                    }
                    catch (XmlException e)
                    {
                        verificationErrorsList.Append(e.Message);
                        verificationErrorsList.Append(Environment.NewLine);
                    }

                }
            }
            catch (XmlSchemaValidationException e)
            {
                verificationErrorsList.Append(e.Message + Environment.NewLine);
            }
        }
        void rs_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
            {
                verificationErrorsList.Append(e.Message + Environment.NewLine);
            }
        }
    }

Usage:

        IData data = new XmlFileData(basepathXML + fileNameXML);
        XMLValidator validator = new XMLValidator();
        validator.ValidationSchema = basepathXML + fileNameXSD;
        validator.Validate(data);
        if (validator.HasErrors)
        {
            Console.WriteLine(validator.ValidationErrors);
        }
        else
        {
            Console.WriteLine("Success");
        }


texts:
How does this class to resize an image look?

using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.IO;

/*
 * Resizes an image
 **/
public static class ImageResizer
{
    // Saves the image to specific location, save location includes filename
    private static void saveImageToLocation(Image theImage, string saveLocation)
    {
        // Strip the file from the end of the dir
        string saveFolder = Path.GetDirectoryName(saveLocation);
        if (!Directory.Exists(saveFolder))
        {
            Directory.CreateDirectory(saveFolder);
        }
        // Save to disk
        theImage.Save(saveLocation);
    }

    // Resizes the image and saves it to disk.  Save as property is full path including file extension
    public static void resizeImageAndSave(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)
    {
        Image thumbnail = resizeImage(ImageToResize, newWidth, maxHeight, onlyResizeIfWider);
        thumbnail.Save(thumbnailSaveAs);
    }
    // Overload if filepath is passed in
    public static void resizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)
    {
        Image loadedImage = Image.FromFile(imageLocation);
        Image thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);

        saveImageToLocation(thumbnail, thumbnailSaveAs);
    }

    // Returns the thumbnail image when an image object is passed in
    public static Image resizeImage(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider)
    {
        // Prevent using images internal thumbnail
        ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        // Set new width if in bounds
        if (onlyResizeIfWider)
        {
            if (ImageToResize.Width <= newWidth)
            {
                newWidth = ImageToResize.Width;
            }
        }

        // Calculate new height
        int newHeight = ImageToResize.Height * newWidth / ImageToResize.Width;
        if (newHeight > maxHeight)
        {
            // Resize with height instead
            newWidth = ImageToResize.Width * maxHeight / ImageToResize.Height;
            newHeight = maxHeight;
        }

        // Create the new image
        Image resizedImage = ImageToResize.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);

        // Clear handle to original file so that we can overwrite it if necessary
        ImageToResize.Dispose();

        return resizedImage;
    }
    // Overload if file path is passed in instead
    public static Image resizeImage(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider)
    {
        Image loadedImage = Image.FromFile(imageLocation);
        return resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);
    }
}


texts: Auto change page title while bookmarking a page

texts:
Here is what I'm trying:

Please review the code:

function quicklyChangePageTitle() {
  var currentTitle = document.title; // remember original title
  document.title = "temp title"; // change to the temporary title

  setTimeout(function() { // revert back to original title
    document.title = currentTitle;
  }, 1);

}
document.addEventListener("keydown", function(event) {
  if (event.ctrlKey && event.keyCode == 68) { // Ctrl + D
    quicklyChangePageTitle();
  }
});


texts: Is there anything wrong with this double ternary?

texts:
Is there anything wrong with using double ternary operator like so:

var stateName:String = state is String ? state as String : "name" in state ? state.name : null;

Here is two lines because someone requested it:

var stateName:String = state is String ? state as String :
                        "name" in state ? state.name :
                            null;

Here is the alternative:

if (state is String) {
    stateName = state as String;
}
else if ("name" in state) {
    stateName = state.name;
}
else {
    stateName = null;
}

The function:

/**
 * Sets the style in the state specified. Creates state if it doesn't exist.
 * */
public static function setStyleInState(styleName:String, value:*, state:*, target:UIComponent = null):void {
    var stateName:String = state is String ? state as String : "name" in state ? state.name : null;

    if (!StateUtils.hasState(target, state)) {
        state = createState(stateName, null, target);
    }
    else if (!(state is State)) {
        state = getState(target, stateName);
    }

    // more code to write
}

It makes sense to me but I'm the one writing it.

This is ActionScript3 or ECMAScript 4 (basically JavaScript with strong typing).


texts: Managing "active" and "rest" state for class name-based CSS animations

texts:
Started working with CSS animations and I'm wondering if there's a more elegant way to manage (with class names) when an animation is on or off. The general pattern I have is like this:

I really dislike the idea of having a css class for base-class-rest that is different than just the base-class. I came up with this solution because I needed a css state that animates from the end of the base-class-active state back to a state of "rest". base-class alone cannot achieve this because there is no animation defined in its css.

tl;dr: I'm toggling a color on and off but I've written too much code for a task this simple. How can I write less code?

Here's a pen: http://codepen.io/anon/pen/GpaJQa

html

css

@keyframes box-active {
    0% { background-color: black; }
    100% { background-color: green; }
}

@keyframes box-rest {
    0% { background-color: green; }
    100% { background-color: currentColor; }
}

.box {
    height: 50px;
    width: 50px;
    background-color: black;
    display: inline-block;
    margin: 5px;
}

.box-active {
    animation: box-active 1s 1 forwards;
}

.box-rest {
    animation: box-rest 1s 1 forwards;
}

js

Array.prototype.slice.call(document.querySelectorAll(".box")).forEach(function(el) {
    el.addEventListener("click", click("box", "box-rest", "box-active"));
});

function click(none, rest, active) {
    return function(e) {
        var classname = e.target.className;
        var arr = classname.split(" ");
        var index = [arr.indexOf(none), arr.indexOf(rest), arr.indexOf(active)];
        //no state
        if (index[1] < 0 && index[2] < 0) {
            arr.push(active);
            return e.target.className = arr.join(" ");
        }
        //at rest
        if (index[2] > -1) {
            arr.splice(index[1], 1);
            arr.push(rest);
        }
        //active
        else {
            arr.splice(index[2], 1);
            arr.push(active);
        }
        e.target.className = arr.join(" ");
    };
}


texts: Issue tokens concurrently with synchronization per client

texts:
I have an API application with token authorization. A token is valid for one hour. Each business client has its own instance of the API application:

{"client_1": "http://localhost:1"},
...
{"client_n": "http://localhost:n"}

In another application I have a class ApiService to make HTTP requests to the API. I create one instance of ApiService. Requests happen concurrently and I want to be sure that for each client token will be issued only once. I use Flurl to make HTTP requests.

public class TokenDetails
{
    public string Token { get; set; }
    public DateTime Expires { get; set; }
}

public class ClientDetails
{
    public string ClientId { get; set; }
    public string BaseAddress { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

public class ClientService
{
    private readonly ConcurrentDictionary<string, Task<TokenDetails>> _tokens =
        new ConcurrentDictionary<string, Task<TokenDetails>>();

    private readonly ConcurrentDictionary<string, object> _locks =
        new ConcurrentDictionary<string, object>();

    public async Task<string> GetDataAsync(ClientDetails client)
    {
        var token = await GetTokenAsync(client).ConfigureAwait(false);

        return await new Url(client.BaseAddress).AppendPathSegment("/data")
            .WithOAuthBearerToken(token.Token)
            .GetStringAsync().ConfigureAwait(false);
    }

    private Task<TokenDetails> GetTokenAsync(ClientDetails client)
    {
        //try find valid token task
        if (!_tokens.TryGetValue(client.ClientId, out var tokenTask)
            || tokenTask.IsFaulted
            || tokenTask.IsCanceled
            || (tokenTask.IsCompleted && tokenTask.Result.Expires < DateTime.UtcNow))
        {
            //token task not found or token is expired - enter lock to make http call
            var lockObject = _locks.GetOrAdd(client.ClientId, id => new object());
            lock (lockObject)
            {
                //try find valid token task again after aquiring lock
                if (!_tokens.TryGetValue(client.ClientId, out tokenTask)
                    || tokenTask.IsFaulted
                    || tokenTask.IsCanceled
                    || (tokenTask.IsCompleted && tokenTask.Result.Expires < DateTime.UtcNow))
                {
                    //http call
                    tokenTask = new Url(client.BaseAddress).AppendPathSegment("/login")
                        .WithBasicAuth(client.Username, client.Password)
                        .GetJsonAsync<TokenDetails>();
                    _tokens.AddOrUpdate(client.ClientId, key => tokenTask, (key, oldToken) => tokenTask);
                }

            }
        }

        return tokenTask;
    }
}


texts: Project Euler Problem #3 - largest prime factor

texts:
I have began doing the problems found on Project Euler and have just solved problem 3. However, I feel as if my code is very long and too brute-force. I was hoping somebody could give it a look and give me some guidelines for this problem and for future programming in general.  This would help me with cleaning it up or even just revealing better ways of solving this.

Problem 3 states:

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of the number 600851475143?

int primeFactor = 0;
int pfCounter = 0;
int[] pf = new int [1229];
int[] numbers = new int[10000];
long number = 600851475143L;
int p = 0;

//initialize the array numbers to include all numbers
//from 1 to 1000 for determining prime numbers
for(int i = 0; i < numbers.length; i++)
{
    numbers[i] = i+1;
}

//determining which numbers are prime numbers
for(int i = 0; i <numbers.length; i++)
{
    //divide each number by every number below it
    //to see if the pfCounter = 1 which would mean
    //it is only divisible by itself and 1
    for(int j = i; j > 0; j--)
    {
        if(numbers[i] % j == 0)
        {
            pfCounter++;
        }
    }

    //if the number only has 1 in it's pfCounter
    //insert the number from the numbers array into the
    //pf array and restart the counter to 0 else restart
    //the counter to 0 and try again
    if(pfCounter == 1)
    {
        pf[p] = numbers[i];
        pfCounter = 0;
        p++;
    }
    else
    {
        pfCounter = 0;
    }

}

/*
for(p = 0; p < pf.length; p++)
{
    System.out.println(pf[p]);
}*/

for(int i = 0; i < pf.length; i++)
{
    if(number % pf[i] == 0)
    {
        primeFactor = pf[i];
    }
}

System.out.println(primeFactor);


texts:
I have been looking into stuff like method chaining, Cascade-Lambda pattern etc.

I have created a class which seems to work fine. However, I just wanted to confirm if this is the best way and the right way to implement this.

For the cascade lambda pattern I was unable to use Action action as a parameter to the Send() method. I couldn't figure out how would I use it.

Any suggestions are welcome.

Here is the code:

public class MailManager
{
    MailMessage _mail { get; set; }
    SmtpClient _smtp { get; set; }

    public MailManager()
    {
        _mail = new MailMessage();
        _smtp = new SmtpClient();
    }

    public MailManager To(string address)
    {
        _mail.From = new MailAddress(address);
        return this;
    }

    public MailManager From(string address)
    {
        _mail.To.Add(new MailAddress(address));
        return this;
    }

    public MailManager Subject(string subject)
    {
        _mail.Subject = subject;
        return this;
    }

    public MailManager Body(string body)
    {
        _mail.Body = body;
        return this;
    }

    public MailManager IsBodyHtml(bool isBodyHtml = true)
    {
        _mail.IsBodyHtml = isBodyHtml;
        return this;
    }

    public MailManager AlternateViews(AlternateView alternateView)
    {
        _mail.AlternateViews.Add(alternateView);
        return this;
    }

    public MailManager Host(string host)
    {
        _smtp.Host = host; return this;
    }

    public MailManager Port(int port)
    {
        _smtp.Port = port; return this;
    }

    public MailManager Credentials(NetworkCredential credentials)
    {
        _smtp.Credentials = credentials; return this;
    }

    public MailManager EnableSsl(bool enableSsl = true)
    {
        _smtp.EnableSsl = enableSsl; return this;
    }

    public void Send()
    {
        using (_smtp)
        {
            _smtp.Send(_mail);
        }
    }
}

This is how I use it:

mailManager.From(_emailSettings.Email)
           .To(item.Email)
           .Subject(string.Format(_emailSettings.Subject, item.Name)).AlternateViews(htmlView)
           .Body(body).IsBodyHtml()
           .Host(_emailSettings.Domain)
           .Port(_emailSettings.Port)
           .Credentials(new NetworkCredential(_emailSettings.Email, _emailSettings.Password))
           .EnableSsl()
           .Send();


texts: Replacing removed secure empty trash feature

texts:
Is this code reliable? Is there any extra precaution I should or should not be taking here? How is my code to securely delete a file by repeatedly overwriting the contents?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int Argc, const char *Argv[]) {
    srand(time(NULL));
    unsigned int *RandBuf = NULL;
    for (int I = 1; I < Argc; I++) {
        long FileSize;
        const char *const Path = Argv[I];
        FILE *const File = fopen(Path, "r+");
        if (!File || fseek(File, 0, SEEK_END) || (FileSize = ftell(File)) < 0) {
            perror(Path);
            continue;
        }
        const unsigned long IntCount = (FileSize+3)>>2;
        RandBuf = realloc(RandBuf, IntCount<<2);
        const unsigned char WriteCount = ((unsigned int)rand()&0xF)+16;
        for (unsigned char Write = 0; Write < WriteCount; Write++) {
            for (unsigned long Int = 0; Int < IntCount; Int++) {
                RandBuf[Int] ^= (unsigned int)rand();
            }
            if (fseek(File, 0, SEEK_SET) || fwrite(RandBuf, 1, FileSize, File) < FileSize) {
                perror(Path);
                continue;
            }
        }
        if (fclose(File) || remove(Path)) {
            perror(Path);
            continue;
        }
    }
    free(RandBuf);
    return 0;
}


texts: Multicast Socket Configuration for Pub/Sub

texts:
I have a set of components that each need to both publish and receive messages using a multicast channel. In production, any one machine could host two or more of these components with 12 or more machines communicating with each other.

My question is... given that components on the same machine and components on separate machines are both sending and received. Have I set this up in the most efficient manner? (Note: messages can periodically be lost with no ill effect)

private readonly static Socket _broadcastSocket;

private readonly static Socket _broadcastListeningSocket;

_broadcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

_broadcastListeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

IPAddress ip = IPAddress.Parse(_configuration.Server.AddressV4);
var ipep = new IPEndPoint(ip, _configuration.Server.Port);

_broadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
_broadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, _configuration.Server.TimeToLive);
_broadcastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
_broadcastSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
_broadcastSocket.Connect(ipep);

var listenerIpep = new IPEndPoint(IPAddress.Any, _configuration.Server.Port);

_broadcastListeningSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
_broadcastListeningSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
_broadcastListeningSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
_broadcastListeningSocket.Bind(listenerIpep);

Messages are received using this following:

_broadcastListeningSocket.Receive(payloadBuffer);

Messages are sent using the following:

if (_broadcastSocket.Connected)
{
    _broadcastSocket.Send(payload);
}

I'm a little new to this so I am assuming I am not setting all the options correctly, feel free to suggest setting of new options.


texts: Entity Framework Lazy loading performance comparison

texts:
The following code takes about 20 seconds to run with about 200,000 records in the TaskLogs table:

using (var db = new DAL.JobManagerEntities())
    {
        return db.TaskLogs.Select(taskLog => new TaskLog()
        {
            TaskLogID = taskLog.TaskLogID,
            TaskID = taskLog.TaskID,
            TaskDescription = taskLog.Task.TaskDescription,
            TaskType = (TaskType)taskLog.Task.TaskTypeID,
            RunID = taskLog.RunID,
            ProcessID = taskLog.ProcessID,
            JobID = taskLog.JobID,
            JobName = taskLog.Job.JobName,
            Result = taskLog.Result,
            StartTime = taskLog.StartTime,
            TimeTaken = taskLog.TimeTaken
        }).OrderByDescending(t => t.RunID).ThenByDescending(t => t.RunID).ThenByDescending(t => t.StartTime).ToList();
    }

I tweaked it until I got something that runs faster. Here's where I got to:

            using (var db = new DAL.JobManagerEntities())
    {
        db.Configuration.LazyLoadingEnabled = false;
        var tasks = db.Tasks.ToList();
        var jobs = db.Jobs.ToList();
        var result = db.TaskLogs.Select(x => new TaskLog()
        {
            TaskLogID = x.TaskLogID,
            TaskID = x.TaskID,
            RunID = x.RunID,
            ProcessID = x.ProcessID,
            JobID = x.JobID,
            Result = x.Result,
            StartTime = x.StartTime,
            TimeTaken = x.TimeTaken
        }).OrderByDescending(t => t.RunID).ThenByDescending(t => t.StartTime).ToList();

        foreach (var r in result)
        {
            r.TaskDescription = tasks.Single(t => t.TaskID == r.TaskID).TaskDescription;
            r.TaskType = (TaskType)tasks.Single(t => t.TaskID == r.TaskID).TaskTypeID;
            r.JobName = jobs.Single(j => j.JobID == r.JobID).JobName;
        }
        return result;}

Which runs in less than 6 seconds for the same number of records.

The TaskLog table is linked to the Job and Task tables as follows:

The Job and Task tables will have 100s and 1000s of records respectively.

Is there anything else I could do in order to further improve the efficiency of the code?


texts:
I have developed a tic-tac-toe game in native JavaScript.
Can you tell me how to optimize more and what are the missing things? JSBIN

The logic, modular approach, testable and scalable?

(function() {
  var playerOneData = {
    name: null,
    arr: []
  };
  var playerTwoData = {
    name: null,
    arr: []
  };
  winnerFound = false;
  var clickCount = 2;

  var start = document.getElementById('start');
  var resultsList = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  var setApplicationView = function(screenId, display) {
    //     hide user infor form
    document.getElementById(screenId).style.display = display;
  };
  start.addEventListener('click', function() {
    //     fetch username
    playerOneData.name = document.getElementById('player-one-name').value;
    playerTwoData.name = document.getElementById('player-two-name').value;
    //     hide user info form
    setApplicationView('user', 'none');
    //     show game board
    setApplicationView('game-board', 'block');
    //     set the player's name
    document.querySelector('#p1-info span').innerHTML = playerOneData.name;
    document.querySelector('#p2-info span').innerHTML = playerTwoData.name;
  });

  var ifClicked = function(index, tile) {
    var i = 0;
    while (i < tile.length) {
      if (index == tile[i])
        return false;
      i++;
    }
    return true
  };
  var selectedTiles = [];

  var winnerFinder = function(playersData, resultsList) {
    if(playersData.arr.length<2) return true;
    var player = playersData.arr;
    var i = 0;
    resultsList.forEach(function(element) {
      i = 0;
      player.forEach(function(ele) {
        if (element.indexOf(ele) >= 0) {
          i++;
        }
      });
      if (i == element.length) {
        matrix.removeEventListener('click', startMatrix);
        document.getElementById('result').innerHTML = "Winner is " + playersData.name;
        winnerFound = true;
        return false;
      }
    });
  };
  var matrix = document.getElementById('matrix');
  var startMatrix = function($event) {
    var target = $event.target;
    var tileIndex = +target.getAttribute('tile-index');
    var alreadyClickedStatus = ifClicked(tileIndex, selectedTiles);
    if (target.className === 'tile' && alreadyClickedStatus === true) {
      selectedTiles.push(tileIndex);

      if (clickCount % 2 === 0) {
        playerOneData.arr.push(tileIndex);
        target.className = 'tile red';

        if (winnerFinder(playerOneData, resultsList) === false) {
          matrix.removeEventListener('click', startMatrix);
        }
      } else {
        playerTwoData.arr.push(tileIndex);
        target.className = 'tile blue';
        if (winnerFinder(playerTwoData, resultsList) === false) {
          matrix.removeEventListener('click', startMatrix);
        }
      }

      clickCount++;
      if (clickCount === 11 && winnerFound === false) {
        document.getElementById('result').innerHTML = 'Match drawn';
      }
    }
  }
  matrix.addEventListener('click', startMatrix);
  var resetBoard = function() {
    winnerFound = false;
    clickCount = 2;
    matrix.addEventListener('click', startMatrix);
    document.getElementById('result').innerHTML = '';
    selectedTiles = [];
    var tile = document.querySelectorAll('.tile')
    tile.forEach(function(ele, index) {
      tile[index].className = 'tile';
    });
    playerOneData.arr = [];
    playerTwoData.arr = [];
  };
  var restart = document.getElementById('restart');
  restart.addEventListener('click', function() {

    resetBoard();
  });
  var newGame = document.getElementById('new-game');
  newGame.addEventListener('click', function() {
    //     show user info form
    setApplicationView('user', 'block');
    //     hide game board
    setApplicationView('game-board', 'none');
    resetBoard();
  });
})();


texts:
For an interview question, I was asked to do the following:

  Given a dot separated domain name, reverse the domain elements.

Here are a few input/output examples:

codereview.stackexchange.com -> com.stackexchange.codereview
foo.bar -> bar.foo
a.. -> ..a

This was my proposed solution. I really feel like there's probably a better way to do this (in place?).

#include <iostream>
#include <string>

std::string
reverse(const std::string &str)
{
    std::string rstr = str;
    std::reverse(rstr.begin(), rstr.end());
    int size = rstr.size();
    int start = 0;
    int end = 0;
    while (end != size + 1) {
        if (rstr[end] == '.' || end == size) {
            std::reverse(rstr.begin() + start, rstr.begin() + end);
            start = end + 1;
        }
        ++end;
    }
    return rstr;
}

int
main()
{
    std::string examples[] = {
        "hello.world",
        "com.domain.something",
        "..a"
    };

    int size = sizeof(examples) / sizeof(examples[0]);
    for (int i = 0; i < size; ++i) {
        std::cout << examples[i] << " -> " << reverse(examples[i]) << std::endl;
    }

    return 0;
}


texts:
I am solving this problem on SPOJ Upper Right King (Hard):

  There is a king in the lower left corner of the \$ n \times n \$ chess board. The king can move one step right, one step up or one step up-right. How many ways are there for him to reach the upper right corner of the board? Give the answer modulo 1000003.

The numbers to be output are the central Delannoy numbers.

I've written a solution in Python with a time complexity of \$ O(n(\log m)^2) \$.  But it's showing "time limit exceeded".  Can anyone help me out with this?

import math
MAX = 10000002
MOD = 1000003

# Extended euclidean algorithm for modular inverse

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        return 0
    else:
        return x % m

t = raw_input()
t = long(t)

fact = []

for i in range(0,MAX):
    fact.append(0)
fact[0]=1
fact[1]=1
for i in range(2,MAX):
    fact[i] = (i%MOD * fact[i-1]%MOD)%MOD

while t:
    n = raw_input()
    n = long(n)
    n = n-1
    Sum = 1
    prod = ((n+1)%MOD * (n)%MOD)%MOD
    increment = n+1
    decrement = n
    Sum = (Sum%MOD + prod%MOD)%MOD

    for k in range(0,n-1):
        temp_prod = (prod%MOD * (increment+1)%MOD * (decrement-1)%MOD)%MOD
        prod = temp_prod
        fct = fact[k+2]
        fat2 = (fct%MOD * fct%MOD)%MOD
     #   print fat2,modinv(fat2,MOD)
        result = (temp_prod%MOD * modinv(fat2,MOD))%MOD
        Sum = (Sum%MOD + result%MOD)%MOD
        increment = increment + 1
        decrement = decrement - 1

    print "%ld" %(Sum)
    t = t-1

How can I reduce the complexity of this problem in order to have it accepted?