texts: Sort all even numbers in ascending order and then sort all odd numbers in Descending order Java

texts:
Given an array of integers (both odd and even), the task is to sort
  them in such a way that the first part of the array contains odd
  numbers sorted in descending order, rest portion contains even numbers
  sorted in ascending order.

  Examples:

Input  :

A[] = {1, 2, 3, 5, 4, 7, 10}

Output :

A[] = {7, 5, 3, 1, 2, 4, 10}

Input  :

A[] = {0, 4, 5, 3, 7, 2, 1}

Output :

A[] = {7, 5, 3, 1, 0, 2, 4}

  Input:

  The first line of input contains an integer T denoting the no
  of test cases. Then T test cases follow. Each test case contains an
  integer N denoting the size of the array. The next line contains N
  space separated values of the array.

  Output:

  For each test case in a new line print the space separated
  values of the  new transformed array.

Constraints:

1<=T<=100

1<=N<=100 0

0<=A[]<=100

  Example:

  Input:

  2
  7
  1 2 3 5 4 7 10
  7
  0 4 5 3 7 2 1

  Output:

  7 5 3 1 2 4

  10 7 5 3 1 0 2 4

My approach:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

class GFG {

    private static List<Integer> sortListOrder (List<Integer> list) {
        List<Integer> oddList = new ArrayList<>();
        List<Integer> evenList = new ArrayList<>();

        for (Integer elem : list) {
            if (elem%2 != 0) {
                oddList.add(elem);
            }
            else {
                evenList.add(elem);
            }
        }
        Collections.sort(evenList);
        Collections.sort(oddList);
        List<Integer> reversedList = new ArrayList<>();
        for (int i = oddList.size() - 1; i >= 0; i--) {
            reversedList.add(oddList.get(i));
        }

        reversedList.addAll(evenList);

        return reversedList;
    }

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

        while(numTests-- > 0) {
            int size = sc.nextInt();
            List<Integer> list = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                int elem = sc.nextInt();
                list.add(elem);
            }

            List<Integer> sortedList = sortListOrder(list);

            for (Integer elem : sortedList) {
                System.out.print(elem + " ");
            }
            System.out.println();

        }
        sc.close();
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts:
I have two lists of coordinates,

lat = [-23.23, -44.23, -12.23]
lon = [-21.23, -14.23, -62.23]

and I generate a tuple of lat long pairs with zip:

latlon = zip(lat, lon)

and that gives the expected result. Now there is a very common pattern of generating lines with the points. It is common to do something like

    line_coords = []
    for i in xrange(len(coords)-1):
        line_coords.append([tuple(coords[i]), tuple(coords[i+1])])

so the result is now a list of tuples, each tuple an list of beginning and end of a line:

line_coords
[[(-23.23, -21.23), (-44.23, -14.23)], [(-44.23, -14.23), (-12.23, -62.23)] ]

and it get worse if the line needs to come back to the beginning. This looks like an anti-pattern. Is there a name for this pattern and a more elegant way to do it?


texts: Printing a Binary Tree top-down (column wise)

texts:
We have a binary tree, suppose like this:

       8
     /   \
    6     10
   / \   /  \
  4   7 9    12
 / \
3   5

We have to print this binary tree in top-down manner - column wise. Note that, 8, 7 & 9 would be considered in same column. So the required output should be:

3
4
6 5
8 7 9
10
12

Currently I've implemented this problem using two maps, and one queue. Here's the method traversal(Node<T> node), which is invoked first time, passing the root node:

