texts:
The following code works great but take too much time. placeQueens requires much time too.  The program takes 5-10 seconds.

public class EightQueen {

    public static void startSimulation(){

        long startTime = System.currentTimeMillis();
        char[] board; // Create an array

        // Repeat while queens are attacking
        do {
            // Generate a board
            board = getNewBoard();

            // Place eight queens
            placeQueens(board);

        } while (isAttacking(board));

        // Display solution
        print(board);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }

    /** placeQueens randomly places eight queens on the board*/
    public static void placeQueens(char[] board) {
        int location;
        for (int i = 0; i < 8; i++) {
            do {
                location = placeQueens();
            } while (isOccupied(board[location]));
            board[location] = 'Q';
        }
    }

    /** placeQueens randomly places one queen on the board */
    public static int placeQueens() {
        return (int)(Math.random() * 64);
    }

    /** isAttacking returns true if two queens are attacking each other */
    public static boolean isAttacking(char[] board) {
        return isSameRow(board) || isSameColumn(board) ||  isSameDiagonal(board);
    }

    /** isSameRow returns true if two queens are in the same row */
    public static boolean isSameRow(char[] board) {
        int[] rows = new int[8];
        for (int i = 0; i < board.length; i++) {
            if (isOccupied(board[i])) {
                rows[getRow(i)]++;
            }
            if (rows[getRow(i)] > 1)
                return true;
        }
        return false;
    }

    /** isSameColumn returns true if two queens are in the same column */
    public static boolean isSameColumn(char[] board) {
        int[] columns = new int[8];
        for (int i = 0; i < board.length; i++) {
            if (isOccupied(board[i])) {
                columns[getColumn(i)]++;
            }
            if (columns[getColumn(i)] > 1)
                return true;
        }
        return false;
    }