public void traverse(Node<T> node) {

    Queue<Node<T>> queue = new LinkedList<>();

    Map<Integer, List<Node<T>>> columnMap = new TreeMap<>();
    Map<Node<T>, Integer> map = new HashMap<>();

    queue.add(node);

    while (!queue.isEmpty()) {

        Node<T> temp = queue.poll();

        if (map.isEmpty()) {
            map.put(temp, 0);
            columnMap.put(0, new ArrayList<Node<T>>(Arrays.asList(temp)));
        }

        int column = map.get(temp);

        if (temp.left() != null) {
            queue.add(temp.left());

            if (columnMap.containsKey(column - 1)) {
                columnMap.get(column - 1).add(temp.left());
            } else {
                columnMap.put(column - 1, new ArrayList<Node<T>>(Arrays.asList(temp.left())));
            }

            map.put(temp.left(), column - 1);
        }

        if (temp.right() != null) {
            queue.add(temp.right());

            if (columnMap.containsKey(column + 1)) {
                columnMap.get(column + 1).add(temp.right());
            } else {
                columnMap.put(column + 1, new ArrayList<Node<T>>(Arrays.asList(temp.right())));
            }

            map.put(temp.right(), column + 1);
        }
    }

    for (Entry<Integer, List<Node<T>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

The idea is, starting from root node as column number 0, the left node will have column number -1, and the right node will have column number 1. Then the right node of the left node will again have column number 0. And similarly I proceed till I've exhausted all the nodes. I've used level order traversal for traversing.

The first map - Map<Node<T>, Integer> is used to get the column number for a particular node. I've used this map, so that I can get the column number of a node in O(1) time. For example, starting with root, I put a mapping - <root, 0>, in the map. And then, put an entry in columnMap - <0, root>, specifying there is currently root at column 0. I've used Queue for the purpose of level-order traversal (Well, it can be avoided by using pre-order, post-order or in-order).

Now, I remove the root from queue, and push it's two children. For left child, I've to find the column number based on it's parent (in this case, root). So, I get the column number for root from map. And subtract 1 from it to get column of left. If the column number is already in the columnMap, I just update the existing list of node for that column, else I add a new entry.

I thought of getting it done with just a single map, but I found it more clear.

Is there some better option? Currently, the code looks a bit complex to me. May be it can be improvised? I'm open to a completely different implementation too, provided it is more clear, and space and time efficient.


texts:
I'm aware that a function in the standard library exists. Please give me feedback regarding good coding conventions and standards.

fun main(arg: Array<String>) {
    val intList = listOf<Int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    println("Enter a valid number:")
    val x = readLine()!!.toIntOrNull() ?: run {
        println("You didn't type a valid number.")
        return
    }
    binarySearch(intList, x)
}

fun binarySearch(list: List<Int>, searchItem: Int){
    val mid = list.size / 2
    val isInFirstHalf =
                list
                    .take(mid)
                    .any { it == searchItem }
    do {
        val result =
                if (isInFirstHalf)
                    list.slice(0 until mid)
                else
                    list.slice(mid until list.size)
        println(result.joinToString())
        if (result.size == 1) break
        binarySearch(result, searchItem)
        return
    } while (true)
    println("Binary search found $searchItem.")
}


texts:
Just completed a piece of code - a credit card validation program in python - as a little side project. Having no experience with classes in the past, I decided to employ classes in this project.

I am wondering if you could review my code, both appraising the actual code, but also evaluate my use of OOP/classes.

The requirements for the program are:

  The user enters their name, postcode, the card code, and the card
  date.

  The eighth digit of the card code is removed and acts as a check digit

  The code is then reversed

  The 1st, 3rd, 5th, and 7th digits are multiplied by 2

  If the result of the multiplication is > 9, subtract 9 from it.

  If the sum of the 7 digits, and the check digit are divisable by 10,
  the code is valid

  The card date must also be in the future.

  Finally, output their name, postcode, card number, and whether it is
  valid or not.

The code:

"""Program used to check if a credit card is authentic."""
# !/usr/bin/env python
# -*- coding: utf-8 -*-

# Check it out
import datetime

class Customer:
    """Class representing the customer and their credit card details"""

    # Constructor
    def __init__(self):
        self.name = input("Name: ")
        self.postcode = input("Postcode: ")
        self.card_date = input("Card date: ")
        self.card_code = input("Card code: ").strip()

    def check_date(self):
        """Checks current date against the credit card's date. If it is valid, returns True; else False."""
        card = datetime.datetime.strptime(self.card_date, "%d/%m/%Y").date()
        if datetime.date.today() < card:
            return True
        else:
            return False

    def check_code(self):
        """Contains the algorithm to check if the card code is authentic"""

        code_list = list(str(self.card_code))
        check_digit = int(code_list[7])
        code_list.pop()
        # The last digit is assigned to be a check digit and is removed from the list.
        code_list.reverse()

        for item in code_list:
            temp_location = code_list.index(item)
            if is_even(temp_location):
                code_list[temp_location] = int(item) * 2
        # Loops over each digit, if it is even, multiplies the digit by 2.

        for item in code_list:
            temp_location = code_list.index(item)
            if int(item) > 9:
                code_list[temp_location] = int(item) - 9
        # For each digit, if it is greater than 9; 9 is subtracted from it.

        sum_list = 0
        for item in code_list:
            sum_list += int(item)
        # Calculates the sum of the digits

        code_total = sum_list + int(check_digit)

        if code_total % 10 == 0:
            return True
        else:
            return False
            # If the code is divisible by 10, returns True, else, it returns False.

    def check_auth(self):
        """Checks the card's authenticity. """
        if self.check_code() and self.check_date():
            print("----------------------")
            print("Valid")
            print(self.name)
            print(self.postcode)
            print(self.card_date)
            print(self.card_code)
        else:
            print("----------------------")
            print("Invalid")
            print(self.name)
            print(self.postcode)

def is_even(number):
    """Function used to test if a number is even."""
    if number % 2 == 0:
        return True
    else:
        return False

if __name__ == "__main__":
    customer().check_auth()


texts: Foobar Fuel Injection Perfection efficiency

texts:
I was writing this code and was using the BigInteger class because it needs to work with numbers up to 309 digits long, however it takes too long to run with numbers that are too big.  I was hoping to find a way to make it more efficient and faster, but have tried everything in my power.  Any suggestions?

public static int answer (String n) {
    return helper(new BigInteger(n));
}
public static int helper (BigInteger n) {
    BigInteger one = new BigInteger("1");
    BigInteger two = new BigInteger("2");
    BigInteger zero = new BigInteger("0");
    if (n.compareTo(two) == -1) {
        return 0;
    }
    if (n.mod(two).equals(zero)) {
        return helper(n.divide(two)) + 1;
    }
    return Math.min(helper(n.add(one).divide(two)) + 2, helper(n.subtract(one).divide(two)) + 2);
}


texts: jQuery plugin for allowing only digits to be entered in html form input

texts:
I wrote this small jQuery plugin to set some fields so that they allow only 0-9 digits to be entered.

I intended to do that by preventing user from typing, pasting or dropping non-digit content.

It seems to work (on Firefox), but I'd like to know if this code has some issue or unpredicted effect I'm not seeing now.

$.fn.onlyDigits = function () {
    return this.val("").off("keypress").on("keypress",
        function (evt) {
            evt = evt || window.evt;
            return /\d/.test("" + evt.originalEvent.key);
        }
    ).off("drop paste").on("drop paste",
        function (evt) {
            $(evt.target).on("input",
                function (evt2) {
                    evt2.target.value = evt2.target.value.replace(/\D+/g, "");
                    $(evt2.target).off("input");
                }
            );
        }
    );
}


texts: Pairwise distance and residual calculation

texts:
I have a code for calculating the pairwise distances and the residuals of my data (X, Y, Z). Data is quite large (average of 7000 rows) and so my interest is code efficiency. My initial code is

import tkinter as tk
from tkinter import filedialog
import pandas as pd
import, numpy as np
from scipy.spatial.distance import pdist, squareform

root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()

data = pd.read_excel(file_path)
data = np.array(data, dtype=np.float)
npoints, cols = data.shape

pwdistance = np.zeros((npoints, npoints))
pwresidual = np.zeros((npoints, npoints))
for i in range(npoints):
    for j in range(npoints):
        pwdistance[i][j] = np.sqrt((data[:,0][i]-data[:,0][j])**2 + (data[:,1][i]-data[:,1][j])**2)
        pwresidual[i][j] = (data[:,2][i]-data[:,2][j])**2

With the pwdistance, I changed it to the following below which works extremely good.

pwdistance = squareform(pdist(data[:,:2]))

Is there a pythonic way of calculating my pwresidual, so I do not need to use a loop and to enable my code to run faster?


texts:
I'm building an event recorder. So far the code looks clean, but I feel like I'm missing something that can make this code even better.

Is composition a better solution? If yes, how can I do it properly in this context. Do you know a better way to share the Recorder across all other components? Will it be better to initialize the recorder in app.js and then pass it to the other components (mouse, keyboard)?

Mouse.js and Keyboard.js look pretty much the same, except they record different event types. Is there a way to avoid repetition (stop and record method)? Just tell me what you think about the logic.

This needs to be flexible because I have no idea how many events I will need to record in the future.

app.js

export default (params) => {
  const container = document.getElementById(params.container),
        recorder = Recorder('session'),
        keyboard = Keyboard(),
        mouse = Mouse(container);

  const startRecording = () => {
    recorder.record('Start recording');
    keyboard.record();
    mouse.record();
  }

  const stopRecording = () => {
    keyboard.stop();
    mouse.stop();
    recorder.record('Stop recording');
  }

  const init = () => {
    document.getElementById('start').onclick = (e) => {
      e.preventDefault();
      startRecording();
    };
    document.getElementById('stop').onclick = (e) => {
      e.preventDefault();
      stopRecording();
    };
  }

  return {
    init
  }
}

recorder.js

import Data from '../db/eventsLog';
import moment from 'moment';

export default (type) => {
  const record = (input) => {
    const t = moment().unix();
    Data[type].push({t, event: input});
  }

  return {
    record
  }
}

keyboard.js

import Recorder from './recorder';

export default () => {
  const recorder = Recorder('keyboard');

  const initRecorder = (recording) => {
    document.onkeydown = (e) => {
      if (recording) {
        recorder.record(e);
      }
    };
  };

  const record = () => initRecorder(true);

  const stop = () => initRecorder(false);

  return {
    record,
    stop
  }
}

mouse.js

import Recorder from './recorder';

export default (container) => {
  const recorder = Recorder('mouse');

  const startRecording = (recording, e) => {
    if (recording) {
      recorder.record(e);
    }
  };

  const initRecorder = (recording) => {
    // Mouse mouve
    container.onmousemove = (e) => startRecording(recording, e);

    // Mouse Double click
    container.ondblclick = (e) => startRecording(recording, e);

    // Mouse Click
    container.onclick = (e) => startRecording(recording, e);
  };

  const record = () => initRecorder(true);

  const stop = () => initRecorder(false);

  return {
    record,
    stop
  }
}


texts: Multiple target method invocation wrapper

texts:
I'm currently working on a system using WCF to communicate between a Windows Service and one or multiple clients. Service is required to answer clients calls, as well as notify them of certain events, which is why I implemented a callback feature using simplified subscriber model. Callback interface has methods with various signatures and I'd like to use a single method to invoke one of them for all subscribers (placing enumerating over them and exception handling in one place). At first I tried approach with an enum containing interface methods and a switch statement to invoke particular method.

private enum CallbackFunc { Method1, Method2, Method3 }
private static void InvokeCallback(CallbackFunc callbackFunc, params object[] args)
{
    foreach (var subscriber in subscribers)
    {
        try
        {
            switch (callbackFunc)
            {
                case CallbackFunc.Method1:
                    subscriber.Method1((int)args[0]);
                    break;
                case CallbackFunc.Method2:
                    Foo foo = args[0] as Foo;
                    if (foo != null)
                        subscriber.Method2(foo , args.Length > 1 ? args[1] as List<Bar> : null);
                    break;
                case CallbackFunc.Method3:
                    subscriber.Method3((Bar)args[0], (Baz)args[1]);
                    break;
            }
        }
        catch
        {
            //error handling
        }
    }
}

This solution works, but I don't like it very much... it's missing finesse. I figured I could do it more universally using delegates, at which I failed because of different method signatures. Next step was to use reflection with the following result:

private static void InvokeCallback(System.Reflection.MethodInfo func, params object[] args)
{
    foreach (var subscriber in subscribers)
    {
        try
        {
            func.Invoke(subscriber, args);
        }
        catch
        {
            //error handling
        }
    }
}

As you can see the code is much nicer, but I began to doubt if this is actually a better solution (for example because of a little reflection overhead, less nice function call).

public static void Method1(int a)
{
    InvokeCallback(typeof(ICallback).GetMethod("Method1"), a);
    InvokeCallback(CallbackFunc.Method1, a);
}
public static void Method2(Foo foo, List<Bar> bars)
{
    InvokeCallback(typeof(ICallback).GetMethod("Method2"), foo, bars);
    InvokeCallback(CallbackFunc.Method2, foo, bars);
}
public static void Method3(Bar bar, Baz baz)
{
    InvokeCallback(typeof(ICallback).GetMethod("Method3"), bar, baz);
    InvokeCallback(CallbackFunc.Method3, bar, baz);
}

I'd like to ask you which of these approaches is better or suggest a better solution. Any help will be much appreciated, thanks in advance.


texts: Given a search string, fetch all movies results from the api

texts:
Was told this code was 'weird' and didn't pass the coding test. I tried to split up to show the different levels of abstraction but maybe I went overboard? I told them this in the walk through of the code as things like console logging would be something more like save to database or something more complex so it's its own abstraction.

const https = require('https');
/*
 * Complete the function below.
 * Use console.log to print the result, you should not return from the function.
 * Base url: https://jsonmock.hackerrank.com/api/movies/search/?Title=
 */
async function getMovieTitles(substr) {

    // get first page results
    const results = await fetchMoviePage(substr, 1);
    let matches = results.data.map(extractMovieTitle);

    // base case - if we only have one page of results then we done here
    if (results.total_pages === 1) {
        return sortAndPrintResults(matches);
    }

    // fill an incremented integer array from page 2 to last page
    const pages = fillRange(2, results.total_pages);

    // for each page fetch data and add to results list
    for await (const page of pages) {
        const { data } = await fetchMoviePage(substr, page);
        matches = matches.concat( data.map(extractMovieTitle) );
    }

    sortAndPrintResults(matches);
}

/**
 * send sorted results to stdout
 */
function sortAndPrintResults(results){
    console.log(results.sort().join('\n'));
}

/**
 * fetches a page of movie results.
 */
async function fetchMoviePage(substr, page) {
    try {
        return await fetchMatchingMovies(substr, page);

    } catch (error) {
        console.log(`Error retrieving movies for ${substr} on page ${page}: ${error}`);
        return {data:[]};
    }
}

/**
 * Fills an array of incremented integers from start to end
 */
function fillRange(start, end) {
    return Array(end - start + 1).fill().map((item, index) => start + index);
};

/**
 * returns the movie title from a movie object
 */
function extractMovieTitle(movie) {
    return movie.Title;
}

/**
 * fetch a list of movies matching a search string
 */
function fetchMatchingMovies(searchString, page) {
    const queryString = `https://jsonmock.hackerrank.com/api/movies/search/?Title=${searchString}&page=${page}`;

    return new Promise((resolve, reject) => {

        https.get(queryString, res => {
            let data = '';
            res.on('data', chunk => data += chunk);
            res.on('end', () => resolve(JSON.parse(data)));

        }).on('error', e => reject(e));
    });
}


texts: MapReduce program for finding low value hashes

texts:
For class we were to make a MapReduce program in Python to find low value hashes of our name. I have completed the assignment but want to try and speed it up. The program currently takes about 45s to complete. I would like to see if there are any suggestions on speeding it up some.

The requirements are to find hashes of your name with 5 leading 0's when printed in hex. We are to try 40 million nonces. I did a few naive implementations before I finally settled on what is below. What I do is send a dict of 40 consecutive numbers to use as multipliers in the Map function. The multiplier represents the range of millions to go through. So when mult = 0 I will use the nonces 0-1mil, when mult = 23 use the nonces 23mil-24mil.

#!/usr/bin/env python
import mincemeat

def mapfn(k, v):
    #Hash the string with the given nonce, if its good save it
    import md5
    #Create a md5 hash and fill it with out initial value
    #The "blockheader" in Bitcoin terms
    m = md5.new()
    m.update("Kevin")
    #Now, step through 1 million nonces with v as a multiplier
    for i in range(v*1000000, ((v+1)*1000000), 1):
        mPrime = m.copy()
        mPrime.update(str(i))
        hashOut = mPrime.hexdigest()
        if(hashOut[:5] == '0' * 5):
           yield hashOut, i
        else:
           pass #Hash trash!

def reducefn(k, vs):
    return (k, vs)

if __name__ == "__main__":
    #Import some useful code
    import sys
    import collections

    #Build the data source, just a list 0-39
    nonces = [i for i in range(0, 40)]
    datasource = dict(enumerate(nonces))

    #Setup the MapReduce server
    s = mincemeat.Server()
    s.mapfn = mapfn
    s.reducefn = reducefn
    s.datasource = datasource

    #Get the results of the MapReduce
    results = s.run_server(password="changeme")

    #List the good hashes
    print "\nHashed on the string: Kevin\nResults..."
    for i in range(0, len(results)):
        key, value = results.popitem()
        hashStr, nonce = value
        print "Nonce: " + str(nonce[0]) + ", hash: " + str(hashStr)


texts: How is my program for computing the Hardy-Ramanujan number?

texts:
I'm just wanting feedback on the efficiency, design and layout of this code if possible please. I suspect it's weird having a constructor with nothing in. I'd be grateful if it could be explained how to modify the code to fit in with conventions,  especially in this respect, but also in others.

package cubes;

import java.util.ArrayList;

public class Cubes {

    ArrayList<Integer> sum = new ArrayList<Integer>();
    ArrayList<Integer> x = new ArrayList<Integer>();
    ArrayList<Integer> y = new ArrayList<Integer>();
    boolean found = false;
    int  cSum = 0, a = 0 , b = 0, c = 0, d = 0, k, floor;
    Integer cubeSum, X, Y, answer;
    double K, J, cs;
    int iterations;

    public static void main(String[] args) {

        Cubes c = new Cubes();
        c.find();
    }

    public Cubes()
    {

    }

    private void find()
    {
        int i = 3;

        K = (double)2;
        J = (double)1;
        cs = Math.pow(K,3.0)+Math.pow(J,3.0);
        cubeSum = new Integer((int) cs);

        sum.add(cubeSum);
        x.add(1);
        y.add(2);

        i = 4;

        while(found!=true)
        {
            floor = (int)Math.floor(i/2);

            for(int j = 1; j < floor+1; j++)
            {
                k=i-j;
                K = (double)k;
                J = (double)j;
                cs = Math.pow(K,3.0)+Math.pow(J,3.0);
                cubeSum = new Integer((int) cs);
                X = new Integer((int) j);
                Y = new Integer((int) k);

                for (int l = 0; l < sum.size(); l++)
                {
                    a = (int)x.get(l);
                    b = (int)y.get(l);
                    if(cubeSum.compareTo(sum.get(l))==0)
                    {
                        if (a != j && a != k && b != j && b != k)
                        {
                            c=j;
                            d=k;
                            System.out.println("The first positive integer "
                            + "expressible as the sum\nof 2 different positive"
                            + " cubes in 2 different ways\nis "
                            + cubeSum + " = " +a+"^3 + "+b+"^3 = "
                            + c+"^3 + "+d+"^3");
                            found=true;
                        }
                    }
                }

                sum.add(cubeSum);
                x.add(X);
                y.add(Y);
            }
            i++;
        }
    }
}


texts:
I wrote this code to allow users to select multiple images, and each image can be selected multiple times. It feels convoluted, though, and prone to errors, such as forgetting to do something associated with an action.

How can I make it more object-oriented or reusable?

var images = [];

function removeImage(image) {
    while((index = images.indexOf(image)) !== -1) {
        images.splice(index, 1);
    }
}
function decrementImage(image) {
    var index = images.indexOf(image);
    images.splice(index, 1);
}

function countOccurrences(image) {
    var occurrences = 0;
    for (i = 0; i < images.length; i++) {
        if (images[i] === image) occurrences += 1
    }
    return occurrences;
}

$('#image-container').on('click', 'img', function () {
    var image = $(this),
        source = image.attr('src');
        image.data('selected', true).addClass('selected').siblings('.controls').show();
        images.push(source);
        image.siblings('span.count').html(countOccurrences(source));
});

$('#image-container').on('mouseleave', '.image-wrapper', function () {
    $(this).children('.controls').hide();
});

$('#image-container').on('mouseenter', 'img', function () {
    var image = $(this),
        controls = image.siblings('.controls');
    if (image.data('selected') === true) {
        controls.show();
    }
});

$('#image-container').on('click', '[data-action="remove"]', function () {
    var controls = $(this).parents('div.controls'),
        image = controls.siblings('img')
        source = image.attr('src');
        image.data('selected', false).removeClass('selected');
        controls.hide();
        removeImage(source);
        image.siblings('span.count').html(countOccurrences(source));
});

$('#image-container').on('click', '[data-action="increment"]', function () {
    var image = $(this).parents('.controls').siblings('img'),
        source = image.attr('src');
    images.push(source);
    image.siblings('span.count').html(countOccurrences(source));
});

$('#image-container').on('click', '[data-action="decrement"]', function () {
    var image = $(this).parents('.controls').siblings('img'),
        source = image.attr('src');
    decrementImage(source);
    var count = countOccurrences(source)
    image.siblings('span.count').html(count);
    if (count < 1) {
        image.siblings('.controls').hide();
        image.data('selected', false).removeClass('selected');
    }
});

$(document).click(function () {
    console.log(images);
});

HTML

            Remove
            Increment
            Decrement

        0

            Remove
            Increment
            Decrement

        0

            Remove
            Increment
            Decrement

        0


texts: Filtering a list of customers in Java based on three criteria

texts:
Let's assume that you need to filter customers based on 3 criteria:

name
tags assigned to customer
customer's location

For some reasons you have to do it directly in your program code, without database queries or PL/SQL for that matter.
Which of these two solutions do you find better in any terms? (e.g code readability, performance, cleanliness)

First example

public List<Customer> filterStepbyStep(List<Customer> customers,
                                       String searchString,
                                       List<Tag> selectedTags,
                                       List<LocationId> selectedLocations) {
    List<Customer> filteredCustomers = new ArrayList<Customer>(customers);
    boolean searchStringNotEmpty = searchString != null && !searchString.trim().isEmpty();
    boolean locationsNotEmpty = selectedLocations != null && selectedLocations.size() > 0;
    boolean selectedTagsNotEmpty = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        boolean valid = true;

        //searchString
        if (valid && searchStringNotEmpty) {
            valid = customer.name.contains(searchString);
        }

        //locations
        if (valid && locationsNotEmpty) {
            valid = selectedLocations.stream().anyMatch(locationId -> locationId.equals(customer.locationId));
        }

        //tags
        if (valid && selectedTagsNotEmpty) {
            boolean tagValid = false;
            for (Tag selectedTag : selectedTags) {
                for (Tag customerTag : customer.getTags()) {
                    if (selectedTag == customerTag) {
                        tagValid = true;
                        break;
                    }
                }
                if (tagValid) {
                    break;
                }
            }
            valid = tagValid;
        }

        return !valid;
    });

    return filteredCustomers;
}

Second example

public List<Customer> filterWithLambda(List<Customer> customers,
                                       String searchString,
                                       List<Tag> selectedTags,
                                       List<LocationId> selectedLocations) {
    List<Customer> filteredCustomers = new ArrayList<Customer>(customers);
    boolean searchStringNotEmpty = searchString != null && !searchString.trim().isEmpty();
    boolean locationsNotEmpty = selectedLocations != null && selectedLocations.size() > 0;
    boolean selectedTagsNotEmpty = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        return (searchStringNotEmpty && !customer.name.contains(searchString))
                || (locationsNotEmpty && !selectedLocations.stream().anyMatch(locationId -> locationId.equals(customer.locationId)))
                || (selectedTagsNotEmpty && !selectedTags.stream().anyMatch(selectedTag ->
                      customer.getTags().stream().anyMatch(customerTag ->
                        selectedTag == customerTag)));
    });

    return filteredCustomers;
}

For me second example is more readable, I can immediately see that customer gets filtered out (removed) if any of 3 operands of OR operator is true.
On the other hand repeating if(valid) for each property in first example does not seem too clean to me. I also find it tiresome and tedious to follow valid variable. Having this kind of state with valid variable is IMO error-prone.
The only reason I can see, that one would prefer first example is not being familiar with lambda expressions.

I've created small repl.it to try these approaches out.

If you can think of better way of doing this, than two above examples, then please feel free to post it here.


texts:
I just finish coding this code which use for control robot using compass sensor with PID control to control motors. Trying to make javascript object for necessary job.

Please guide me for a better code.

Watch Video to get how it works

I use johnny-five package for control Arduino and pid-controller for PID control.

var five = require('johnny-five');
var board = new five.Board();
var motorRight;
var motorLeft;
var compass;

var PID = require('pid-controller');
var heading = 0;
var headingSetpoint = 0;
var Kp = 5;
var Ki = 0;
var Kd = 0;
var ctrl = new PID(heading, headingSetpoint, Kp, Ki, Kd, 'reverse');
board.on('ready', function(){
  motorLeft = new five.Motor({
    pins: {
      pwm: 4,
      dir: 50,
      cdir: 51
    }
  });
  motorRight = new five.Motor({
    pins: {
      pwm: 5,
      dir: 52,
      cdir: 53
    }
  });
  motorUtils = {
    Forward : function(pwm) {
      motorRight.forward(pwm);
      motorLeft.forward(pwm);
    },
    Backward : function(pwm) {
      motorRight.reverse(pwm);
      motorLeft.reverse(pwm);
    },
    RotateLeft : function(pwm) {
      motorRight.forward(pwm);
      motorLeft.reverse(pwm);
    },
    RotateRight : function(pwm) {
      motorRight.reverse(pwm);
      motorLeft.forward(pwm);
    },
    TurnLeft : function(pwm) {
      motorRight.forward(pwm);
      motorLeft.brake();
    },
    TurnRight : function(pwm) {
      motorRight.brake();
      motorLeft.forward(pwm);
    },
    Stop : function() {
      motorRight.brake();
      motorLeft.brake();
    }
  }

  var pidUtils = {
    init : function() {
      ctrl.setPoint(0);
      ctrl.setMode(PID.AUTOMATIC);
      ctrl.setSampleTime(1);
    },
    readCompass : function() {
      return heading;
    },
    pidLoop : function() {
      ctrl.setInput(10 - pidUtils.readCompass());
      ctrl.compute();
      pidUtils.setMotor(ctrl.getOutput());
    },
    setMotor : function(output) {
      //console.log('PID', Math.floor(ctrl.getOutput()) , Math.floor(ctrl.getSetPoint()), ctrl.getInput(), ctrl.getDirection(), heading);
      //Q1 && Q2
      if(ctrl.getSetPoint() >= 0 &&
              ctrl.getSetPoint() < 180){
                console.log('Q1');
        if((180+ctrl.getSetPoint()) > pidUtils.readCompass()){
          console.log('right', output);
          motorUtils.RotateRight(output);
        }
        else if ((180+ctrl.getSetPoint()) < pidUtils.readCompass() ||
                  ctrl.getSetPoint() > pidUtils.readCompass()) {
          console.log('left');
          motorUtils.RotateLeft(ctrl.getOutput());
        }
      }
      //Q3
      else if (ctrl.getSetPoint() > 180 &&
               ctrl.getSetPoint() < 270){
                 console.log('Q3');
         if((180+ctrl.getSetPoint()) > pidUtils.readCompass()){
           motorUtils.RotateRight(ctrl.getOutput());
         }
         else if (ctrl.getSetPoint() > pidUtils.readCompass()) {
           motorUtils.RotateLeft(ctrl.getOutput());
         }
      }
      //Q4
      else if (ctrl.getSetPoint() > 270 &&
               ctrl.getSetPoint() <= 360){
                 console.log('Q4');
         if((180+ctrl.getSetPoint()) > pidUtils.readCompass() ||
             (ctrl.getSetPoint() - 180) > pidUtils.readCompass()){
           motorUtils.RotateRight(ctrl.getOutput());
         }
         else if ((ctrl.getSetPoint() - 180) < pidUtils.readCompass()) {
           motorUtils.RotateLeft(ctrl.getOutput());
         }
      }
    }
  }

  compass= new five.Compass({
    controller: "HMC5883L"
  });

  board.repl.inject({
    motorUtils: motorUtils,
    motorLeft: motorLeft,
    motorRight: motorRight,
    ctrl: ctrl
  });

  compass.on('data', function() {
    heading = this.heading;
  });
  compass.once('data', function(){
    pidUtils.init();
    setInterval(pidUtils.pidLoop, 1);
  });

});