    /** isSameDiagonal returns true if two queens are on the same diagonal */
    public static boolean isSameDiagonal(char[] board) {
        for (int i = 0; i < board.length; i++) {
            if (isOccupied(board[i])) {
                for (int j = 0; j < board.length; j++) {
                    if (isOccupied(board[j]) && Math.abs(getColumn(j) - getColumn(i)) ==
                            Math.abs(getRow(j) - getRow(i)) && j != i) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /** isOccupied returns true if the element in x is the char Q */
    public static boolean isOccupied(char x) {
        return x == 'Q';
    }

    /** getNewBoard returns a char array filled with blank space */
    public static char[] getNewBoard() {
        char[] board = new char[64];
        for (int i = 0; i < board.length; i++)
            board[i] = ' ';
        return board;
    }

    /** print displays the board */
    public static void print(char[] board) {
        for (int i = 0; i < board.length; i++) {
            System.out.print(
                    "|" + ((getRow(i + 1) == 0) ? board[i] + "|\n" : board[i]));
        }
    }

    /** getRow returns the row number that corresponds to the given index */
    public static int getRow(int index) {
        return index % 8;
    }

    /** getColumn returns the column number that corresponds to the given index */
    public static int getColumn(int index) {
        return index / 8;
    }
 }


texts: My included in every script file - follow-up -2 (the front controller)

texts:
This question is a sub-post to this question

This post is a follow up for this and this.

"In this particular question I need the reviewers help to judge my front controller design pattern"

.htaccess file

it's purpose is to internally redirect to the front controller file

RewriteEngine On
RewriteCond "%{REQUEST_URI}" "!=/frontController.SE.php"
RewriteCond %{REQUEST_FILENAME} !^.*\.js$
RewriteCond %{REQUEST_FILENAME} !^.*\.css$
RewriteCond %{REQUEST_FILENAME} !^.*\.ico$
RewriteCond %{REQUEST_URI} !^/media/.*$
RewriteRule .* /frontController.SE.php [L]

frontController.SE.php

The front controller will receive the request and decide 2 things :

what is the action name intended by the request .
which sub controller knows how to handle that action and then
include it.

(I'm planing to expand the front controller functionalities later to do things like logging the requests, blocking requests,.. etc). the controllers files have names like "/name.SE.php" SE is for "side effects" since PSR stated that a php file must either has definitions or do side effects. the controllers files has functions inside it with names exactly the same name as the action name that the is requested.

<?php
namespace aap;

require_once 'classes/AutoLoader.class.php';
$autoLoader = new AutoLoader($_SERVER["DOCUMENT_ROOT"] . "classes/", "aap\\");
$autoLoader->register();

$sysModel = new SystemModel();
$frontController = new FrontController();

$subController = $frontController->getSubController();

if ($subController) {
    include $frontController->getSubControllerFile();
} else {
    die("bad Rrequest");
}

FrontController.class.php

<?php
namespace aap;

class FrontController
{

    protected $subController = "";

    protected $subControllerFile = "";

    protected $action = "";

    public function __construct()
    {
        $path = trim(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/");
        $pathParts = explode("/", $path);

        switch ($pathParts[0]) {
            // name/home
            case "home":
            case "":
                $this->subController = "home";
                $this->subControllerFile = "home.SE.php";
                $this->action = "show";
                break;
            // name/about
            case "about":
                $this->subController = "about";
                $this->subControllerFile = "about.SE.php";
                $this->action = "show";
                break;
            // name/contact/send
            // name/contact
            case "contact":
                $this->subController = "contact";
                $this->subControllerFile = "contact.SE.php";
                if (! empty($pathParts[1]) && $pathParts[1] == "send" && $_SERVER['REQUEST_METHOD'] == "POST") {
                    $this->action = "send";
                } else {
                    $this->action = "show";
                }
                break;
            default:
                $this->subController = false;
                break;
        }
    }

    public function getSubController()
    {
        return $this->subController;
    }

    public function getSubControllerFile()
    {
        return $this->subControllerFile;
    }

    public function getAction()
    {
        return $this->action;
    }
}

contact.SE.php

a sub controller example (it's code is omitted)

<?php
namespace aap;
// contact.SE.php (a controller designed to be included by the fron controller)
/*
 * @actions list:
 * 1-show
 * 2-send
 */
switch ($frontController->getAction()) {
    case "send":
        send($sysModel);
        break;
    default:
        show($sysModel);
        break;
}

function show(SystemModel $sysModel){}
function send(SystemModel $sysModel){}


texts: Find if a word with wildcard exists in dictionary

texts:
This is a question from a phone interview I had.

The question was in 2 parts:

  a. find("cat") -> T/F suggest a data structure to find is if a word
  exists in a large dictionary, how will one node of that data structure
  will look like?

  b. Implement a bool Find(string str) function which returns true or
  false if the word exists or not, and also supports "?" wildcard which
  can occur more than once.

    O
a    b     c    d   e
  a      b
b   r  t
    r    e
    o     r
    t

This is the final answer I have arrived with the interviewer:

public class TreeNode {
    public HashSet<TreeNode> Nodes {get;set;} // 26 children
    public HashSet<char> Index {get;set;}
    public bool EndOfWord {get;set;}
}

public bool Find(string str, TreeNode root, int currentIndex)
{
    if (str.IsNullOrEmpty() || root == null || currentIndex < 0)
    {
        return false;
    }

    if( currentIndex == str.Length )
    {
        return root.EndOfWord;
    }

    if(str[currentIndex] == '?')
    {
        for(int i=0; i< root.Nodes.Count ; i++)
        {
            if(root.Nodes[i] == null)
            {
                continue;
            }
            if (Find(str, root.Nodes[str[currentIndex]], currentIndex+1))
            {
                return true;
            }
        }
        return false;
    }
    else
    {
        if (root.Index.Contains(str[currentIndex]))
        {
            return Find(str, root.Nodes[str[currentIndex]], currentIndex+1);
        }
        else
        {
            return false;
        }
    }
}

Please suggests any data structure you can think of. I thought of using a suffix tree and tried to implement it.

Please suggest any other implementation for the Find() function and let me know if this is an interview where are the mistakes in my code. Complexity, code checking, naming, style, ...and so on. I didn't pass the interview and I'm trying to learn from this.


texts: Temperature conversion program with a lot of repetition

texts:
My son (9) is learning Python and wrote this temperature conversion program. He can see that there is a lot of repetition in it and would like to get feedback on ways to make it shorter.

def get_temperature():
    print "What is your temperature?"
    while True:
        temperature = raw_input()
        try:
            return float(temperature)
        except ValueError:
            print "Not a valid temperature. Could you please do this again?"

print "This program tells you the different temperatures."
temperature = get_temperature()

print "This is what it would be if it was Fahrenheit:"
Celsius = (temperature - 32)/1.8
print Celsius, "degrees Celsius"
Kelvin = Celsius + 273.15
print Kelvin, "Kelvin"

print "This is what it would be if it was Celsius."
Fahrenheit = temperature * 9 / 5 + 32
print Fahrenheit, "degrees Fahrenheit"
Kelvin = temperature + 273.15
print Kelvin, "Kelvin"

print "This is what it would be if it was Kelvin"
Celsius = temperature - 273.15
print Celsius, "degrees Celsius"
Fahrenheit = Celsius * 9 / 5 + 32
print Fahrenheit, "degrees Fahrenheit"


texts: PHP test isset and instantiate in one shot. Possible in PHP?

texts:
How to improve this kind of redundancy?

$nid = isset( $_GET['nid'] ) ? $_GET['nid'] : 0;

I want to avoid to repeat $_GET['nid']

Example of useful use case:

$nid = isset( $node->field_mymodule_extended_nid['und'][0]['target_id'] ) ? $node->field_mymodule_extended_nid['und'][0]['target_id'] : 0;


texts: Project Euler #549: Divisibility of factorials

texts:
This is the problem:

  Calculate

  $$\sum_{i=2}^{10^8} s(i)$$

  where \$s(n)\$ is the smallest \$m\$ such that \$n\$ divides \$m!\$.

Quite mathematical, I've found a better way than brute force by using largest prime factor and greatest common divisor. It works fine when n = 100 but still very slow when n gets larger and far too slow to solve the problem. So of course there are better ways.

Here is the code in Python:

import math

def maxPrimeFactor(n):
    p = 2
    while (p <= n/p):
        if (n%p):
            p += 1
        else:
            n/=p
    return n

def gcd(a,b):
    c = 1
    while (b):
        c = b
        b = a % b
        a = c
    return a

def sn(n):
    solution = prod = 1
    p = maxPrimeFactor(n)
    pFac = math.factorial(p)
    if((pFac%n) == 0 and pFac>=n):
        solution = p
    else:
        rest = n / gcd(pFac, n)
        solution = p+1
        prod = p + 1
        while(prod < rest):
            solution += 1
            prod *= solution
        while (prod % rest):
            solution += 1
            prod *= solution
    return solution

sum = 0
for i in range(2,100000001):
    sum += sn(i)
print sum


texts:
I am trimming an existing (stored in my gallery) video into smaller chunks; but I find the resulting video quality to be too degraded.

var chunkNumber = 1
let startTime = CMTime(seconds: 0.0, preferredTimescale: CMTimeScale(600.0))
let theDuration = CMTime(seconds: 10.0, preferredTimescale: CMTimeScale(600.0))

// the AVMutableComposition holds the track instances
let mixCompostion = AVMutableComposition()

// video
let videoTrack = mixCompostion.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do {
    try videoTrack?.insertTimeRange(CMTimeRangeMake(startTime, theDuration),
            of: (asset?.tracks(withMediaType: AVMediaType.video)[0])!, at: kCMTimeZero)
} catch {
    print ("failed to load the video track")
}

// audio
if ((asset?.tracks(withMediaType: AVMediaType.audio).count)! > 0) {
    let audioTrack = mixCompostion.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: 0)
    do {
        try audioTrack?.insertTimeRange(CMTimeRangeMake(startTime, theDuration),
                of: (asset?.tracks(withMediaType: AVMediaType.audio)[0])!, at: kCMTimeZero)
    } catch {
        print ("failed to load the audio track")
    }
}

// layers
let parentLayer = CALayer()
let videoLayer = CALayer()
let layerFrame = CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
parentLayer.frame = layerFrame
videoLayer.frame = layerFrame
parentLayer.addSublayer(videoLayer)

// master instruction wraps entire set of instructions
let masterInstruction = AVMutableVideoCompositionInstruction()
masterInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, theDuration)
let videoLayerInstruction = videoCompositionInstructionForTrack(track: videoTrack!, asset: asset!)

// add instructions to master, prepare composition
masterInstruction.layerInstructions = [videoLayerInstruction]
let mainComposition = AVMutableVideoComposition()
mainComposition.instructions = [masterInstruction]
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = CGSize(width: mainCompositionWidth, height: mainCompositionHeight)
mainComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)

// get path
let date = Date()
let savePath = (documentDirectory as NSString).appendingPathComponent("\(date)-\(chunkNumber).mov")
let url = URL(fileURLWithPath: savePath)
chunkNumber += 1

// create exporter
guard let exporter = AVAssetExportSession(asset: mixCompostion, presetName: AVAssetExportPresetHighestQuality) else { return }
exporter.outputURL = url
exporter.outputFileType = AVFileType.mov
exporter.shouldOptimizeForNetworkUse = true
exporter.videoComposition = mainComposition

// export
exporter.exportAsynchronously(completionHandler: { () -> Void in
    DispatchQueue.global().async {
        self.exportDidFinish(session: exporter)
    }
})

func exportDidFinish(session: AVAssetExportSession) {
    if session.status == AVAssetExportSessionStatus.completed {
        PHPhotoLibrary.shared().performChanges({
            _ = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: session.outputURL!)
        }, completionHandler: { (success, error) in
            let completionString = success ? "Success." : error?.localizedDescription
            print ("Finished updating asset: \(String(describing: completionString))")
        })
    }
    else if session.status == AVAssetExportSessionStatus.failed {
        print ("Export failed -> Reason: \(String(describing: session.error))")
        delegate?.exportFailed()
    }
}


texts:
For building an LSH based system in Python, I need to have a very fast calculation of the hashcode.

I won't need to explain here the LSH algorithm itself, but I need help in improving performance of the generate-Hash-Code operation:

Given a big number of features n (example: 5000 or even 50000):

multiply a dense matrix (13xn) with a sparse vector (nx1)
in the resulting vector (13x1) change to 1 if positive and 0 otherwise
generate a binary number out of the result

I tried various approaches and I put here two implementation generateCode1 and generateCode2 but both are still too heavy.

generateCode1 takes 56 seconds for 100 call (avg: 0.56 s)
generateCode2 takes 20 seconds for 100 call (avg: 0.20 s)

I am sure it is possible to do it faster but not sure how.
For you to be able to play with it, i am write a full working sample program:

import time
import numpy as np
from scipy import sparse
from scipy import stats

def randomMatrix(rows, cols, density):
    rvs = stats.norm(loc=0).rvs  # scale=2,
    M = sparse.random(rows, cols, format='lil', density=density, data_rvs=rvs)
    return M

def generateCode1(matrix, vector):
    nonzeros = np.nonzero(vector)
    temp_hashcode = []

    for i in range(matrix.shape[0]):
        d = 0
        for j in nonzeros[1]:
            d += matrix[i, j] * vector[0, j]

        temp_hashcode.append('1' if d > 0 else '0')

    return ''.join(temp_hashcode)

def generateCode2(matrix, vector):
    m = matrix * vector.T
    m [m > 0] = 1
    m [m < 0] = 0
    txt = ''.join(m.A.ravel().astype('U1'))
    return txt

features = 50000
test_count = 100

matrix = randomMatrix(13, features, 1.0)
vector = randomMatrix(1, features, 0.01)
vector = abs(vector)

methods = [ generateCode1, generateCode2 ]

for func in methods:
    print ('run {0} times of method {1}:'.format( test_count, func ) )
    time1 = time.time()
    for i in range(test_count):
        code1 = func(matrix, vector)
    time1 = time.time() - time1

    print ('\tcode: {0} - run time: '.format(code1), end="" )
    print ('{0}(s) == {1}(m) [ avergae {2}(s) ]'.format(time1, time1/60, time1/test_count) )

Note: Please don't go to parallelism and multi processing, that won't fit in my overall application (unfortunately).


texts:
This is a follow-up to yesterday's codereview-question about reading serial data and parsing it.

The code below is run into a seperate thread looped endlessly.
Currently I track the position in my inputBufer manually and copy all bytes which haven't been processed into a new byte-array and assigning that to the old inputBuffer.

Can the read buffer handling be improved?

bytesRead = SerialPort.Read(inputBuffer, bufferPos, SerialPort.BytesToRead);
bufferPos += bytesRead;
bytesProcessed = 0;

// process data-packets
for (int i = 0; i < this.bufferPos; i++) {

  // Flex sensor data
  //
  if (this.bufferPos-i >= 14 && inputBuffer[i] == 'F'){
    i++;
    short[] sensorData = new short[6];
    sensorData[0] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // thumb
    sensorData[1] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // index finger (finger knuckle)
    sensorData[2] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // middle finger
    sensorData[3] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // ring finger
    sensorData[4] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // not used
    sensorData[5] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // index finger (hand knucke)
    // checksum
    byte checksum = inputBuffer[i++];
    ParseSerialData(PacketType.Flex, sensorData, checksum);
    bytesProcessed = i;
    //Debug.Log (sensorData[0] + " then " + bytesProcessed);
  }

  // Raw sensor data
  //
  if (this.bufferPos-i >= 20 && inputBuffer[i] == 'S'){
    i++;
    short[] sensorData = new short[9];
    sensorData[0] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // gyroscope X
    sensorData[1] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // gyroscope Y
    sensorData[2] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // gyroscope Z
    sensorData[3] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // accelerometer X
    sensorData[4] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // accelerometer Y
    sensorData[5] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // accelerometer Z
    sensorData[6] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // magnetometer X
    sensorData[7] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // magnetometer Y
    sensorData[8] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // magnetometer Z
    // checksum
    byte checksum = inputBuffer[i++];
    ParseSerialData(PacketType.Raw, sensorData, checksum);
    bytesProcessed = i;
  }

  // Quaternion of device's rotation
  //
  if (this.bufferPos-i >= 20 &&  inputBuffer[i] == 'Q'){
    i++;
    short[] sensorData = new short[4];
    sensorData[0] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // W
    sensorData[1] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // X
    sensorData[2] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // Y
    sensorData[3] = (short)((short)inputBuffer[i++] << 8 | inputBuffer[i++]); // Z
    // checksum
    byte checksum = inputBuffer[i++];
    ParseSerialData(PacketType.Quaternion, sensorData, checksum);
    bytesProcessed = i;
  }
}

// Copy unprocessed rest of stream
int rest = bufferPos - bytesProcessed;
  if (rest > 0){
  byte[] tempBuffer = new byte[4096];
  Array.Copy (inputBuffer, bytesProcessed, tempBuffer, 0, rest);
  inputBuffer = tempBuffer;
  bufferPos = rest;
}
else {
  inputBuffer = new byte[4096];
  bufferPos = 0;
}


texts: Listing all possible names from a phone number

texts:
In the program we have to input a number and then calculate all the possible name we can form according to the following rule:

2: A,B,C     5: J,K,L    8: T,U,V
3: D,E,F     6: M,N,O    9: W,X,Y
4: G,H,I     7: P,R,S

Just like we did on a keypad phone. Q and Z have been excluded (for simplicity, I believe)

For example 4734 produces

GPDG GPDH GPDI GPEG GPEH GPEI GPFG GPFH GPFI GRDG GRDH GRDI
GREG GREH GREI GRFG GRFH GRFI GSDG GSDH GSDI GSEG GSEH GSEI
GSFG GSFH GSFI HPDG HPDH HPDI HPEG HPEH HPEI HPFG HPFH HPFI
HRDG HRDH HRDI HREG HREH HREI HRFG HRFH HRFI HSDG HSDH HSDI
HSEG HSEH HSEI HSFG HSFH HSFI IPDG IPDH IPDI IPEG IPEH IPEI
IPFG IPFH IPFI IRDG IRDH IRDI IREG IREH IREI IRFG IRFH IRFI
ISDG ISDH ISDI ISEG ISEH ISEI ISFG ISFH ISFI

The digits in the inputted number can vary from 1 through 12.

I tried to do this using recursion.

import java.util.*;
import java.io.*;
public class namenum{
        public static void main(String[] args) throws Exception{

        Scanner sc = new Scanner(new File("namenum.in"));

        PrintWriter pw  = new PrintWriter(new File("namenum.out"));
        String n = sc.next();
        ArrayList<String> ans = new ArrayList<>();
        List<Character> arr2 = new ArrayList<>();
        arr2.add('A');
        arr2.add('B');
        arr2.add('C');

        List<Character> arr3 = new ArrayList<>();
                arr3.add('D');
        arr3.add('E');
        arr3.add('F');

        List<Character> arr4 = new ArrayList<>();
        arr4.add('G');
        arr4.add('H');
        arr4.add('I');

        List<Character> arr5 = new ArrayList<>();
        arr5.add('J');
        arr5.add('K');
        arr5.add('L');

        List<Character> arr6 = new ArrayList<>();
        arr6.add('M');
        arr6.add('N');
        arr6.add('O');
        List<Character> arr7 = new ArrayList<>();
        arr7.add('P');
        arr7.add('Q');
        arr7.add('R');

        List<Character> arr8 = new ArrayList<>();
        arr8.add('T');
        arr8.add('U');
        arr8.add('V');

        List<Character> arr9 = new ArrayList<>();
        arr9.add('W');
        arr9.add('X');
        arr9.add('Y');

        List<List<Character>> Lists = new ArrayList<>();
        Lists.add(arr2);
        Lists.add(arr3);
        Lists.add(arr4);
        Lists.add(arr5);
        Lists.add(arr6);
        Lists.add(arr7);
        Lists.add(arr8);
        Lists.add(arr9);

        List<String> result = new ArrayList<String>();
        genPermutations(Lists, result, 0, "");
        boolean ansFound = false;
        for(int i = 0; i< result.size(); i++){
            String name = result.get(i);
            if(isInDict(name)){
                pw.println(name);
                ansFound = true;
            }

        }
        if (!ansFound){
            pw.println("NONE");
        }
        pw.close();

    }
    static boolean isInDict(String name) throws Exception{
        boolean ans = false;
        Scanner dict = new Scanner(new File("dict.txt"));
        while(dict.hasNext()){
            if(dict.next() == name){
                ans = true;
                break;
            }
        }
        return ans;

    }

    static void genPermutations(List<List<Character>> Lists, List<String> result, int depth, String current){
        if(depth == Lists.size()){
            result.add(current);
            return ;
        }
        for(int i = 0; i<Lists.get(depth).size();i++){
            genPermutations(Lists, result, depth+1,current+Lists.get(depth).get(i));
        }
    }
    }

But it uses more time (2.128 seconds to be precise) than the accepted 1 second and I get a time limit exceeded verdict.

The question can be found here USACO

What are the ways in which I can simplify the program?


texts: Count character 'a' in first n characters of indefinitely repeating string s

texts:
Problem statement:

  Lilah has a string, s, of lowercase English letters that she
  repeated infinitely many times. Given an integer, n, find and
  print the number of letter a's in the first n letters of
  Lilah's infinite string.

  For example, if the string s = 'abcac' and n = 10, the
  substring we consider is abcacabcac, the first 10 characters
  of her infinite string. There are 4 occurrences of a in the
  substring.

  Function Description

  Complete the repeatedString function in the editor below. It should
  return an integer representing the number of occurrences of a in
  the prefix of length  n in the infinitely repeating string.

  repeatedString has the following parameter(s):

s: a string to repeat
n: the number of characters to consider

  Input Format The first line contains a single string, s.  The second line contains an integer, n.

  Output Format

  Print a single integer denoting the number of letter a's in the
  first  letters of the infinite string created by repeating infinitely
  many times.

  Sample Input 0

aba
10

  Sample Output 0

7

  Explanation 0  The first  letters of the infinite string are abaabaabaa. Because there are  a's, we print  on a new line.

  Sample Input 1

a
1000000000000

  Sample Output 1

1000000000000

  Explanation 1  Because all of the first  letters of the infinite string are a, we print  on a new line.

My Solution:

def repeatedString(s: String, n: Long): Long = {

  def getCount(str: String): Int = str.groupBy(identity).get('a').map(x => x.length).getOrElse(0)

  val length= s.length
  val duplicate: Long = n / length
  val margin = n % length
  val numberOccurencesInString = getCount(s)
  val countInRepetetiveString = numberOccurencesInString * duplicate

  val numberOfOccurencesInStripedString = getCount(s.take(margin.toInt))

  countInRepetetiveString + numberOfOccurencesInStripedString
}


texts: C++ memset / memcpy / strcpy implementation performance

texts:
In C++, I have made a basic memset / memcpy / strcpy implementation, yet I am worried that they are slower than the STL equivalent, as they are probably made in assembly, which I do not know. Is there any way of making these quicker, still using C++?

#define BYTE unsigned char

typedef BYTE byte;

void *__memset(void *_Dst, int _Val, UINT _Size)
{
    BYTE *buf = (BYTE *)_Dst;
    while (_Size--)
    {
        *buf++ = (BYTE)_Val;
    }
    return _Dst;
}

void *__memcpy(void *_Dst, const void *_Src, UINT _Size)
{
    BYTE *buf = (BYTE *)_Dst;
    BYTE *__Src = (BYTE *)_Src;
    while (_Size--)
    {
        *buf++ = *__Src++;
    }
    return _Dst;
}

char *__strcpy(char *_Dst, const char *_Src)
{
    while ((*_Dst++ = *_Src++) != '\0');
    return _Dst;
}


texts:
So I've been writing a unit test using Rhino Mocks to a controller in my ASP MVC application. The test passes, but I'm interested in your opinion and if there's something I should be doing differently or what it could be.

Here's my test method:

    [TestMethod]
    public void TestSlideView()
    {
        // Arrange
        var repositoryMock = MockRepository.GenerateMock<ISlideRepository>();
        var controller = new SlideController(repositoryMock);
        var expectedSlides = new List<SlideModel>();
        expectedSlides.Add(new SlideModel
        {
            Id = "id"
        });
        repositoryMock.Stub(x => x.GetSlides("id")).Return(expectedSlides);

        // Act
        var actualView = controller.Slide("id") as ViewResult;
        var actualData = actualView.Model;

        // Assert
        Assert.IsNotNull(actualView);
        Assert.IsNotNull(actualData);
        Assert.AreEqual("Slide", actualView.ViewName);
    }

Here's the controller under test:

    public ActionResult Slide(string slideid)
    {
        var slides = slideRepository.GetSlides(slideid);

        return View("Slide", slides);
    }

The repository the controller uses is here:

public interface ISlideRepository
{
    List<SlideModel> GetSlides(string id);
}

public class SlideRepository : ISlideRepository
{
    public SlideModel Slides { get; set; }
    public List<SlideModel> SlideList { get; set; }

    public List<SlideModel> GetSlides(string id)
    {
        string cs = dbPath;
        string slideid = id;

        using (SQLiteConnection con = new SQLiteConnection(cs))
        {
            var listOfSlides = new List<SlideModel>();
            string stm = "SELECT * FROM Slide WHERE ID = " + slideid;
            con.Open();

            using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
            {
                using (SQLiteDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        listOfSlides.Add(new SlideModel
                        {
                            Id = rdr["ID"].ToString()
                        });
                    }

                    rdr.Close();
                    SlideList = listOfSlides;
                }
            }

            con.Close();
        }

        return SlideList;
    }
}

Any input is greatly appreciated!


texts:
I'm currently looking at this Boost::CRC example code which I have also inserted below.

I always try to look for suggestions for improving my own coding style when I encounter well-written and well-formatted code.

This code definitely looks like good code, but two things puzzle me about this:

is it good practice to copy #defined constants to local const variables before using them? Why would this be a good idea?
is it actually acceptable to just omit the parenthesis around a function body if the body is a try-catch-block?

//  Boost CRC example program file  ------------------------------------------//

//  Copyright 2003 Daryle Walker.  Use, modification, and distribution are
//  subject to the Boost Software License, Version 1.0.  (See accompanying file
//  LICENSE_1_0.txt or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)

//  See <http://www.boost.org/libs/crc/> for the library's home page.

//  Revision History
//  17 Jun 2003  Initial version (Daryle Walker)

#include <boost/crc.hpp>  // for boost::crc_32_type

#include <cstdlib>    // for EXIT_SUCCESS, EXIT_FAILURE
#include <exception>  // for std::exception
#include <fstream>    // for std::ifstream
#include <ios>        // for std::ios_base, etc.
#include <iostream>   // for std::cerr, std::cout
#include <ostream>    // for std::endl

// Redefine this to change to processing buffer size
#ifndef PRIVATE_BUFFER_SIZE
#define PRIVATE_BUFFER_SIZE  1024
#endif

// Global objects
std::streamsize const  buffer_size = PRIVATE_BUFFER_SIZE;

// Main program
int
main
(
    int           argc,
    char const *  argv[]
)
try
{
    boost::crc_32_type  result;

    for ( int i = 1 ; i < argc ; ++i )
    {
        std::ifstream  ifs( argv[i], std::ios_base::binary );

        if ( ifs )
        {
            do
            {
                char  buffer[ buffer_size ];

                ifs.read( buffer, buffer_size );
                result.process_bytes( buffer, ifs.gcount() );
            } while ( ifs );
        }
        else
        {
            std::cerr << "Failed to open file '" << argv[i] << "'."
             << std::endl;
        }
    }

    std::cout << std::hex << std::uppercase << result.checksum() << std::endl;
    return EXIT_SUCCESS;
}
catch ( std::exception &e )
{
    std::cerr << "Found an exception with '" << e.what() << "'." << std::endl;
    return EXIT_FAILURE;
}
catch ( ... )
{
    std::cerr << "Found an unknown exception." << std::endl;
    return EXIT_FAILURE;
}


texts: JavaScript implementation of Symbol Table (Dictionary)

texts:
I'm currently going over Robert Sedgewick Algorithms book. Here I'm implementing a Symbol Table using a Linked List. The Sequential Search Symbol table is implemented in JavaScript. The book mentiones that this Abstract Data Structure is not a good solution when dealing with big amounts of data.
I would like feedback on the implementation and on following JavaScript best practices. I'm coming from Ruby so having this implementation follow the best practices in JavaScript is a plus for me.

// Symbol Table using Sequential search (Linked List)
//
class SequentialSearchST {

  constructor() {
    this.first = null;
  }

  get(key) {
    for(let x = this.first; x != null; x = x.next) {
      if(x.key === key) {
        return x.val
      }
    }
    return null;
  }

  put(key, val) {
    for(let x = this.first; x != null; x = x.next) {
      if(x.key === key) {
        return x.val = val
      }
    }
    this.first = new Node(key, val, this.first);
  }

}

class Node {
  constructor(key, val, next) {
    this.key = key;
    this.val = val;
    this.next = next;
  }
}

st = new SequentialSearchST();
st.put('s', 0)
st.put('e', 1)
st.put('a', 2)
st.put('r', 3)
st.put('c', 4)
st.put('h', 5)
st.put('e', 6)
st.put('x', 7)
st.put('a', 9)
st.put('m', 10)
st.put('p', 11)
st.put('l', 12)
st.put('e', 13)
console.dir(st.get('s'));


texts: Arrange three integers from least to greatest

texts:
I'm a C++ beginner and I was told to make a program to arrange three integers from least to greatest. How did I do?

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    int y = 0;
    int z = 0;
    int first = 0;
    int second = 0;
    int third = 0;
    cout<<"Enter three integers to be arranged from least to greatest.\n";
    cin>>x>>y>>z;

    if(x <= y)
    {
        if(x <= z)
        {
            first = x;
            if(y <= z)
            {
                second = y;
                third = z;
            }
            else
            {
                third = y;
                second = z;
            }
        }
        else
        {
            second = x;
            if(y <= z)
            {
                first = y;
                third = z;
            }
            else
            {
                third = y;
                first = z;
            }
        }
    }
    else
    {
        if(x <= z)
        {
            second = x;
            if (y <= z)
            {
                first = y;
                third = z;
            }
        }
        else
        {
            third = x;
            if ( y <= z)
            {
                first = y;
                second = z;
            }
            else
            {
                second = y;
                first = z;
            }
        }
    }
    cout<<first<<second<<third;
}


texts:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace ExamManagement.DLL
{
    public class SQLDataAccessHelper
    {
        string connectionString=string.Empty;

        public SQLDataAccessHelper()
        {
            try
            {
                connectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;

            }
            catch (Exception)
            {
                //todo error handling  mechanism
                throw;
            }
        }

        public void ExecuteNonQuery(string commandText,CommandType commandType, params SqlParameter[] commandParameters)
        {
            using(var connection= new SqlConnection(connectionString))
            using (var command = new SqlCommand(commandText, connection))
            {
                command.CommandType = commandType;
                command.Parameters.AddRange(commandParameters);
                connection.Open();
                command.ExecuteNonQuery();
            }
        }

        public DataSet ExecuteQuery(string commandText,CommandType commandType,params SqlParameter[] parameters)
        {
            using(var connection=new SqlConnection(connectionString))
            using(var command= new SqlCommand(commandText,connection))
            {
                DataSet ds=new DataSet();
                command.CommandType=commandType;
                command.Parameters.AddRange(parameters);
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(ds);
                connection.Close();
                return ds;
            }
        }
    }
}

This is helper class I have written to retrieve data and execute CRUD operation on sql server database either using queries or stored procedures.

Currently it is used from DAL classes as follows :

I create instance of it
I call method "ExecuteQuery" and it returns DataSet

Details as follows:

namespace ExamManagement.DLL.Implementations
{
    public class StudentDAO : IStudentDAO
    {
        SQLDataAccessHelper sqlHelper;
        public StudentDAO()
        {
            sqlHelper = new SQLDataAccessHelper();
        }