texts: Finding matching Node instances in an array - running slow

texts:
I have encountered a performance issue in Swift. I compared the same method between C# and Swift: Swift is much slower than C#.

Here is the code I'm working with. Could some one help me to speed it up in Swift?

CSharp version (for reference only - it takes 73 ticks):

var nodes = new Node[328];
            for (int i = 0; i < nodes.Length; i++)
            {
                nodes[i] = new Node();
            }

            var oneNode = new Node();
            var count = 1;

            Stopwatch sw = Stopwatch.StartNew();
            foreach(var node in nodes)
            {
                if (oneNode.Equals(node))
                {
                    count++;
                }
            }
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

Swift version (it takes 1.78 ms):

import Foundation

public class Node : Equatable {
    var cost : Int = 0
    var x : Int = 100
    var y : Int = 100
}

public func == (a : Node, b : Node) -> Bool {
    return (a.x == b.x) && (a.y == b.y)
}

var t = NSDate()
let a = [Node](count: 328, repeatedValue: Node())
let b = Node()
var count = 1
for i in a {
    if i == b {
        count++
    }
}

var elapsed = t.timeIntervalSinceNow * -1000
println(elapsed)


texts: Counting pairs of integers whose sum is less than a given threshold

texts:
Recently I was going through this codechef problem while practicing for the upcoming zoc.

The problem asks to calculate number of combinations of the given numbers where the sum is less than another given number.

Previously I had a bruteforce algorithm which gave the correct answer but took a lot of time, in some cases even more than a second which raised a TLE error in codechef.

I changed my whole algorithm to get rid of that TLE error and also almost got that but for the last test it still gets stuck.

#include <iostream>
#include <vector>
#include <algorithm>
int main(){
    std::vector<long long> tstCases;
    std::vector<long long> okset;
    std::vector<long long> testset;
    for(int i =0;i<2;i++){
        long long cases;
        std::cin >> cases;
        tstCases.push_back(cases);
    }
    long long n = tstCases.at(0);
    long long k = tstCases.at(1);
    for(long long i =0;i<n;i++){
        long long cases;
        std::cin >> cases;
        if(cases<=k){
            if(cases < k/2){
                okset.push_back(cases);
            }else{
                testset.push_back(cases);
            }
        }
    }
    long long l = okset.size();
    long long p1 = (l*(l-1))/2;
    long long p2 = 0;
    sort(testset.begin(),testset.end());
    for(long long itr1 : okset){
        for(long long itr2 : testset){
            if(itr1+itr2 >= k){
                break;
            }else{
                p2++;
            }
        }
    }
    long long p = p1+p2;
    std::cout << p << std::endl;
    return 0;
}

Note : I am using long long because the problem instructed me to do so and I am lazy enough to do it by myself so I used replace all. Sorry for that.


texts:
I've put together another simple query that allows you to search post/comments with specific keywords. At the moment, only post bodies are checked.

DECLARE @search_keywords NVARCHAR(MAX) = ##SearchKeywords:string##;
DECLARE @search_type_id NVARCHAR(MAX) = ##SearchTypeId:string##;

IF (LOWER(@search_type_id) = 'post')
BEGIN
  SELECT
      Id AS [Post Link]
    , OwnerUserId AS [User Link]
    , Score
    , Tags
  FROM Posts WHERE
    LOWER(Body) LIKE LOWER(
      CONCAT('% ', REPLACE(@search_keywords, ' ', '%%'), ' %')
    )
  ORDER BY Score DESC;
END

ELSE IF (LOWER(@search_type_id) = 'comment')
BEGIN
  SELECT
      Id AS [Comment Link]
    , UserId AS [User Link]
    , Score
    , Text
  FROM Comments WHERE
    LOWER(Text) LIKE LOWER(
      CONCAT('% ', REPLACE(@search_keywords, ' ', '%%'), ' %')
    )
  ORDER BY Score DESC;
END

ELSE
BEGIN
  PRINT 'SearchTypeId must either be "comment" or "post".';
END

Here's some sample input. Single quotes, '', are not needed for the input.

SearchKeywords: :)
SearchTypeId:   comment


texts:
I'm trying to speed up the execution of the following problem:

I have two functions which are used together.

Here are the functions explained:

The first function simulates N coin flips and returns an array of strings with the results:

def throw_a_coin(N):
    return np.random.choice(['H','T'], size=N)

The second function takes in number_of_samples, sample_size
and returns sample_probs.
The function simulates number_of_samples runs of sample_size coin flips and stores the result of num_heads / sample size in sample_probs for each run.

Here is the code:

def make_throws(number_of_samples, sample_size):
    sample_probs = np.zeros(number_of_samples)
    for i in range(number_of_samples):
        num_heads = sum(throw_a_coin(sample_size) == "H")
        sample_probs[i] = float(num_heads) / sample_size
    return sample_probs

Now I want to simulate multiple runs with different sample_sizes and 200 runs for each sample size. So sample_size = 1 I would do 200 runs of 1 coin flip, for sample_size = 10 I would do 200 runs of 10 coin flips and so on.

Here is the code that takes so long:

mean_of_sample_means = np.zeros(len(sample_sizes))
std_dev_of_sample_means = np.zeros(len(sample_sizes))

for i in range(len(sample_sizes)):
    prob = make_throws(200, sample_sizes[i])
    mean_of_sample_means[i] = np.mean(prob)
    std_dev_of_sample_means[i] = np.std(prob)

I am pretty sure that this process can be improved by getting rid of the for loops and using array-operations instead. But I just cannot think of how to apply throw_a_coin or make_throws to an array.


texts: How do I optimize the bubble sort in Assembly8086?

texts:
I tried to implement bubble sort in Assembly 8086.
datasg      SEGMENT BYTE 'data'
array       DB 1, 3, 2, 5, 4
n           DW 5
datasg      ENDS
stacksg     SEGMENT BYTE STACK 'stack'
            DW 12 DUP(?)
stacksg     ENDS
codesg      SEGMENT PARA 'code'
            ASSUME CS:codesg, DS:datasg, SS:stacksg
MAIN        PROC FAR

; Pushing the previous data segment to keep it secure.
            PUSH DS
            XOR AX, AX
            PUSH AX
            MOV AX, datasg
            MOV DS, AX
;SI = i
            XOR SI, SI
            MOV CX, n
            DEC CX
out:        PUSH CX; Pushing CX to the stack before entering the second for loop
            XOR DI, DI
            MOV CX, n
            DEC CX
            SUB CX, SI
in:         MOV AH, array[DI]
            CMP AH, array[DI+1]
            JLE if_end
            XCHG AH, array[DI+1]
            MOV array[DI], AH
if_end:     INC DI
            LOOP in
            POP CX
            INC SI
            LOOP out
            XOR SI, SI
; Some garbage code to move array elements to AL register one by one to see them while debugging.
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            INC SI
            MOV AL, array[SI]
            RETF
MAIN        ENDP
codesg      ENDS
            END MAIN

It seems to be working for the given example in the above code. I also tried it with different arrays and they all seem to work.
I just want to learn if there is a way to improve it? Improvements like changing JMP codes to decrease the size of code or using AX with XCHG because that is faster.
I also can't comprehend the idea of pushing CX to stack for using nested-for loops. If you would give some suggestion about it I would be very happy.


texts: Generating Bitly links in a Google Sheet

texts:
I have this set of functions in my Google Sheet to create a Bitly bitlink whenever data in a row is changed. While this does work, it seems really slow to me. Looking at the Execution transcript, it looks like the lag is happening when the script queries the Sheet:

Spreadsheet.getRange([L6]) [9.535 seconds]
Range.getValue() [10.186 seconds]
Spreadsheet.getRange([O6]) [20.228 seconds]
Spreadsheet.getRange([O6]) [20.222 seconds]

The total script execution takes 40 to 80 seconds. This seems longer than it should take. Is there a better way to do this that is faster? Should I somehow be combining/batching the Sheet queries?

Here is the code:

/*
 * SETTINGS
 */

var bitlyToken = "abcdefghijklmnopqrstuvwxyz";
var logging = true;

/*
 * FUNCTIONS
 */

function _(logMsg) {
  if(logging) {
    Logger.log(logMsg);
  }
}

function getBitlink(longUrl) {
  var bitlyRequest = "https://api-ssl.bitly.com/v3/shorten?format=txt&access_token=" + bitlyToken + "&longUrl=" + longUrl;
  var options = {
    'method': 'get'
  };
  try {
    response = UrlFetchApp.fetch(bitlyRequest,options);
    response = response.getContentText();
    response = response.trim();
    return response;
  } catch(e) {
    return false;
  }
}

function getBitlinkClicks(bitlink) {
  var bitlyRequest = "https://api-ssl.bitly.com/v3/link/clicks?format=txt&unit=day&units=-1&rollup=true&access_token=" + bitlyToken + "&link=" + bitlink;
  var options = {
    'method': 'get'
  };
  try {
    response = UrlFetchApp.fetch(bitlyRequest,options);
    response = response.getContentText();
    response = response.trim();
    return response;
  } catch(e) {
    return false;
  }
}

function onEdit(e){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var editedCell = e.range;
  var rowEdited = editedCell.getRow();
  var longUrl = encodeURIComponent(ss.getRange("L"+rowEdited).getValue());
  var bitlink = '';

  _("longUrl: " + longUrl);
  if(longUrl.length > 0) {
    bitlink = getBitlink(longUrl);
    if(bitlink) {
      _("bitlink: " + bitlink);
      ss.getRange("N"+rowEdited).setValue(bitlink);
      bitlinkClicks = getBitlinkClicks(bitlink);
      if(bitlinkClicks) {
        _("bitlinkClicks: " + bitlinkClicks);
        ss.getRange("O"+rowEdited).setValue(parseInt(bitlinkClicks));
        ss.getRange("O"+rowEdited).setNote( 'Bitlink clicks as of ' + new Date() + '.' );
      }
    }
  }
}


texts:
I have the following method:

Float getPriceEqualsCategoryName(BrowseNode node, Float productPrice) {
    String name = node.getName();
    for (Entry<String, List<RangeValue>> entry : categoryToFee.entrySet()) {
        if (name.equals(entry.getKey())) {
            List<RangeValue> values = entry.getValue();
            for (RangeValue value : values) {
                if (productPrice < value.getMinValue())
                    return value.getMinValue();
                if (value.getRange().contains(productPrice))
                    return value.getReferPercentFee() / 100 * productPrice;
            }
        }
    }
    if (node.getAncestors() == null)
        return 0f;
    return getPriceEqualsCategoryName(node.getAncestors().getBrowseNode().get(0), productPrice);
}