        public List<Entities.Student> AllStudents()
        {
            List<Entities.Student> studentsList = new List<Entities.Student>();

            SqlParameter[] parameterList = { new SqlParameter("@Id",DBNull.Value),
                                               new SqlParameter("@name",DBNull.Value),
                                               new SqlParameter("@address",DBNull.Value)};

            var table = sqlHelper.ExecuteQuery("GetStudents", System.Data.CommandType.StoredProcedure,parameterList).Tables[0];
            studentsList = table.AsEnumerable().Select(row => new Entities.Student { Id = row.Field<int>("Id"), Name = row.Field<string>("Name"), Address = row.Field<string>("Address") }).ToList();
            return studentsList;
        }

I have following questions with regards to it

Helper class should be static class or the methods in it should be static methods?
Connection string is not supplied by class user, instead its is auto calculated from Web.config using ConfigurationManager. Is this approach ok?
I'm creating connection in "Using" statement, so can I ignore calling connection.Close() or its required even then ?
How can I improve it.
Possible to write unit tests for this class?


texts: Persisting database row ID between controller actions on a multi-step "create item" form

texts:
I have a form on an anonymous site which has 3 steps. A user submits each step individually, in sequence (1-2-3). BUT, step 1 creates a new table row, while steps 2 and 3 only update the existing row (from step 1), writing to different sets of fields, though. In order for steps 2 and 3 to know which database row to update, they reference a a querystring parameter generated after step 1.  But, I need to also prevent manual tweaking of the querystring parameter in steps 2/3.

I've come up with this method of passing/persisting a hashed string between controller actions.  I'd appreciate some feedback, just so I know if there isn't anything terribly wrong with this approach, or if I've missed something obvious.

First, like I said, a row ID is passed via a URL parameter, as in:

http://site/MultiStepFormController/Step1Action/id

A hash string gets computed and passed from one controller action to another via TempData. The hash string is another property in the viewmodels, and is used on the Views as a hidden field.  This makes it possible to get picked up by the POST action so it can be re-evaluated again, as well as passed onto the following step easily.

View Models

There are 3 separate ViewModel classes (for the 3 separate signup "steps"), but the 2nd and 3rd have these properties, among others:

[Required, HiddenInput]
public int SignupId { get; set; }

[Required, HiddenInput]
public string HashCode { get; set; }

Views (for Step 2 and 3):

@model MyApp.Web.ViewModels.Step2ViewModel

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.SignupID)
    @Html.HiddenFor(model => model.HashCode)