In the above method I have to loop over something similar to tree structure bottom up and check if the name of the node EQUALS to entry name in the map. if yes - I will calculate the price according to it.

As a second choice, I need to loop again to check if the name CONTAINS the entry name in the map.

I wrote a similar method:

Float getPriceContainsCategoryName(BrowseNode node, Float productPrice) {
        String name = node.getName();
        for (Entry<String, List<RangeValue>> entry : categoryToFee.entrySet()) {
            if (name.contains(entry.getKey())) {
                List<RangeValue> values = entry.getValue();
                for (RangeValue value : values) {
                    if (productPrice < value.getMinValue())
                        return value.getMinValue();
                    if (value.getRange().contains(productPrice))
                        return value.getReferPercentFee() / 100 * productPrice;
                }
            }
        }
        if (node.getAncestors() == null)
            return 0f;
        return getPriceContainsCategoryName(node.getAncestors().getBrowseNode().get(0), productPrice);
    }

As you see, the only difference is the name.equals vs name.contains in the 4th line.

I don't like this duplicated code.. is there a better way to write it?


texts:
This is a continuation of this question, at least the first part of that question.
I want to check if everything in the new code is right or if there are other way to make it better.

Exercise

The validBraces method takes a string of braces as a single parameter and determines if the order of the braces is valid.  All input strings will only consist of open curly braces {, closed curly braces }, open parentheses (, closed parentheses ), and open brackets [ and closed brackets ].

A string of braces is considered valid if all open braces are matched with their corresponding closed brace.  For example: (){}[] and ([{}]) would be considered valid, while (}, [(]), and [({})](] would be considered invalid.
An empty string is considered valid.
A non-string input is considered an invalid input.  The method should throw an InvalidArgumentException in this case.

class StringUtil {

  public function validBraces($braces) {
    if ($braces === "") {
      return true;
    } elseif (!is_string($braces)) {
      throw new InvalidArgumentException("Not a string");
    }

    $balance = array();

    for ($i = 0; $i < strlen($braces); $i++) {
      //allowed chars  (){}[]
      if (!($braces[$i] === "(" || $braces[$i] === ")"
           || $braces[$i] === "{" || $braces[$i] === "}"
           || $braces[$i] === "[" || $braces[$i] === "]")) {
        throw new InvalidArgumentException("Invalid string");
      } elseif ($braces[$i] === "(" || $braces[$i] === "{" || $braces[$i] === "[") {
        array_push($balance, $braces[$i]);
      } elseif ($braces[$i] === ")") {
        if (array_pop($balance) !== "(") {
          return false;
        }
      } elseif ($braces[$i] === "}") {
        if (array_pop($balance) !== "{") {
          return false;
        }
      } elseif ($braces[$i] === "]") {
        if (array_pop($balance) !== "[") {
          return false;
        }
      }
    }

    if (count($balance) == 0) {
      return true;
    }

    return false;
  }
}


texts: Display a dropdown based on another dropdown change

texts:
I have a dropdown and when that dropdown changes I want to display/render another dropdown. Can someone help me improve it?

So, a person requests for getting referred in a company for a job. When that person selects a company name in the "Referral Form" I want to show only the cover letters for specific to that company.

My JSON Action:

public JsonResult ListOfCoverLetterByCompanyId(int companyId)
{
    var coverletters = _context.CoverLetters
        .Where(c => c.CompanyId == companyId)
        .ToList();

    var dropdown = new List<SelectListItem>();
    foreach (var cl in coverletters)
    {
        dropdown.Add(new SelectListItem { Text = cl.CoverLetterName, Value = cl.CoverLetterId.ToString() });
    }
    return Json(dropdown, JsonRequestBehavior.AllowGet);
}

My View File:

@model Bridge.ViewModels.ReferralViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Job Request

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.CompanyId, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(m => m.CompanyId, Model.Companies, new { @class = "form-control js-change", onchange = "companyChanged()" })
                @Html.ValidationMessageFor(model => model.CompanyId, "", new { @class = "text-danger" })

        <select id="ajaxdrop" name="ajaxdrop"></select>

                <input type="submit" value="Create" class="btn btn-default" />

}

@section scripts{

}

Model:

public class ReferralViewModel
{
    public int ReferralViewModelId { get; set; }
    [Display(Name = "Resume")]
    public int ResumeId { get; set; }
    public IEnumerable<Resume> Resumes { get; set; }
    public int CoverLetterId { get; set; }
}


texts:
Number letter counts, Problem 17:

  If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

  If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

  NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

Result:

  \$21124\$ (Correct according to Project Euler)

  Time: \$0.0172510147094727\$ seconds

Since this hasn't been solved in Swift, I'd like a code review of this challenge which talks about the efficiency of the code, and how to correct bad practices or violations of any concepts. Here is the code:

import Foundation

let unitNames:[String] = [
    "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
]

let tensNames:[String] = [
    "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred"
]

func convertIntegerToWords(number:Int) -> String {
    var words:String = ""

    if number >= 0 && number <= 19 {

        words = words + unitNames[number]

    } else if number >= 20 && number <= 99  {

        var digits = number.array

        words = words + tensNames[digits[0]]
        words = words + unitNames[digits[1]]

    } else if number >= 100 && number <= 999 {

        var digits = number.array

        if number % 100 == 0 {
            words = words + unitNames[digits[0]] + "hundred";
        } else {
            words = words + unitNames[digits[0]] + "hundredand";
            var newNumber = number - digits[0] * 100;
            words = words + convertIntegerToWords(newNumber)
        }

    } else if number == 1000 {

        words = words + "onethousand"

    }

    return words
}

extension Int {
    var array: [Int] {
        return Array(description).map{String($0).toInt() ?? 0}
    }
}

func EulerSeventeen() -> Int {

    var length:Int = 0

    for iterator in 1...1000 {
        length = length + count(convertIntegerToWords(iterator))
    }
    let end = NSDate();

    return length
}

let start = NSDate();
var result = EulerSeventeen()
let end = NSDate();

let timeInterval: Double = end.timeIntervalSinceDate(start);

println("Result: \(result) found in \(timeInterval) seconds")


texts: activerecord, refactoring the source code

texts:
I have three tables

class User < AR::Base
  has_many :lexemes, :dependent => :destroy
end

class Lexeme < AR::Base
  belongs_to :user
  belongs_to :word
end

class Word < AR::Base
  has_many :lexemes
end

This code is storing the word to Words table and assign it to the user.

word = Word.where(:word=>token).first_or_create
lexeme = @user.lexemes.where(:word_id=>word.id).first_or_create

I don't like my code, so is it possible to improve it? Thanks


texts:
I tried to search and read for 10-12 hours on how to have a secure session, and this is the (simplified version of the) code that I came up with. (found no good book or article with complete guide about PHP Sessions, each had something and missed something else)

Could you kindly please check if I have taken the necessary steps or if I've made a mistake somewhere?

Additional Info: PHP 7.3.x will be used, Webserver is nginx on Ubuntu 18.04, will have a maximum of ~500 visitors per second, usually ~50-100, sessions are written on disk (default of PHP)

function secure_session_start($domain, $ip, $useragent)
{
    // Change PHPSESSID for better security, remove this if set in php.ini
    session_name('app_session');

    // Secure session_set_cookie_params
    session_set_cookie_params(0, '/', $domain, true, true);

    // Don't show any output if session_start fails, die immediately (will add log_error later)
    @session_start() or die();

    // Keep session alive (as suggested by comment on https://www.php.net/manual/en/function.session-start.php#121209)
    $_SESSION['time'] = time();

    // Hash Useragent to be safe from storing malicious useragent text as session data on server
    $useragent_hash = hash('sha256', $useragent);

    // Make sure we have a canary set
    if ( ! isset($_SESSION['canary']))
    {
        // Regenerate & delete old session as well
        session_regenerate_id(true);

        $_SESSION['canary'] = [
            'birth' => time(),
            'ip' => $ip,
            'useragent_hash' => $useragent_hash
        ];
    }

    // Regenerate session ID every 5 minutes:
    if ($_SESSION['canary']['birth'] < time() - 300)
    {
        // Regenerate & delete old session as well
        session_regenerate_id(true);
        $_SESSION['canary']['birth'] = time();
    }

    // If user is logged in, log out user if IP or Useragent is changed (this is intentional, I know users behind load-balancers etc will have issues)
    if (isset($_SESSION['username']) && ($_SESSION['canary']['ip'] !== $ip OR $_SESSION['canary']['useragent_hash'] !== $useragent_hash))
    {
        // Destroy cookie
        setcookie (session_name(), "", time() - 3600, '/', $domain, true, true);

        // Destroy session
        session_unset();
        session_destroy();

        // Redirect (avoid loop by checcking ip_browser_changed)
        if( ! isset($_GET['ip_browser_changed']))
        {
            header('Location: '.URL.'login/?ip_browser_changed');
            exit('IP Address or Browser has been changed, please login again!');
        }
    }
}

Then I will simply do secure_session_start() in my code after validating user IP Address with filter_var($ip, FILTER_VALIDATE_IP)

Edit: I've always relied on PHP Frameworks and their Auth library to handle the sessions etc for me and never worried about them, this time because of too many visitors, I had to skip using frameworks.

I have to make sure users are kept logged in with secure sessions as long as their Browser or IP hasn't changed. Now I'm trying to learn how to securely add the Remember Me feature, just needed to make sure I'm on the right track (with your help)


texts: Create all combinations of length N from a given alphabet (2)

texts:
I implemented this challenge in Java before but performance was not the best so I decided to implement this in C++ to compare the two. The code works and performance is indeed much better than in the Java version. However I am unsure about the quality of this code.
I am still not overly familiar with modern C++ and would like to know if there is anything that I am doing awfully wrong.
Challenge description:

You are given a number N and a string S. Print all of the possible ways to write a string of length N from the characters in string S, comma delimited in alphabetical order.
The first argument will be the path to the input filename containing the test data. Each line in this file is a separate test case. Each line is in the format: N,S i.e. a positive integer, followed by a string (comma separated). E.g.
Print all of the possible ways to write a string of length N from the characters in string S comma delimited in alphabetical order, with no duplicates.
Input sample:
1,aa
2,ab
3,pop

Output sample:
a
aa,ab,ba,bb
ooo,oop,opo,opp,poo,pop,ppo,ppp

Code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <iterator>