    //Other stuff for the view...
}

Controller

In my controller there are 6 total Actions (3 signup steps x 2 actions each for Get and Post):

[HttpGet]
public ActionResult Step1()
{
    //Nothing special needed in Step 1 GET, because there is no Signup record yet.
    //Do stuff and return View(model)...
}

[HttpPost]
public ActionResult Step1(Step1ViewModel model)
{
    //Do stuff and create new record in DB from step 1 viewmodel

    //Now, compute a hash string using MD5 from the newly-created signup ID + a salt value of some kind:
    var hashCode = GenerateHashCode(newSignup.SignupID, someSalt);

    //Use TempData to pass the hash code onto next action
    TempData["HashCode"] = hashCode;
    return RedirectToAction("Step2", new { id = newSignup.SignupID });
}

[HttpGet]
public ActionResult Step2(int id)
{
    /* At this point, Step 2 GET is really an "edit" action, because
       the signup now exists in the DB and needs to be "appended" with
       new data. */

    var hashCode = TempData["HashCode"] as string;

    if (!IsHashCodeValid(id, hashCode))
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //Hash code checks out, so proceed to build and return the View(model)
}

[HttpPost]
public ActionResult Step2(Step2ViewModel model)
{
    //Check the hash again on posting, too
    if (!IsHashCodeValid(model.SignupID, model.HashCode))
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //Hash code checks out, so proceed to update the Signup record in DB

    //Use TempData again to store the hash code and pass onto Step 3
    TempData["HashCode"] = model.HashCode;
    return RedirectToAction("Step3", new { id = signup.SignupID });
}

/* Step 3 Get and Post actions are almost identical to Step 2... */

I'd really appreciate some feedback and pointers to anything that might be a screaming "no-no!"  Or better yet, if this is OK, that would be good to know, too.


texts: EventList a generic list implementation that raises events when items are added and removed

texts:
I created this class for a project when I wanted to have List<T> properties on a class and also listen for items being added and removed.

I looked at using BindingList<T> or ObservableCollection<T> but I felt that their collection changed events are too complicated. I simply wanted to know when items are added and removed.

public class EventList<T> : IList<T>
{
    private readonly List<T> _list;

    public EventList()
    {
        _list = new List<T>();
    }

    public EventList(IEnumerable<T> collection)
    {
        _list = new List<T>(collection);
    }

    public EventList(int capacity)
    {
        _list = new List<T>(capacity);
    }

    public event EventHandler<EventListArgs<T>> ItemAdded;
    public event EventHandler<EventListArgs<T>> ItemRemoved;

    private void RaiseEvent(EventHandler<EventListArgs<T>> eventHandler, T item, int index)
    {
        var eh = eventHandler;
        eh?.Invoke(this, new EventListArgs<T>(item, index));
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Add(T item)
    {
        var index = _list.Count;
        _list.Add(item);
        RaiseEvent(ItemAdded, item, index);
    }

    public void Clear()
    {
        for (var index = 0; index < _list.Count; index++)
        {
            var item = _list[index];
            RaiseEvent(ItemRemoved, item, index);
        }

        _list.Clear();
    }

    public bool Contains(T item)
    {
        return _list.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _list.CopyTo(array, arrayIndex);
    }

    public bool Remove(T item)
    {
        var index = _list.IndexOf(item);

        if (_list.Remove(item))
        {
            RaiseEvent(ItemRemoved, item, index);
            return true;
        }

        return false;
    }

    public int Count => _list.Count;
    public bool IsReadOnly => false;

    public int IndexOf(T item)
    {
        return _list.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        _list.Insert(index, item);
        RaiseEvent(ItemRemoved, item, index);
    }

    public void RemoveAt(int index)
    {
        var item = _list[index];
        _list.RemoveAt(index);
        RaiseEvent(ItemRemoved, item, index);
    }

    public T this[int index]
    {
        get { return _list[index]; }
        set { _list[index] = value; }
    }
}

public class EventListArgs<T> : EventArgs
{
    public EventListArgs(T item, int index)
    {
        Item = item;
        Index = index;
    }

    public T Item { get; }
    public int Index { get; }
}

The typical use case would be something like this:

public class MyClass
{
    public MyClass()
    {
        MyItems = new EventList<string>();

        MyItems.ItemAdded += (sender, args) =>
        {
            // do something when items are added
        };

        MyItems.ItemRemoved += (sender, args) =>
        {
            // do something when items are removed
        };
    }

    public EventList<string> MyItems { get; }
}

I'm posting this here for code review for general feedback, but also to ask if I've missed something obvious, like an alternative class in the .NET framework or a 3rd party library that might do the same sort of thing?


texts: Generating unique alphanumeric ID's of a fixed length

texts:
I am needing to generate unique id's for users. The 'unique' part is the problem for me.

The 13 character id's which have a format of the following:

0 + random int with range of 1-9 + random letter + random 3 digit number + string 98XX001 For example: 04X90398XX001 --> (0) (4) (X) (903) (98XX001)

This is the code I currently have for generating the ID's:

package generation;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class id {
private static List<String> generatedIDs = new ArrayList<String>();
public static void main(String[] args) {
    generateIDs(1200);
}

public static void generateIDs(int numOfUsers) {
    for (int i = 0; i < numOfUsers; i++) {
        Random r = new Random();
        int first = r.nextInt((9 - 1) + 1) + 1;
        char second = (char) (r.nextInt(26) + 'A');
        int third = r.nextInt((899 - 100) + 100) + 100;

        String id = "0" + first + second + third + "98XX001";
        generatedIDs.add(id);
        System.out.println(id);

    }
  }
}

Like I said, I am pretty clueless on how to make sure that they are unique.


texts: Palindrome numbers - Project Euler Problem 4

texts:
Project Euler Problem #4: Largest palindrome product:

  A palindromic number reads the same both ways. The largest palindrome
  made from the product of two 2-digit numbers is 9009 = 91 × 99.