void generate_words(const std::vector<char> &alphabet, size_t &word_length, std::vector<std::string> &results)
{
    std::vector<size_t> index(word_length, 0);

    for (;;)
    {
        std::string word(index.size(), ' ');
        for (size_t i = 0; i < index.size(); ++i)
        {
            word[i] = alphabet[index[i]];
        }
        results.emplace_back(word);

        for (int i = index.size() - 1; ; --i)
        {
            if (i < 0)
            {
                return;
            }

            ++index[i];

            if (index[i] == alphabet.size())
            {
                index[i] = 0;
            }
            else
            {
                break;
            }
        }
    }
}

int main(int argc, char **argv)
{
    std::ifstream infile(argv[1], std::ios::in | std::ifstream::binary);

    std::string line;
    while (infile.good() && getline(infile, line))
    {
        size_t word_length = std::stoi(line.substr(0, line.find(',')));
        std::string letters = line.substr(line.find(',') + 1);

        std::vector<char> alphabet;
        for (const auto &it : letters)
        {
            alphabet.push_back(it);
        }
        std::sort(alphabet.begin(), alphabet.end());
        auto last = std::unique(alphabet.begin(), alphabet.end());
        alphabet.erase(last, alphabet.end());

        std::vector<std::string> results;
        generate_words(alphabet, word_length, results);

        std::ostringstream result_line;
        std::copy(results.begin(), results.end() - 1, std::ostream_iterator<std::string>(result_line, ","));
        result_line << results.back();

        std::cout << result_line.str() << "\n";
    }
}


texts: Creating a Dynamic Select Statement from 2 databases on the same server

texts:
Can someone improve on my method for creating union select views from 2 databases located within the same server in C#, here is the code for the method:

public override DataSet GetDynamicReportData(string strSQL) {

        var sbSQL = new StringBuilder(strSQL);
        var finalQueryStr = new StringBuilder(strSQL);

        sbSQL.Replace("SELECT DISTINCT ", "");

        var iamNEAS3 =
            new StringBuilder(" UNION SELECT DISTINCT ");

        var queryColumns = sbSQL.ToString().Split(',');

        for (var i = 0; i <= queryColumns.Length - 1; i++) {

            iamNEAS3.Append(queryColumns[i]);

            if (i < queryColumns.Length - 1) {
                iamNEAS3.Append(", ");
            } else if (i == queryColumns.Length - 1) {

                var appendMagic =
                    queryColumns[i].Replace(
                        "From [dbo].[vw_Classified_ApplicationsFiles]",
                        "FROM [project_phoenix].[dbo].[vw_Classified_ApplicationFiles]")

                iamNEAS3.Append(appendMagic);

                // Systematic removal; thank you!
                iamNEAS3.Replace(queryColumns[i], "");
            }
        }

        finalQueryStr.Append(iamNEAS3);

        return DALDynamicReport.GetData(finalQueryStr.ToString());
    }

Now it receives a string parameter where

strSQL = "Select Distinct [Row1], [Row2], [Row3], [Row4] From [project_mongoose].[dbo].[vw_Classified_ApplicationsFiles] where [Row2] <= 200".

I know my programming skills are limited, but is there a way to not code this by hand like I did?


texts:
I'm working on a feature which user can set frequency of a job. I am using Sidekiq.

My solution is when someone updates the frequency from view, I will delete all old scheduled jobs and create a new job in the action of controller.

I'm looking for a cleaner and more succinct way to do this.

Right now, I have a frequency column on the settings table. There is an update_frequency method in DashboardController to delete all old scheduled jobs and create a new scheduled job.

app/controllers/dashboard_controller.rb

class DashboardController < ApplicationController
  def update_frequency
    setting = Setting.find_by(id: params[:id])
    if setting.blank?
      render json: {status: 404, msg: 'Not found.'}
    else
      if setting.update_attributes(frequency: params[:frequency])
        # find and delete all scheduled jobs
        scheduler = Sidekiq::ScheduledSet.new
        old_jobs = scheduler.select {|work| work.klass == 'HardWorker'}
        old_jobs.each(&:delete) if old_jobs.present?

        # add new schedule job
        HardWorker.perform_in(setting.frequency.minutes)

        render json: {status: 200, msg: 'update frequency successful.'}
      else
        render json: {status: 500, msg: 'update frequency failed.'}
      end
    end
end

A HardWorker to do something and create a new scheduled job:

app/workers/hard_worker.rb

class HardWorker
  include Sidekiq::Worker

  def perform
    # Do something
    setting = Setting.first
    HardWorker.perform_in(setting.frequency.minutes)
  end
end


texts: Converting an array-returning function to a lazy evaluator

texts:
Take a look at the following function:

std::vector<double> get_data(
    std::vector<double> const &data,
    double const t,
    double const x)
{
    std::vector<double> result(data.size(), 0.0);

    double const
        A = func(t, x),
        B = func2(t, x);

    std::transform(std::begin(data) + 1, std::end(data), std::begin(result) + 1,
        [A, B](double const val){
            return A * val + B;
        });

    return result;
}

I am attempting to convert the function above into some sort of structure that computes the values of the result array lazily. First, I will present the code, then describe some rationale.

class data_obj {
    std::vector<double>
        m_data;

    double
        m_A , m_B;

public:
    data_obj(
        std::vector<double> data,
        double const t,
        double const x)
    : m_data(data)
    {
        set_values(t, x);
    }

    void set_values(double const t, double const x)
    {
        m_A = func(t, x);
        m_B = func2(t, x);
    }

    friend class obj_iterator;
};

class obj_iterator {
    data_obj const
        &m_obj;

    std::vector<double>::const_iterator
        m_data_iter, m_data_end;

    double
        m_val;

public:
    obj_iterator(data_obj const &obj)
    : m_obj(obj)
    , m_data_iter(m_obj.m_data.begin())
    , m_data_end(m_obj.m_data.end())
    , m_val(0) { }

    bool has_next() const {
        return m_data_iter != m_data_end;
    }

    void next() {
        ++m_data_begin;

        m_val = *m_data_iter * m_obj.m_A + m_obj.m_B;
    }

    double val() const {
        return m_val;
    }
};

Here are some points to explain the rationale/requirements:

t and x are independent parameters in an optimizer, hence the obj_iterator::set_values() method. On the other hand, data_obj::m_data is constant throughout.
I chose a reference member in obj_iterator::m_data because I want the lifetime of the iterator to be dependent on the lifetime of the object holding the data, as mentioned here.

Finally, here's an example usage of the classes created:

data_obj res_obj(src_data, t, x);

for(obj_iterator res_iter(res_obj); res_iter.has_next(); res_iter.next()) {
    std::cout << res_iter.val() << ", ";
}

Is my rationale flawed? How would you improve this implementation? As someone who programs in python, this could be easily achieved with generator functions.


texts: Count number of bits to convert one integer to another integer

texts:
Return the number of bits (N) that will need to be changed in order to convert an integer(X), into another integer(Y).

  Constraint: 0 <= X <= Y <= 2**128

  Example:

  X = 1, Y = 2 => N = 2

  X = 2, Y = 3 => N = 1

  X = 0, Y = 4 => N = 1

I have written following code, how to improve it?

def bit_diff(n1,n2):
    cmn_d = n1 & n2
    all_d = n1 | n2
    diff = all_d - cmn_d
    cnt = 0
    while diff:
        if diff & 1:
            cnt+=1
        diff>>=1
    return cnt

print bit_diff(1,2)


texts: Simple JavaScript module to manipulate CSS

texts:
After posting some of this code on Stack Overflow I was told to have a look here and get some feedback.

I am having fun building a light JavaScript framework and have copied this pattern. It works fine, but I like to have some review on it.
The reason that I was directed here is likely the use of CSSStyleDeclaration. I wonder if that is good practice, or just a dirty shortcut.

var $ = (function() {
     function doCSS(prop, val) {
       var isSet = Boolean(val),
         action = CSSStyleDeclaration.prototype.setProperty,
         args = arguments;
       if (isSet) {
         this.each(function(node) {
           action.apply(node.style, args);
         });
         return this;
       } else if (typeof(prop) === 'object') {
         this.each(function(node) {
           Object.keys(prop).forEach(function(property) {
             node.style[property] = prop[property];
           });
         });
         return this;
       } else {
         return this.nodes[0].style[prop];
       }
     }

     //

     return function(selector, context) {
       var element = context || window.document;
       return {
         selector: selector,
         nodeList: element.querySelectorAll(selector),
         each: function(action) {
           [].forEach.call(this.nodeList, function(item, i) {
             action(item, i);
           });
           return this;
         },
         toString: function() {
           return selector;
         },
         css: function(prop, val) {
           return doCSS.call(this, prop, val);
         }
       };
     };
   }());

   $.extendingFunction = function() {
     alert("I am an extending function");
   };

   $("#string-css").css("background", "seagreen");
   $("#object-css").css({
     background: "olive",
     color: "yellow"
   });

   document.getElementById("extending")
   .addEventListener("click",$.extendingFunction,false);
h1 {
  padding: 5px;
}

CSS String

CSS Object

<button id="extending">call extended function</button>

Comparing function

As far as the CSSStyleDeclaration goes, I personally am not in favor of it. To be honest, the original was not as dirty as I made by extending it with the option for an object. The following is how I would think it should be.

function doCSS(prop, val) {

    if (typeof (prop) === 'string') {
        this.each(function(node) {
            node.style[prop] = val;
        });
    }

    if (typeof (prop) === 'object') {
        this.each(function(node) {
            Object.keys(prop).forEach(function(property) {
                node.style[property] = prop[property];
            });
        });
    }

    return this;

}


texts: Mirrors number at borders of interval, untill it lays in the interval

texts:
I have the following simple function:

__device__
mirror(int index , int lB, int uB)
{
    while(index < lB || index >= uB)
    {
        if(index < lB) {
            index = lB + (lB-index);
        }

        if(index >= uB) {
            index = uB-1 -(index-uB);
        }
    }
    return index;
}

Assume lb <= uB.

It is used for every index to give it a mirror border behaviour and make sure the result is a valid index.

Are there ways to improve this, with or without changing the result for indices outside [lB-d,uB+d), where d >= uB-lB.

mirror(i,lB,uB) has to be in [lB,uB) of course.

What are concerns for performance?

this function is called very often
it is called from an kernel (cuda things relevant? thread divergence?)

Are there possible improvments for the special case lB == 0?

EDIT: added this small test example

__global__
void driver(unsigned char* img_dest, unsigned char* img_src, int width, int height)
{
    int x = blockIdx.x*blockDim.x+threadIdx.x;
    int y = blockIdx.y*blockDim.y+threadIdx.y;
    if(x >= 0 && x < width && y >= 0 && y < height)
    {
        int x_src = mirror(x*2-width/2,0,width);
        assert(x_src >= 0);
        assert(x_src < width);
        int y_src = mirror(y+x,0,height);
        assert(y_src >= 0);
        assert(y_src < height);
        img_dest[x+y*width] = img_src[x_src + y_src*width];
    }
}