  Find the largest palindrome made from the product of two 3-digit
  numbers.

I got the correct answer for the problem, but I want to know if my coding style is good or bad for this solution.
I need to know how I can improve my coding, if it is bad and write this in a more general way.

#include<stdio.h>
#define MAX 999
#define START 100

int main()
{
   int i,j,current,n,prev = 0;
for(i = START;i<=MAX;i++)
{
    for(j=START;j<=MAX;j++)
    {
        current = j * i;
        if(current > prev)  /*check the current value so that if it is less need not go further*/
        {
            n = palindrome(current);
            if (n == 1)
            {
                printf("The palindrome number is : %d\n",current);
                prev = current;  // previous value is updated if this the best possible value.
            }
        }
    }
}
}

int palindrome(int num)
{
int a[6],temp;
temp = num;
/*We need a array to store each element*/
a[5] = temp % 10;
a[4] = (temp/10) %10;
a[3] = (temp/100) %10;
a[2] = (temp/1000) %10;
a[1] = (temp/10000) %10;
if(temp/100000 == 0)
{
    a[0] = 0;
    if(a[1] == a[5] && a[2] == a[4])
        return 1;
}
else
{
    a[0] = (temp/100000) %10;
    if(a[0] == a[5] && a[1] == a[4] && a[2] == a[3])
        return 1;
    else
        return 0;
}
}


texts:
The following code is part of a big application. I am new to Go, and appreciate feedback on the best practices and improvements. Please consider styling and comments as well.

Every 30 minutes, this will fetch news from HackerNews and store it in a database:

What fetches the news:

package services

import (
    "fmt"
    "net/http"
    "log"
    "io/ioutil"
    "github.com/demas/cowl-go/pkg/quzx-crawler"
    "encoding/json"
    "github.com/demas/cowl-go/pkg/postgres"
    "time"
    "strconv"
)

// represent an implementation of quzx_crawler.HackerNewsService
type HackerNewsService struct {
}

const idsUrl = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
const newsUrl = "https://hacker-news.firebaseio.com/v0/item/%d.json?print=pretty"
const syncInterval = 60 * 30 // 30 minutes

func (s *HackerNewsService) Fetch() {

    var lastSyncTime int64
    var err error

    lastSyncTimeStr := (&postgres.SettingsRepository{}).GetSettings("lastHackerNewsSyncTime")
    if lastSyncTimeStr == "" {
        lastSyncTime = time.Now().Unix() - syncInterval - 1
    } else {
        lastSyncTime, err = strconv.ParseInt(lastSyncTimeStr, 10, 64)
        if err != nil {
            log.Fatal(err)
        }
    }

    currentTime := time.Now().Unix()

    if lastSyncTime + syncInterval > currentTime {
        return
    }

    // get list of messages
    res, err := http.Get(idsUrl)
    if err != nil {
        log.Fatal(err)
    }

    jsn, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        log.Fatal(err)
    }

    // decode
    var ids []int64
    err = json.Unmarshal(jsn, &ids)

    if err != nil {
        log.Fatal(err)
    } else {

        for _, id := range ids {

            if !(&postgres.HackerNewsRepository{}).NewsExists(id) {

                // fetch each news
                log.Println("hacker news: " + fmt.Sprintf(newsUrl, id))
                res, err := http.Get(fmt.Sprintf(newsUrl, id))
                if err != nil {
                    log.Fatal(err)
                }

                jsn, err := ioutil.ReadAll(res.Body)
                res.Body.Close()
                if err != nil {
                    log.Fatal(err)
                }

                // decode
                var news quzx_crawler.HackerNews
                err = json.Unmarshal(jsn, &news)

                if err != nil {
                    log.Fatal(err)
                } else {
                    (&postgres.HackerNewsRepository{}).InsertNews(news)
                }
            }
        }
    }

    (&postgres.SettingsRepository{}).SetSettings("lastHackerNewsSyncTime",  strconv.FormatInt(currentTime, 10))
}

What stores the data:

package postgres

import (
    "log"
    "github.com/demas/cowl-go/pkg/quzx-crawler"
)

// represent a PostgreSQL implementation of quzx_crawler.HackerNewsService
type HackerNewsRepository struct {
}

func (r *HackerNewsRepository) NewsExists(id int64) bool {

    var cnt int
    err := db.Get(&cnt, "SELECT count(*) FROM HackerNews WHERE Id = $1", id)

    if err != nil {
        log.Fatal(err)
    }

    return cnt != 0
}

func (r *HackerNewsRepository) InsertNews(n quzx_crawler.HackerNews) {

    tx := db.MustBegin()

    insertQuery := `INSERT INTO HackerNews(Id, By, Score, Time, Title, Type, Url, Readed)
                VALUES($1, $2, $3, $4, $5, $6, $7, $8)`

    _, err := tx.Exec(insertQuery,
              n.Id, n.By, n.Score, n.Time, n.Title, n.Type, n.Url, 0)

    if err != nil {
        log.Fatal(err)
    }

    tx.Commit()
}


texts: Schedule Global Task by using static System.Timers

texts:
I'm using System.Timers to schedule tasks. I find this working, but I'm not quite sure if it's ok to do it this way.

using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Timers;
using System.IO;
using System.Threading;

namespace WebApplication2
{
    public class Global : System.Web.HttpApplication
    {
        public static System.Timers.Timer timer1 = new System.Timers.Timer();

        protected void Application_Start(object sender, EventArgs e)
        {
            timer1.Interval = 100;
            timer1.Elapsed += timer1_Elapsed;
        }

        void timer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer1.Stop();
            // Example: Execute Task after 6 hours
            Thread.Sleep(6 * 60 * 60 * 1000);
            // Do something. Example:
            File.AppendAllText("C:\\log.txt", DateTime.Now + "\r\n");
        }
    }
}

By using this method, I can start the task anywhere in the application by calling this:

WebApplication2.Global.timer1.Start();

What do you think?


texts: Ruby if-statement, possible to shorten it further?

texts:
Is it possible to shorten this, or to improve the code in any way? I know it's just a simple if-statement, but it's always fun to learn a shorter way of doing things.

if self.citizenship == 'ES'
  @identification_type = IDENTIFICATION_TYPES[0]
elsif self.country == 'ES'
  @identification_type = IDENTIFICATION_TYPES[1]
end


texts: Key and value mapping from one object to another

texts:
I've been trying to figure out a clean way of managing mappings between two objects. In the case of this example, it's two hashes. This spec should illustrate the problem at hand:

describe 'key mapping' do
  let(:have) { { data1: 'foo', data2: 'bar', data3: 'baz' } }
  let(:want) { { LINE1: 'foo', LINE2: 'bar', LINE3: 'baz' } }
  let(:result) { {} }

  after(:each) do
    expect(result).to eq want
  end

  it 'by assigning manually' do
    result[:LINE1] = have[:data1]
    result[:LINE2] = have[:data2]
    result[:LINE3] = have[:data3]
  end

  it 'by reading keys from a hash' do
    mappings = { data1: :LINE1, data2: :LINE2, data3: :LINE3 }
    mappings.each do |k, v|
      result[v] = have[k]
    end
  end
end

The notable thing here is that the source and destination can be mapped by known keys and unlike in the example there is no numeric correlation between the source and destination (example lists numbered keys just to make it easier to read)

The number of keys could be rather high, so the latter example will make code more readable, but is there an even better way of handling this?


texts: Python exception-raising generator function

texts:
I want my generator function to raise as soon as it can.  If I make it yield the elements directly, then the KeyError won't happen until iteration begins.  Is the following code the best I can do?

def cluster_terminals(self, key):
    """
    Deals with forwarding.
    """
    return_list = self.cluster_map[key]
    def internal_cluster_terminals(return_list):
        for x in return_list:
            if isinstance(x, ClusterTerminal):
                yield x
            elif isinstance(x, NodeTerminalMappingName):
                yield from x.node_terminal.cluster_terminals(x.mapping_name)
            else:
                assert False
    return internal_cluster_terminals(return_list)


texts:
I wrote the following code for solving the Rod-Cutting Problem using dynamic programming:

  Rod Cutting Problem: Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces and also find the size of the pieces to be cut.

import random

prices = {x:random.randrange(x, 2*x) for x in range(1,101)}