// let the images be gray images, with no pitch.
void callDriver(unsigned char* img_dest, unsigned char* img_src, int width,int height)
{
    dim3 block(16,16);
    dim3 grid((width+block.x-1)/block.x,(height+block.y-1)/block.y);
    driver<<<grid,block>>>(img_dest,img_src,width,height);
    cudaDeviceSynchronize();
}

main()
{
    int width = 512;
    int height = 256;
    unsigned char* img_dest;
    cudaMalloc(&img_dest,width*height);
    unsigned char* img_src;
    cudaMalloc(&img_src,width*height);
    callDriver(img_dest,img_src,width,height);
}

My use case is similar to the driver example:
I have functions deforming where I would have to load pixel that would lay outside of the defined region. To provide meaningful values I want to define them by mirroring at the borders.

My use case are distortion, and linear filters. In both cases I have to use values for pixels that are not defined in the image. While in the case of linear filters, there are other possible solutions (starting extra kernel for border), I decided to work with one kernel for this time.


texts: Simple (Very Easy to Make) RPG Game Simulation in Python and Turtle

texts:
The code creates a very simple/easy RPG game, with 2 classes Jedi and Orc. The data is visualized using turtle. Each class has a method of attack (lightsaber_attack for Jedi), which has an argument that must be either a Jedi or Orc instance. The .health attribute of the attacked one will be reduced by .power of the attacker. If .health is not positive, then the image of the character will disappear. By design, each character can attack itself.

Simulation

luke.lightsaber_attack( orc_1 )
luke.lightsaber_attack( orc_2 )
orc_1.attack( luke )
orc_2.attack( orc_2 )

Questions

How can I make the code to be easily understood by teenagers? (in a tutorial)
How can I make it more compact?
Are there any missing important features of Python's OOP that are important to be explained to students? (other than super and inheritance)

Image Links

jedi.gif
orc.gif
darkorc.gif
damaged.gif

Full code

import turtle
import time

jedi_gif = "/home/asus/Arief_tempo/images/random/jedi.gif"
orc_gif = "orc.gif"
darkorc_gif = "darkorc.gif"
damaged_gif = "damaged.gif"

turtle.register_shape( jedi_gif )
turtle.register_shape( orc_gif )
turtle.register_shape( darkorc_gif )
turtle.register_shape( damaged_gif )

class JediLuke:
    def __init__(self):
        self.power = 300
        self.health = 300

        self.img = turtle.Turtle( shape = jedi_gif )
        self.damaged_img = turtle.Turtle( shape = damaged_gif, visible = False )

        self.img.penup()
        self.damaged_img.penup()

    def lightsaber_attack(self, enemy):
        self.img.setpos(enemy.img.pos()[0], enemy.img.pos()[1])
        enemy.damaged_img.showturtle()
        enemy.health += - self.power
        time.sleep(1)

        enemy.damaged_img.hideturtle()
        if enemy.health < 0:
            enemy.img.hideturtle()

        self.img.setpos(200, 0)

    def change_pos(self, pos):
        self.img.setpos(pos[0], pos[1])
        self.damaged_img.setpos(pos[0], pos[1] + 150)

class Orc:
    def __init__(self, health, gif_image):
        self.power = 100
        self.health = health

        self.img = turtle.Turtle( shape = gif_image )
        self.damaged_img = turtle.Turtle( shape = damaged_gif, visible = False )

        self.img.penup()
        self.damaged_img.penup()

    def attack(self, enemy):
        current_pos = self.img.pos()
        self.img.setpos(enemy.img.pos()[0], enemy.img.pos()[1])
        enemy.damaged_img.showturtle()
        enemy.health += - self.power

        time.sleep(1)

        enemy.damaged_img.hideturtle()
        if enemy.health < 0:
            enemy.img.hideturtle()

        self.img.setpos(current_pos[0], current_pos[1])

    def change_pos(self, pos):
        self.img.setpos(pos[0], pos[1])
        self.damaged_img.setpos(pos[0], pos[1] + 150)

luke = JediLuke()
luke.change_pos( [200, 0] )

orc_1 = Orc( health = 400 , gif_image = orc_gif)
orc_1.change_pos( [-200, 100] )

orc_2 = Orc( health = 200, gif_image = darkorc_gif )
orc_2.change_pos( [-200, -100] )


texts: Sum over selected numpy.ndarray column and write to a file

texts:
I am trying to write the sum of selected NumPy array column and write to a file.
The following code snippet is working fine:

for i in range(int(ldata[2])):
    s_u.append(dos2[i][1])
    s_d.append(dos2[i][2])
    p_u.append(np.sum(dos2[i,[3,5,7]]))
    p_d.append(np.sum(dos2[i,[4,6,8]]))
    d_u.append(np.sum(dos2[i,[9,11,13,15,17]]))
    d_d.append(np.sum(dos2[i,[10,12,14,16,18]]))
with open("dos.dat","w") as ados:
    for i in range(int(ldata[2])):
        ados.write(str(atom[0,i,0]-float(ldata[3]))+" ")
        ados.write(str(s_u[i])+" ")
        ados.write(str(s_d[i])+" ")
        ados.write(str(p_u[i])+" ")
        ados.write(str(p_d[i])+" ")
        ados.write(str(d_u[i])+" ")
        ados.write(str(d_d[i])+" ")
        ados.write("\n")
print(type(dos2))   #<class 'numpy.ndarray'>
print(type(s_u))    #<class 'list'>

But I am feeling like I am overdoing things. Also, I am not checking how many columns (j) there are in dos2[i,[j]] (which may vary).

Can I get some help to make it better?


texts:
I wrote this form object to handle an e-commerce order form. My areas of concern are the verbosity of the populate method, and the repetition of the validations. I omitted some address fields and validations for brevity.

class OrderForm
  include ActiveModel::Model

  def persisted?
    false
  end

  attr_accessor :params

  delegate :email, :bill_to_shipping_address, to: :order
  delegate :name, :street, :city, :state, :post_code, to: :shipping_address, prefix: :shipping
  delegate :name, :street, :city, :state, :post_code, to: :billing_address,  prefix: :billing

  validates :email, length: { maximum: 60 }, email_format: true

  validates :shipping_name, :shipping_street, :shipping_city, presence: true
  validates :shipping_post_code, numericality: { only_integer: true }

  validates :billing_name, :billing_street, :shipping_city, presence: true, unless: -> { bill_to_shipping_address }
  validates :billing_post_code, numericality: { only_integer: true }, unless: -> { bill_to_shipping_address }

  def initialize(item, params = nil, customer = nil)
    @item, @params, @customer = item, params, customer
  end

  def submit
    populate
    if valid?
      order.save!
      true
    else
      false
    end
  end

  def order
    @order ||= @item.build_order do |order|
      order.customer = @customer if @customer
    end
  end

  private

  def shipping_address
    @shipping_address ||= order.build_shipping_address
  end

  def billing_address
    @billing_address ||= order.build_billing_address
  end

  def populate
    order.email = params[:email]
    order.bill_to_shipping_address = params[:bill_to_shipping_address]

    shipping_address.name          = params[:shipping_name]
    shipping_address.street        = params[:shipping_street]
    shipping_address.city          = params[:shipping_city]
    shipping_address.state         = params[:shipping_state]
    shipping_address.post_code     = params[:shipping_post_code]

    if order.bill_to_shipping_address?
      billing_address.name          = params[:shipping_name]
      billing_address.street        = params[:shipping_street]
      billing_address.city          = params[:shipping_city]
      billing_address.state         = params[:shipping_state]
      billing_address.post_code     = params[:shipping_post_code]
    else
      billing_address.name          = params[:billing_name]
      billing_address.street        = params[:billing_street]
      billing_address.city          = params[:billing_city]
      billing_address.state         = params[:billing_state]
      billing_address.post_code     = params[:billing_post_code]
    end
  end
end

The Order object has billing_address and one shipping_address objects. They both inherit from an Address.

Here's the controller:

  def new
    @order_form = OrderForm.new(@item)
  end

  def create
    @order_form = OrderForm.new(@item, params[:order], current_user)
    if @order_form.submit
      # process payment
    else
      render 'new'
    end
  end


texts: Brotli compression algorithm, translated from Python into Haskell

texts:
I have converted some code in Python into its Haskell equivalent.

Python implementation:

def final_codes( bit_lengths, next_code ):
    tree_code = []
    for i in range(len(bit_lengths)):
        tree_code.append( next_code[ bit_lengths[i] ] )
        next_code[bit_lengths[i]] += 1
    return tree_code

#Inputs:
bit_lengths = [ 3, 3, 3, 3, 3, 2, 4, 4 ]
next_code = [0,0,0,2,14]
print final_codes( bit_lengths, next_code )
[2, 3, 4, 5, 6, 0, 14, 15]

Haskell implementation:

replaceNth :: (Eq a, Num a) => a -> a1 -> [a1] -> [a1]
replaceNth n newVal (x:xs)       # Picked this function from somewhere on stackoverflow.
    | n == 0 = newVal:xs
    | otherwise = x:replaceNth (n-1) newVal xs

final_codes' :: (Eq a, Num a, Num a1) => [a1] -> [Int] -> [a1] -> a -> [a1]
final_codes' lst bit_lngths next_cd 0 = lst
final_codes' lst bit_lngths next_cd n = final_codes' new_lst bit_lngths new_next_code (n-1)
    where tlen = bit_lngths !! (length lst)
          new_lst = (next_cd !! tlen) : lst
          new_next_code = replaceNth tlen ((next_cd !! tlen) + 1) next_cd  -- INEFFICIENT!

final_codes :: Num a => [Int] -> [a] -> [a]
final_codes bit_lengths next_code = reverse $ final_codes' [] bit_lengths next_code (length bit_lengths)

In the last where statement in final_codes' I create a new_next_code list by incrementing the value at position tlen by 1. This makes the algorithm \$O(N^2)\$ in comparison to the \$O(N)\$ implementation in Python.

This approach works but it feels a bit contrived. Any suggestions on how I could improve this code and its performance?

Note: I'd like to avoid using the lens library for now (I'm still a novice). I found this Stack Overflow link on replacing a single element in a list; but most approaches are \$O(N)\$. I haven't yet dug into the versions that use lens.


texts:
Hoping someone can help me out with the two aspects of my script that I think is causing the most performance hindrance. Recreating the Array $Result and using the Get-ItemProperty on each and every key to get the required information. Is there a better way to accomplish this task?