def find_optimum_revenue(length, prices, memo={}):
    '''This function finds the maximum possible revenue
       that can be generated by cutting a rod of
       length = length and the prices for each rod of length n
       is stored in prices such that prices[n] finds the price
       of the rod.'''

    if length == 1: # Base Case: You can't cut a rod of length == 1
        return prices[1]

    elif length in memo:
        return memo[length]

    else:
        # The first list will contain all the possible revenues after
        # cutting the rod. We add the list [prices[length]] to add the
        # possibility that we may sell the rod as is and not cut it.

        possible_revenues = [find_optimum_revenue(half, prices, memo) + \
                            find_optimum_revenue
                             (length - half, prices, memo) \
                    for half in range(1, length//2+1)] + [prices[length]]

        memo[length] = max(possible_revenues) # Saving in dictionary for future use
        return memo[length]

get_price = lambda pieces: sum(prices[rod] for rod in pieces)

def find_optimum_cuts(length, prices, memo={}):
    '''This function finds the length of pieces to be cut so
       as to generate the maximum revenue that can be generated
       by cutting a rod of length = length and the prices for
       each rod of length n is stored in prices such that prices[n]
       finds the price of the rod.'''

    if length == 1: # Base Case: You can't cut a rod of length == 1
        return (1,)

    elif length in memo:
        return memo[length]

    else:
        # The first list will contain all the possible revenues after
        # cutting the rod. We add the list [prices[length]] to add the
        # possibility that we may sell the rod as is and not cut it.

        best_cuts = [find_optimum_cuts(half, prices, memo) + \
                    find_optimum_cuts(length - half, prices, memo) \
                    for half in range(1, length//2+1)] + [(length,)]

        memo[length] = max(best_cuts, key=get_price) # Saving in dictionary for future use
        return memo[length]

print(find_optimum_revenue(100, prices))
print(find_optimum_cuts(100, prices))

It works correctly for all the test cases I have tried and is not broken. The first function finds the maximum revenue and the second the pieces to be cut. I am thinking of merging them as it would save time. The prices list contains the prices of different sizes of rods. Is it possible to reduce the time and memory consumption and make the code better and more Pythonic? Also, can you please tell me its time complexity? I believe it to be \$O(n^2)\$ but I am not sure.


texts: Javascript: Google Analytics Track Outbound Page Views

texts:
I've researched this morning how to use Google Analytics to track outbound page views. However, I think the implementation might be a bit difficult on our website (as we have hundreds of outbound links)

Here's what google recommends.

/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
Check out example.com

As you can see, attaching an onClick attribute to every single anchor tag you want to track is fine, IF YOU ARE JUST NOW DEVELOPING A WEBSITE!

To remedy this issue, I have written some code to loop through every anchor tag on the page, and determine if the anchor is external or not. In this script, *.pdf need to be included. Here my custom script:

var anchors = document.getElementsByTagName("a");

  for (i = (anchors.length - 1); i > -1; i--) {
   var anchorHREF = anchors[i].getAttribute("href");
   if (anchorHREF != "" && anchorHREF != null) {
    var doSetOnClick = false;

    if (anchors[i].hostname != document.location.hostname) {
     doSetOnClick = true;
    }

    if (anchorHREF.indexOf(".pdf") > -1) {
     doSetOnClick = true;
    }

    if (doSetOnClick) {
     anchors[i].setAttribute("onClick", "javascript: trackOutboundLink('" + anchorHREF + "');")
    }
   }
  }

Note: This code fires on DOM Ready.

I am not asking for code review on the google part, just my custom loop. Do you feel as though my loop is going to have good browser support? >IE8? How could I Improve this code?


texts: Finding the nearest agents to a customer using IComparable

texts:
I got a C# class:

public class Agent
{
    public string AgentId { set; get; }
    public double Longitude { set; get; }
    public double Latitude { set; get; }
}

There are several agents in several different locations. During the program's lifetime, they can receive a call to another (latitude, longitude) point which is unknown during runtime. I got an API to calculate the distance in meters between their location and the given point. What I need eventually is to find the 5 closest agents to the given point.

What I did in order to achieve this is adding another class:

public class AgentDistance : Agent, IComparable<AgentDistance>
{

    public AgentDistance(Agent agent)
    {
        if(agent == null)
        {
            throw new Exception("Can't initalize agent with distance since agent is null");
        }
        this.AgentId = agent.AgentId;
        this.Latitude = agent.Latitude;
        this.Longitude = agent.Longitude;
    }

    public double Distance { set; get; }

    public int CompareTo(AgentDistance other)
    {
        if(other == null)
        {
            return 1;
        }
        return Distance.CompareTo(other.Distance);
    }
}

And the usage:

var agents = db.GetAgents();
if(agents == null || agents.Count == 0)
{
    Console.WriteLine("No Results");
}
List<AgentDistance> agentsWithDistance = new List<AgentDistance>();
foreach(Agent agent in agents)
{
    double res = ws.GetDistanceMeters(agent.Latitude, agent.Longitude, customerLatitude, customerLongitude);
    agentsWithDistance.Add(new AgentDistance(agent) { Distance = res });
}
agentsWithDistance.Sort();
for(int i = 0; i < 5; i++)
{
    Console.WriteLine(string.Format("agent_id:  {0}  distance: {1} m", agentsWithDistance[i].AgentId, agentsWithDistance[i].Distance));
}

It works, but is there a more elegant way to do it? I'm not sure if adding another class might be a bit redundant since all it does is just adding a property for sorting, but adding the distance property to the Agent class, doesn't make so much sense.


texts:
Can I somehow make this a bit cleaner using Math.[Something], without making a method for it?

int MaxSpeed = 50;

if (Speed.X > MaxSpeed)
    Speed.X = MaxSpeed;

if (Speed.X < MaxSpeed * -1)
    Speed.X = MaxSpeed * -1;

if (Speed.Y > MaxSpeed)
    Speed.Y = MaxSpeed;

if (Speed.Y < MaxSpeed * -1)
    Speed.Y = MaxSpeed * -1;


texts:
Solution to bounded knapsack 01 problem. Once again comprehensive description is difficult in this space, refer here. Looking for code review. optimizations and best practices.

final class Item {
    private final int value;
    private final int weight;

    public Item (int value, int weight) {
        if (value == 0) {
            throw new IllegalArgumentException("The value " + value + " should be positive.");
        }
        if (weight == 0) {
            throw new IllegalArgumentException("The weight " + weight + " should be positive.");
        }

        this.value = value;
        this.weight = weight;
    }

    public int getValue() {
        return value;
    }

    public int getWeight() {
        return weight;
    }
}

public final class Knapsack01 {

    private Knapsack01() {  }

    /**
     * Returns the maximum value, given set of items and maxweight
     *
     * @param items         the set of items.
     * @param maxWeight     the max weight
     * @return              the max value obeying the constraints
     */
    public static int getMaxValue (Item[] items, int maxWeight) {
        if (maxWeight <= 0) {
            throw new IllegalArgumentException("the maxweight: " + maxWeight + " should be positive");
        }

        int[][] knapsack = new int[items.length + 1][maxWeight + 1];

        for (int item = 0; item <=items.length; item++) {
            for (int weight = 0;  weight <= maxWeight; weight++) {

                if (item == 0 || weight == 0) {
                    continue;
                }

                int itemWeight = items[item - 1].getWeight();
                if (weight >= itemWeight) {
                    int remainingWeight = weight -  itemWeight;
                    // check the max value upto remainingWieght, the we might have computed before.
                    int valueUptoRemainingWeight = knapsack[item - 1][remainingWeight];
                    // how about trying currentItem + remainingItem ?
                    int tentativeValue = items[item - 1].getValue() + valueUptoRemainingWeight;
                    // compare this against previously calculated max-value
                    int previousMaxValue = knapsack[item - 1][weight];

                    knapsack[item][weight] = Math.max(tentativeValue, previousMaxValue);

                } else {
                    knapsack[item][weight] = knapsack[item - 1][weight];
                 }
            }
        }

        return knapsack[items.length][maxWeight];
    }

    public static void main(String[] args) {
        Item i1 = new Item( 60, 10);
        Item i2 = new Item(100, 20);
        Item i3 = new Item(120, 30);

        Item[] items = new Item[3];
        items[0] = i1;
        items[1] = i2;
        items[2] = i3;

        assertEquals(180, getMaxValue(items, 40));
        assertEquals(220, getMaxValue(items, 50));
        assertEquals(280, getMaxValue(items, 60));
        assertEquals(280, getMaxValue(items, 60));
    }
}


texts:
This function formats a string by replacing every occurrence of '{n}' with the corresponding argument that was passed to the function where n is an index that starts at 0. The same index can be used multiple times and the order is irrelevant. If n is out of bounds or cannot be converted to an integer number I just add '{n}' to the result. The function is intended to be used e.g with config files that can be changed by the user where it would be unsafe to use sprintf. The use of std::ostringstream allows me to pass any type that has an overloaded << operator. I was considering using iterators in the loops but I'm not sure whether that would gain anything.

#pragma once

#include <string>
#include <vector>
#include <sstream>
#include <string_view>

namespace util::str{
    inline void to_string_vector(std::vector<std::string>&){} //Dummy used to end recursion

    template<typename T, typename ... Args>
    void to_string_vector(std::vector<std::string>& result, const T& t, Args&& ...args){
        result.push_back((std::ostringstream{} << t).str());
        to_string_vector(result, args...);
    }

    template<typename ... Args>
    std::string format(std::string_view fmt, Args&& ...args){
        std::string result;
        std::vector<std::string> values;

        result.reserve(fmt.size());
        to_string_vector(values, args...);

        for(std::size_t first = 0; first < fmt.size(); ++first){
            if(fmt[first] == '{'){
                for(std::size_t second = first + 1; second < fmt.size(); ++second){
                    if(fmt[second] == '}'){
                        try{
                            std::size_t index = std::stoi(std::string{fmt.substr(first + 1, second - first - 1)});

                            if(index < values.size())
                                result += values[index];
                            else
                                result += fmt.substr(first, second - first + 1);
                        }catch(...){
                            result += fmt.substr(first, second - first + 1);
                        }

                        first = second;

                        break;
                    }else if(fmt[second] == '{'){
                        result += fmt.substr(first, second - first);
                        first = second - 1;

                        break;
                    }
                }
            }else{
                result.push_back(fmt[first]);
            }
        }

        return result;
    }
}


texts: Safe, fully standards-following integer abs in C

texts:
Here's a bit tricky one, because AFAIK there is no existing platform, where conditionally compiled part of the code would actually get included by compiler, so it is entirely up to the human review to see if it is correct.

The purpose is to have abs function, which does not trigger undefined behavior with any user input, on any C99 standard compliant compiler, on any platform, and in the theoretical case of result not fitting in the return type, return maximum value that fits.

Apart from any bugs, blunders etc, the real challenge is to come up with a (maybe theoretical) platform where the code doesn't produce desired result, or (hopefully) be reasonably certain that it works in all cases allowed by the standard.

// function to review
#include <inttypes.h>

uintmax_t maxed_abs(intmax_t i) {
    if (i < 0) {
#if UINTMAX_MAX == INTMAX_MAX && INTMAX_MIN < -INTMAX_MAX
        // catch the theoretical case of 2's complement platform,
        // where unsigned and signed have same number of value bits
        if (i == INTMAX_MIN) return UINTMAX_MAX;
#endif
        return -(uintmax_t)i;
    }
    return (uintmax_t)i;
}

// test code
#include <stdio.h>

int main(void)
{
    printf("Enter int in range %jd .. %jd:\n > ", INTMAX_MIN, INTMAX_MAX);
    intmax_t i;
    if (scanf("%jd", &i) == 1) {
        printf("Result: |%jd| = %ju\n", i, maxed_abs(i));
    }
}


texts: Two similar functions for writing data to binary file using BinaryWriter

texts:
I have two functions for writing data to binary file using BinaryWriter.
The first function has single data object as argument and looks as below:

    // write single data object to binary file
    public void AddHeaderToIndexer(string path, RollHeader header)
    {
        bool isDone = false;
        bool error = false;

        DateTime quitTime = DateTime.Now.AddMilliseconds(500);

        while (!isDone && DateTime.Now < quitTime)
        {
            try
            {
                BinaryWriter writer;
                using (writer = new BinaryWriter
                    (File.Open(path, FileMode.OpenOrCreate)))
                {
                    writer.Seek((int)writer.BaseStream.Length, new SeekOrigin());
                    WriteSingleHeader(writer, header);

                    isDone = true;
                    if (error)
                        Program.logger.Write(LogLevel.Error, "Done after timeout.");
                }

                SetReadRightToFileForEveryone(path);
            }
            catch (IOException ex)
            {
                if (!error)
                    Program.logger.Write(LogLevel.Error, ex.Message);
                error = true;
            }
        }
    }

The second is very similar, with only difference on accepting List of data objects and writing all List members to binary file. Actually, BinaryWriter is opened in Create unlike the first function, which uses OpenOrCreate.

    // write list of fdata objects to binary file
    public void WriteHeadersToIndexer(string path, List<RollHeader> headers)
    {
        bool isDone = false;
        bool error = false;

        DateTime quitTime = DateTime.Now.AddMilliseconds(500);

        while (!isDone && DateTime.Now < quitTime)
        {
            try
            {
                BinaryWriter writer;
                using (writer = new BinaryWriter
                    (File.Open(path, FileMode.Create)))
                {
                    foreach (RollHeader header in headers)
                        WriteSingleHeader(writer, header);

                    isDone = true;
                    if (error)
                        Program.logger.Write(LogLevel.Error, "Done after timeout.");
                }

                SetReadRightToFileForEveryone(path);
            }
            catch (IOException ex)
            {
                if (!error)
                    Program.logger.Write(LogLevel.Error, ex.Message);
                error = true;
            }
        }
    }

I'm not able to find some elegant solution, how to separate all duplicate code, which is around the using BinaryWriter block. Also, you will maybe find more elegant solution of my error handling in this case. I'll be glad for such comments, too.


texts: More convenient way to use comparators in Kotlin

texts:
In Kotlin comparison operators can be used instead of compareTo method:

a > b   // a.compareTo(b) > 0
a < b   // a.compareTo(b) < 0
a >= b  // a.compareTo(b) >= 0
a <= b  // a.compareTo(b) <= 0

It's convenient and makes comparisons a lot more readable. However, these operators cannot be used if there is no suitable compareTo method, but there is  a suitable Comparator.

To make it possible to use them in this case, I've created a use extension function for a Comparator interface:

inline fun <T, R> Comparator<T>.use(block: ComparatorDSL<T>.() -> R) =
    ComparatorDSL(this).run(block)

Where ComparatorDSL is the following class:

inline class ComparatorDSL<T>(private val comparator: Comparator<T>) {
    operator fun T.compareTo(other: T) = comparator.compare(this, other)
}

Now I can use it like this:

comparator.use { a > b } // comparator.compare(a, b) > 0

Questions:

Is comparator.use { a > b } more readable than comparator.compare(a, b) > 0?
Is it a good idea to replace use with invoke operator or make this function infix?
Any improvement suggestions that you can think of


texts: Nested loop with synchronous and asynchronous behavior

texts:
The problem is as follows. I have an array of objects like so:

let myObj = [
{'db1':['doc1','doc2','doc3']},
{'db2':['doc4','doc5']},
{'db3':['doc7','doc8','doc9','doc10']}
]

Note that this is a data structure I decided to use for the problem and can be changed if it can improve the overall implementation. The actual db and document ids are read from a text file formatted as below.

"db1","doc1"
"db1","doc2"
...

My app will iterate through the db list synchronously. Inside each db iteration, there will be an asynchronous iteration of the document list. Each document will be retrieved, processed and saved back to the db.

So basically at any given instance: one db, but multiple documents.

I have a working implementation of the above like so:

dbIterator: the synchronous outer loop to iterate dbs. The callback passed to docIterator will trigger the next iteration.

const dbIterator = function (x) {
  if (x < myObj.length) {
    let dbObj = myObj[x];
    let dbId = Object.keys(dbObj)[0];
    docIterator(dbId, dbObj[dbId], ()=>dbIterator(x+1));
  } else {
    logger.info('All dbs processed');
  }
};

docIterator: the asynchronous loop to iterate docs. The callback cb is called after all documents are processed. This is tracked via the docsProcessed and docsToBeProcessed variables

const docIterator = function(dbId, docIds, cb){
  //create connection
  targetConnection = //some config for connection to dbId
  let docsProcessed = 0;
  let docsToBeProcessed = docIds.length;

  //asynchronous iteration of documents
  docIds.forEach((docId)=>{
    getDocument(docId, targetConnection).then((doc)=>{
      //process document
      processDoc(doc, targetConnection).then(()=>{
        //if processing is successful
        if (++docsProcessed >= docsToBeProcessed) {
          cb();
        }
      })
       //if processing fails
      .catch((e) => {
        logger.error('error when processing document');
        if (++docsProcessed >= docsToBeProcessed) {
          cb();
        }
      });

    }).catch((e)=>{
      logger.error('error when retrieving document: ');
      if (++docsProcessed >= docsToBeProcessed) {
        cb();
      }
    });
  });
};

processDoc: used to process and save an individual document. This returns a promise that gets resolved when the document processing is done which in turn increments docsProcessed and conditionally (docsProcessed >= docsToBeProcessed) calls the call back passed into docIterator

const processDoc = function(doc, targetConnection) {

  return new Promise(function(resolve, reject) {
    if(shouldThisDocBeProcessed(doc){
      let updatedDoc = logic(doc);
      targetConnection.insert(updatedDoc, updatedDoc._id,
        function (error, response) {
          if (!error){
            logger.info('updated successfully');
          } else {
            logger.error('error when saving doc');
          }
          resolve();
        }
      );
    } else {
      resolve();
    }
  })
};

This works as expected but for me this implementation is sub-optimal and messy. I'm pretty sure this can be improved upon and most importantly a chance to better understand and implement solutions to synchronous and asynchronous problems.

I'm open to constructive criticism. So how can this be improved?


texts: Implementing a faster inbound neighbour similarity in Networkx

texts:
Given a directed graph G of 20+ million edges and approximately 2 million unique nodes, can this function/process be made faster on a dataset of 40k edges?

The current speed is at ~1.8 seconds per edge.

import pandas as pd
import networkx as nx

# main feature calculator
def jacard_inbound(u,v):
    preds = G.predecessors(v)
    result = [jacard_coef(u,x) for x in preds]
    return sum(result), max(result), sum(result)/len(result)

# jacquard's coefficient & helper functions
def jacard_coef(u,v):
    return common_friends(u,v)/total_friends(u,v)

def total_friends(u,v):
    return len(set(Gamma(u)).union(Gamma(v)))

def common_friends(u,v):
    return len(set(Gamma(u)).intersection(Gamma(v)))

# to cache calculated results
gamma_dict = dict()
def Gamma(u):
    s = gamma_dict.get(u)
    if s is None:
        s = set(G.successors(u)).union(G.predecessors(u))
        gamma_dict[u]=s
    return s

Running example:

# sample graph
G = nx.DiGraph()
G.add_edges_from([(1,2), (1,3), (2,3), (3,4), (3,5), (7,1), (5,6), (8,2), (9,0)])

# sample edges
dataset = pd.DataFrame(columns = ['source','target'])
dataset['target'] = [3, 6, 2, 3]
dataset['source'] = [2, 1, 8, 1]

t = time.time()
dataset['jacard_inbound'] = dataset[['source','target']].apply(lambda x: jacard_inbound(x['source'],x['target']), axis=1)
print(time.time() - t)


texts: Count elements in a collection based on a condition [Java 8]

texts:
Came across this question here: Write a generic method to count the number of elements in a collection that have a specific property (for example, odd integers, prime numbers, palindromes).

Following is my solution:

Counter.java

public class Counter {
    public static <T> long countIf(Collection<T> collection, Predicate<T> predicate) {
        return collection.stream()
                         .filter(predicate)
                         .count();
    }
}

Behaviours.java

public class Behaviours {

    public static boolean checkEvenNumber(final int num) {
        return num % 2 == 0;
    }

    public static boolean checkOddNumber(final int num) {
        return num % 2 != 0;
    }

    public static boolean checkPrimeNumber(final int num) {
        if (num == 0 || num == 1) {
            return false;
        }

        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkPalindrome(final String word) {
        for (int i = 0; i < word.length() / 2; i++) {
            if (word.charAt(i) != word.charAt(word.length() - 1 - i)) {
                return false;
            }
        }
        return true;
    }
}

CounterTest.java

public class CounterTest {

    /**
     * Counting odd numbers.
     */
    @Test
    public void testCountingOddNumbers() {
        System.out.println("testCountingOddNumbers");
        List<Integer> ci = Arrays.asList(1, 2, 3, 4, 5, 6);
        long expected = 3l;
        long actual = Counter.countIf(ci, Behaviours::checkOddNumber);
        Assert.assertEquals(expected, actual);
    }

    /**
     * Counting prime numbers.
     */
    @Test
    public void testCountingPrimeNumbers() {
        System.out.println("testCountingPrimeNumbers");
        List<Integer> ci = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        long expected = 4l;
        long actual = Counter.countIf(ci, Behaviours::checkPrimeNumber);
        Assert.assertEquals(expected, actual);
    }

    /**
     * Counting palindromes
     */
    @Test
    public void testCountingPalindromes() {
        System.out.println("testCountingPalindromes");
        List<String> cs = Arrays.asList("madam", "test", "tacocat", "hello");
        long expected = 2l;
        long actual = Counter.countIf(cs, Behaviours::checkPalindrome);
        Assert.assertEquals(expected, actual);
    }

}

Output

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.mycompany.demo.assignment001.question001.CounterTest
testCountingPalindromes
testCountingPrimeNumbers
testCountingOddNumbers
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.088 sec

Does my implementation take care of all the scenarios or am I missing something?
Can any other Java 8 concept be used here?
Please also review overall correctness.


texts:
I am new to Python and only just started learning about functions. I stumbled upon a question which recommends using function to print triangles in such a format:

Enter height: 5

         /\
        /  \
       /    \
      /      \
     /________\
    /\        /\
   /  \      /  \
  /    \    /    \
 /      \  /      \
/________\/________\

Enter height: 2

   /\
  /__\
 /\  /\
/__\/__\

Although I have gone through and successfully coded for the requirements. I feel though there needs to be a better approach. I was wondering if someone could review my code and point me in the right direction as to how I might improve on it.

This is what I currently have:

import sys

def triangle(height):
    print()
    max = (height * 2) - 1
    mid = 0
    while max > height:
        statement = " " * max + "/" + " " * mid + "\\"
        print(statement)
        max -= 1
        mid += 2
    statement = " " * max + "/" + "_" * mid + "\\"
    max -= 1
    print(statement)
    small = 0
    while max > 0:
        statement = " " * max + "/" + " " * small + "\\" + " " * mid + "/" + " " * small + "\\"
        print(statement)
        mid -= 2
        max -= 1
        small += 2
    statement = " " * max + "/" + "_" * small + "\\" + " " * mid + "/" + "_" * small + "\\"
    print(statement)
    pass

if __name__ == "__main__":
    userInput = input("Enter height: ")
    try:
        userInput = int(userInput)
    except ValueError:
        sys.exit("\nInvalid height.")
    if userInput < 2 or userInput > 20:
        sys.exit("\nInvalid height.")
    triangle(userInput)

I am curious as to there is a way to only code for one triangle and print multiple.


texts: Print all nodes that are at distance k from a leaf node

texts:
Given a binary tree and a positive integer \$k\$, print all nodes that
  are distance \$k\$ from a leaf node.

  Here, the meaning of distance is different from the previous post.
  Here, \$k\$ is the distance from a leaf means \$k\$ levels higher than
  a leaf node. For example, if \$k\$ is more than height of binary tree,
  then nothing should be printed. Expected time complexity is \$O(n)\$
  where \$n\$ is the number nodes in the given binary tree.

I'm looking for code review, optimizations and best practices.  I'm verifying \$O(n)\$ to be both the time and space complexity.

public class KDistanceFromLeaves<T> {

    private TreeNode<T> root;

    public KDistanceFromLeaves(List<T> items) {
        create(items);
    }

    private void create (List<T> items) {
        root = new TreeNode<T>(items.get(0));

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<T>(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<T>(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    public static class TreeNode<T> {
        private TreeNode<T> left;
        private T item;
        private TreeNode<T> right;

        TreeNode(T item) {
            this.item = item;
        }
    }

    public List<T> kDistanceFromLeaf(int k) {
        final List<T> list = new ArrayList<>();
        final List<Boolean> booleanList = new ArrayList<>();
        recurse(root, k, new ArrayList<T>(), list, booleanList);
        return list;
    }

    private void recurse(TreeNode<T> node, int k, List<T> items, List<T> list, List<Boolean> visited) {

        if (node == null) return;

        if (node.left == null && node.right == null && k <= items.size() && !visited.get(items.size() - k)) {
                list.add(items.get(items.size() - k));
                visited.set(items.size() - k, true);
        }

        items.add(node.item);
        visited.add(false);

        recurse(node.left, k, items, list, visited);
        recurse(node.right, k, items, list, visited);

        items.remove(items.size() - 1);
        visited.remove(visited.size() - 1);
    }
}

public class KDistanceFromLeavesTest {

    @Test
    public void testCompleteTree() {
        KDistanceFromLeaves<Integer> kd = new KDistanceFromLeaves<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        assertEquals(Arrays.asList(2, 3), kd.kDistanceFromLeaf(1));
        assertEquals(Arrays.asList(1), kd.kDistanceFromLeaf(2));
        assertEquals(Collections.EMPTY_LIST, kd.kDistanceFromLeaf(3));
        assertEquals(Collections.EMPTY_LIST, kd.kDistanceFromLeaf(4));
    }

    @Test
    public void testInCompleteTree() {
        KDistanceFromLeaves<Integer> kd1 = new KDistanceFromLeaves<Integer>(Arrays.asList(1, 2, 3, 4, 5, null, null, null, null, 6, 7));
        assertEquals(Arrays.asList(2, 5, 1), kd1.kDistanceFromLeaf(1));
        assertEquals(Arrays.asList(1, 2), kd1.kDistanceFromLeaf(2));
        assertEquals(Arrays.asList(1), kd1.kDistanceFromLeaf(3));
        assertEquals(Collections.EMPTY_LIST, kd1.kDistanceFromLeaf(4));
    }
}


texts: Code for simplifying the creation of Dimension Objects

texts:
I have a class that I use to represent a distance called Dimension.

Here is its four constructors:

    /// <summary>
    /// Accepts any valid architectural string value for input.
    /// </summary>
    public Dimension(string passedArchitecturalString)
    {
         storeArchitecturalStringAsInternalUnit(passedArchitecturalString);
    }

    /// <summary>
    /// Accepts standard types for input.
    /// </summary>
    public Dimension(DimensionType passedDimensionType, double passedInput)
    {
        storeAsInternalUnit(passedDimensionType, passedInput);
    }

    /// <summary>
    /// copy constructor - create a new Dimension with the same _intrinsicValue as the passed Dimension
    /// </summary>
    public Dimension(Dimension passedDimension)
    {
        _intrinsicValue = passedDimension._intrinsicValue;
    }

    /// <summary>
    /// Zero Constructor
    /// </summary>
    public Dimension()
    {
        _intrinsicValue = 0;
    }

This question gives some more background on my Dimension Class.

Because it is a class that I use so often and it usually uses inches. I had to write out the one of the full constructors every time that I wanted to use it.

Dimension inchDimension = new Dimension(DimensionType.Inch, 14.1875);

This became a major pain when creating things like my 3 dimensional Point object:

Dimension xDimension = new Dimension(DimensionType.Millimeter, 0);
Dimension yDimension = new Dimension(DimensionType.Millimeter, 0);
Dimension zDimension = new Dimension(DimensionType.Millimeter, 0);

        Point p = new Point(xDimension, yDimension, zDimension);

So I created a class to generate these objects called DimensionGenerator.

public class DimensionGenerator
{

    /// <summary>
    /// Default generator sets to inches
    /// </summary>
    public DimensionGenerator()
    {
        _internalType = DimensionType.Inch;
    }

    /// <summary>
    /// This constructor allows you to specify a static type and change it later
    /// </summary>
    /// <param name="wantedType">DimensionType to use for now</param>
    public DimensionGenerator(DimensionType wantedType)
    {
        _internalType = wantedType;
    }

    DimensionType _internalType;
    public DimensionType DimensionOutputType
    {
        get { return _internalType; }
        set { _internalType = value; }
    }

    public Dimension MakeDimension(double passedValue)
    {
        return new Dimension(_internalType, passedValue);
    }
}

I seem to use it a LOT. its less typing to just create on of these instead of using a Dimension constructor. Especially when writing Unit Tests where numbers may not really matter and all I care about are their equality or etc. Isn't it terribly wasteful to create a new one of these in most methods in my application? Should I make a bunch of static DimensionGenerators that only output a specific type? What should I consider when having a class like this?


texts: "Does an array contain the same elements as another array?"

texts:
Write a static method named contains that accepts two arrays of
  integers a1 and a2 as parameters and that returns a boolean value
  indicating whether or not a2's sequence of elements appears in a1
  (true for yes, false for no). The sequence of elements in a2 may
  appear anywhere in a1 but must appear consecutively and in the same
  order. For example, if variables called list1 and list2 store the
  following values:

  int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8}; int[] list2 = {1, 2, 1};

  Then the call of contains(list1, list2) should return true because
  list2's sequence of values {1, 2, 1} is contained in list1 starting at
  index 5. If list2 had stored the values {2, 1, 2}, the call of
  contains(list1, list2) would return false because list1 does not
  contain that sequence of values. Any two lists with identical elements
  are considered to contain each other, so a call such as
  contains(list1, list1) should return true.

  You may assume that both arrays passed to your method will have
  lengths of at least 1. You may not use any Strings to help you solve
  this problem, nor methods that produce Strings such as
  Arrays.toString.

I'm looking for general feedback to improve my future code. I'm intent on learning Java, so any style tips would be well appreciated. Other ways to accomplish this task?

public static boolean contains(int[] list1, int[] list2) {
    for (int i = 0; i <= (list1.length - list2.length); i++) {
        if (list1[i] == list2[0]) {
            for (int j = 1; j < list2.length; j++) {
                if (list1[i + j] == list2[j]) {
                    if (j == (list2.length - 1)) {
                        return true;
                    }
                } else {
                    break;
                }
            }
        }
    }
    return false;
}


texts: SICP - exercise 2.69 - generate a huffman tree from a set of ordered leaves

texts:
From SICP

  Exercise 2.69: The following procedure takes as its argument a list of
  symbol-frequency pairs (where no symbol appears in more than one pair)
  and generates a Huffman encoding tree according to the Huffman
  algorithm.

(define (generate-huffman-tree pairs)
  (successive-merge
   (make-leaf-set pairs)))

  Make-leaf-set is the procedure given above that transforms the list of
  pairs into an ordered set of leaves. Successive-merge is the procedure
  you must write, using make-code-tree to successively merge the
  smallest-weight elements of the set until there is only one element
  left, which is the desired Huffman tree. (This procedure is slightly
  tricky, but not really complicated. If you find yourself designing a
  complex procedure, then you are almost certainly doing something
  wrong. You can take significant advantage of the fact that we are
  using an ordered set representation.)

make-code-tree creates a tree from two branches, make those branches as left and right branches respectively, combine all symbols of the branches as its own set of symbols, and finally add the weights of the branches as its own weight.
adjoin-set inserts a tree to the set while remaining ordered based on the weight of the items.

Though I am confident my code is correct, I am extremely unsure of my solution. What's bothering me is the hint that it's tricky. It does gave correct results for all tests I did. I have thought of alternative ways of doing this, but the procedures I came up with were very complex. Also, I think this is very slow. Please review my code.

(define (successive-merge leaves)
(if     (= (length leaves) 1)
        (car leaves)
    (successive-merge (adjoin-set (make-code-tree (car leaves) (cadr leaves)) (cddr leaves)))))

How can I make this code better and faster? And are there better ways of doing this?


texts: Calculate the centroid of a collection of complex numbers

texts:
In working on another problem, one component I needed was to calculate the centroid of a collection of complex objects.  The well-known way to calculate this is to simply average the real and imaginary parts.  To accommodate either std::complex<double> or std::complex<float>, I have created the following code as a template.  Everything works as expected.
centroid.cpp
#include <iostream>
#include <complex>
#include <vector>
#include <numeric>

template<class ComplexIterator>
typename ComplexIterator::value_type centroid(ComplexIterator a, ComplexIterator b) {
    return std::accumulate(a, b, typename ComplexIterator::value_type{0})
            / typename ComplexIterator::value_type{b-a};
}

int main() {
    std::vector<std::complex<float>> points{ {4,5}, {30,6}, {20,25} };
    std::cout << centroid(points.begin(), points.end()) << "\n";
}

Sample output:

(18, 12)

My questions

The compiler rightly warns that in the calculation of the denominator in the template, there is a narrowing conversion.  I can't think of a way to elegantly handle that.  Should I just ignore it?
If given an empty set, the code returns a value of (-nan, -nan) which works for me, but for general use, should I throw an exception instead?
Should I use std::enable_if or C++20 requires to constrain the function to require only floating point numbers?
I thought about calling it average because technically, it would happily compute the average of, say, a std::vector<float> but for my purposes, centroid seemed apt.  What do you think of that choice?

Any other ways to improve this would be good as well.


texts:
This function calculates the standard deviation of a patch, given a kernel size and greyscale OpenCV image. The middle pixel of the patch is kept if stdev of the patch is below the given threshold, else it is rejected. This is done for each pixel except the border.

I have never worked with OpenMP or optimization of C++, so all help is welcome. I'm probably doing some very stupid things that slow down the process drastically. It doesn't need to be the fastest, but I think some easy tricks will significantly speed it up.

#include "stdafx.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/photo/photo.hpp"
#include <stdlib.h>
#include <stdio.h>
#include "utils.h"
#include <windows.h>
#include <string.h>
#include <math.h>
#include <numeric>

using namespace cv;
using namespace std;
Mat low_pass_filter(Mat img, int threshold, int kernelSize)
{
    unsigned char *input = (unsigned char*)(img.data);
    Mat output = Mat::zeros(img.size(), CV_8UC1);
    unsigned char *output_ptr = (unsigned char*)(output.data);

    #pragma omp parallel for
    for (int i = (kernelSize - 1) / 2; i < img.rows - (kernelSize - 1) / 2; i++){
        for (int j = (kernelSize - 1) / 2; j < img.cols - (kernelSize - 1) / 2; j++){
            double sum, m, accum, stdev;
            vector<double> v;
            v.reserve(kernelSize*kernelSize);
            // Kernel Patch
            for (int kx = i - (kernelSize - 1) / 2; kx <= i + (kernelSize - 1) / 2; kx++){
                for (int ky = j - (kernelSize - 1) / 2; ky <= j + (kernelSize - 1) / 2; ky++){
                    v.push_back((double)input[img.step * kx + ky]);//.at<uchar>(kx, ky));
                }
            }
            sum = std::accumulate(std::begin(v), std::end(v), 0.0);
            m = sum / v.size();

            accum = 0.0;
            std::for_each(std::begin(v), std::end(v), [&](const double d) {
                accum += (d - m) * (d - m);
            });

            stdev = sqrt(accum / (v.size() - 1));
            if (stdev < threshold){
                output_ptr[img.step * i + j] = input[img.step * i + j];
            }
        }
    }
    return output;
}