Function Get-SoftwareList {
    <#
    #>
    Param()

    New-Variable -Force -ErrorAction SilentlyContinue -Name Result   -Value @()
    New-Variable -Force -ErrorAction SilentlyContinue -Name Function -Value @{}
    $Function.Exclusions = (
        "Security Update for Windows",
        "Security Update for Microsoft",
        "Update for Windows",
        "Update for Microsoft",
        "Hotfix for Windows",
        "Update for Skype",
        "Security Update for Skype"
    )
    If([IntPtr]::Size -eq 8){
        $Function.OSArch='64-bit'
    } Else{
        $Function.OSArch='32-bit'
    }

    $Function.Registry = Get-Childitem -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
    IF ($Function.OSArch -EQ "64-bit") {
        $Function.Registry += Get-ChildItem -Path "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    }

    ForEach ($Key in $Function.Registry) {
        $Key = Get-ItemProperty -Path Registry::$Key
        IF ($Key.DisplayName.length -NE 0) {
            ForEach ($Exclusion in $Function.Exclusions) {
                If ($Key.DisplayName.StartsWith($Exclusion) -EQ $True) {
                    $Skip = $True
                    Break
                } Else {
                    $Skip = $False
                }
            }
            IF ($Skip -EQ $False) {
                $Result += New-Object PSObject -Property @{
                    DisplayName     = $Key.DisplayName
                    Version         = $Key.DisplayVersion
                    UninstallString = $Key.UninstallString
                    Publisher       = $Key.Publisher
                    #ModifyPath      = $Key.ModifyPath
                    InstallDate     = $Key.InstallDate
                }
            }
        }
    }
    Return $Result
}


texts: Optimize the CSV Upload function in Ruby On Rails

texts:
The code is working fine however, I would like to fix code after unless and can I store thread ID in the database too? Is there a way to improve performance?

require 'csv'
    class CsvDb
      class << self
        def convert_save(model_name, csv_data, field_name=nil)
          target_model = model_name.classify.constantize
          csv_file = csv_data.read
          row_headers={}
          counter=0;
          #Thread.new do
                    CSV.parse(csv_file) do |row|
                        if counter==0
                            temp=row
                            row_headers = Hash[temp.map.with_index.to_a]
                            counter +=1
                            next
                        end
                        unless row[row_headers["name"]].nil?
                            temp={}
                            business_type = row[row_headers["business_type_id"]]
                            business_type_id = business_type=='Online' ? 1: business_type=='Local' ? 2: 3
                            temp[:business_type_id]         = business_type_id
                            temp[:user_id]                          = row[row_headers["user_id"]]
                            temp[:name]                                 = row[row_headers["name"]]
                            temp[:country_id]                   = row[row_headers["country_id"]]
                            temp[:homepage]                         = row[row_headers["homepage"]] ||=""
                            temp[:telephone]                        = row[row_headers["telephone"]] ||=""
                            temp[:email]                                = row[row_headers["email"]] ||=""
                            temp[:address]                          = row[row_headers["address"]] ||=""
                            temp[:latitude]                         = row[row_headers["latitude"]]
                            temp[:longitude]                        = row[row_headers["longitude"]]
                            temp[:facebook]                         = row[row_headers["facebook"]] ||=""
                            temp[:twitter]                          = row[row_headers["twitter"]] ||=""
                            temp[:google]                           = row[row_headers["google"]] ||=""
                            temp[:instagram]                        = row[row_headers["instagram"]] ||=""
                            temp[:pinterest]                        = row[row_headers["pinterest"]] ||=""
                            temp[:free_shipping]                = row[row_headers["free_shipping"]]
                            temp[:ship_details]                 = row[row_headers["ship_details"]] ||=""
                            temp[:category_ids]                 = [row[row_headers["category_ids"]]]
                            temp[:style_ids]                        = [row[row_headers["style_ids"]]]
                            temp[:shipping_country_ids] = [row[row_headers["shipping_country_ids"]]]
                            business = target_model.new(temp)
                            business.save
                        end
                    end
                    ActiveRecord::Base.connection.close
          end
        #end
      end
    end


texts:
I've been trying to remember old programming concepts like data structures.

My first challenge was about implementing my own array of positive integers:

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

int* array_initialize(int size) {
    return calloc(size, size * sizeof(int));
}

void array_set(int *array, int index, int value) {
    array += index;
    *array = value;
}

int array_get(int *array, int index) {
    array += index;
    return *array;
}

int array_size(int *array) {
    int size = 0;
    while(*array != 0) {
        size++;
        array++;
    }
    return size;
}

int main() {
    int* array = array_initialize(5);

    array_set(array, 0, 2);
    array_set(array, 1, 4);
    array_set(array, 2, 6);
    array_set(array, 3, 8);
    array_set(array, 4, 10);

    for (int i = 0; i < array_size(array); i++) {
        printf("Index #%d -> %d\n", i, array_get(array, i));
    }
    printf("\nSize: %d\n", array_size(array));

    free(array);

    return 0;
}

Can I call it an array?

Is it a good starting point? What would you change?

Can I implement my custom array with [] to read/write values to my array?


texts: Checking winning conditions in Tic-Tac-Toe

texts:
This code checks winning conditions in Tic-Tac-Toe by checking if there is any row, column or diagonal with the same symbols.

The board is a 2-dimensional array of chars. The character ' ' means that a field is empty.

How can I refactor/simplify this code?

 public static bool SomeoneWins(char[][] board)
        {
            // Check columns
            for (var x = 0; x < board.Length; x++)
            {
                var firstField = board[x][0];
                if (firstField == ' ') continue;
                bool allFieldsTheSame = true;

                for (var y = 1; y < board[x].Length; y++)
                {
                    if (board[x][y] != firstField)
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }

                if (allFieldsTheSame) return true;
            }

            // Check rows
            for (var y = 0; y < board.Length; y++)
            {
                var firstField = board[0][y];
                if (firstField == ' ') continue;
                var allFieldsTheSame = true;

                for (var x = 1; y < board.Length; x++)
                {
                    if (board[x][y] != firstField)
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }

                if (allFieldsTheSame) return true;
            }

            // first diagonal
            if (board[0][0] != ' ')
            {
                var allFieldsTheSame = true;

                for (var d = 0; d < board.Length; d++)
                {
                    if (board[d][d] != board[0][0])
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }
                if (allFieldsTheSame) return true;
            }

            // second diagonal
            if ( board[board.Length - 1][0] != ' ')
            {
                var allFieldsTheSame = true;
                for (var d = 0; d < board.Length; d++)
                {
                    if (board[d][board.Length-d-1] !=  board[board.Length - 1][0])
                    {
                        allFieldsTheSame = false;
                        break;
                    }
                }
                if (allFieldsTheSame) return true;
            }

            return false;
        }


texts: Start Electron after Parcel.js started development server

texts:
I'd like to improve my Parcel.js build but I'm not sure how to do it.

You can find the source code here.

Build process to improve yarn start

At the moment, Electron starts in parallel with the build process and displays a blank page until parcel finished.

But I'd like to wait for first bundle before starting Electron.

What I've tried

Changed npm-run-all to run dev then start:electron sequentially but parcel is blocking the following thread, so Electron was not starting
Spawn start:electron from build script (see scripts/dev.js) but app doesn't start correctly. I'll describe this in more details below. It would be great if it would work with-out that custom script but I'm not sure if that's possible
Also tested the code mentioned here or here with the same result.

Dev script

In the repo the scripts are 'commented' in package.json. Just change commented_dev and commented_start to dev & start to test my current version of the script.

The script is correctly running sequentially but Electron is unable to load from the server (see screenshot below)

I've also tried to run start:electron with npm run and execSync but that wasn't working. It seems like parcel is not correctly starting the dev server - maybe that's related to a configuration that's missing because the server starts correctly with the parcel command from CLI.
(localhost:1234 is also not accessible from a web browser.)

Here is the script:

const Bundler = require("parcel-bundler");
const Path = require("path");
const { spawn, execSync, fork } = require("child_process");

// Entrypoint file location
const file = Path.join(__dirname, "./src/index.html");

console.log("file", file);

const options = {
  //outDir: './dist', // The out directory to put the build files in, defaults to dist
  //outFile: 'index.html', // The name of the outputFile
  publicUrl: "./" // The url to server on, defaults to dist
};

async function runBundle() {
  // Initializes a bundler using the entrypoint location and options provided
  const bundler = new Bundler(file, options);

  bundler.on("bundled", bundle => {
    // bundler contains all assets and bundles, see documentation for details
    // gets called once after first bundle
  });

// bundler.bundle(); // this is in the script but I would comment this

// Run the bundler, this returns the main bundle
// Use the events if you're using watch mode as this promise will only      trigger once and not for every rebuild
 const bundle = bundler.serve().then(server => {
   console.log("server listen");
   spawn("yarn", ["start:electron"], {
     stdio: "inherit",
     shell: true
    });
  });
  await bundle;
}
runBundle();


texts: Prototype for sending commands to an Arduino Uno

texts:
This is a prototype for sending commands to an Arduino Uno. The program will allow the user to receive all the logged data such as GPS data and stuff like that. Since I haven't written the Arduino code to get actual data, the random_log function creates random data.

I have not yet written all the code for returning to home and all that jazz above, but I would first like feedback on what I have so far and how I can better organize or simplify it. (FYI the code works perfectly for me.)

import random
import time

print ('PROTOTYPE COMMAND PROMPT FOR TRANS COM')
print ('')

def random_log():
  for i in range(1, 50):
    right = random.randint(-10, 10)
    left = random.randint(-10, 10)
    r_time = random.randint(1, 15)
    l_time = random.randint(1, 15)
    log = [left, l_time, right, r_time]
    print (log)

def rth_dir():
  print ('RETURNING TO HOME POINT VIA DIRECT PATH')
  return trans_com()

def rth_log():
  print ('RETURNING TO HOME VIA PATH LOGS')
  return trans_com()

def abort():
  print ('EMERGENCY RTH HAS BEEN AUTHORIZED.')
  print ('URGENT: "u"   LOW BATTERY: "low bat"')
  a_type = input('SELECT ABORT TYPE')

  if a_type == 'u':
    print ('RETURNING ASAP')
    return trans_com

  elif a_type == "low bat":
    print ('RETURNING BECAUSE OF LOW BATTERY')
    return trans_com()

  else:
    print ('ERROR! NOT VALID ABORT TYPE')
    return abort()

def trans_com():
  trans_com_in = input('COMMAND COM: ')
  if trans_com_in == 'get log':
    random_log()
    return trans_com()

  elif trans_com_in == 'rth dir':
    rth_dir()
    return trans_com()

  elif trans_com_in == 'rth log':
    rth_log()
    return trans_com()

  elif trans_com_in == 'a':
    abort()
    return trans_com()

  elif trans_com_in == 'coms':
    print ('=================================================================')
    print ('rth_dir ---> Return To Home by direct path')
    print ('rth_log ---> Return To Home by logged data')
    print ('a ---> imediatly returns to home medium speed: EMERGENCY ONLY!')
    print ('get log ---> prints all travel log since home point')
    print ('=================================================================')
    print ('')
    return trans_com()

  else:
    print ('Unknown command, type "coms" for list of all commands')
    print ('')
    return trans_com()
trans_com()

trans_com is the user input for executing the different functions