texts: NewSequentialId - pure net core 2.2 implementation of sql server function

texts:
i'm currently trying to rewrite sql server newSequentialId() function in pure c# that is performing as fast as possible and eats minimum memory.

Question is can I it be done better - current benchamark shows it is at most 2x slower than native function used by SqlServer (p/invoke)?

using System;
using System.Buffers;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;

namespace PerfBenchmarkDotNet
{
    internal static class FastGuid
    {
        private static readonly byte[] macBytes;
        private static long baseDateTicks;

        private static long ClockSequenceNumber = 0;

        static FastGuid()
        {
            macBytes = GetDefaultMacAdress();
            baseDateTicks = new DateTime(1582, 10, 15, 0, 0, 0, DateTimeKind.Utc).Ticks;
        }

        public static Guid NewGuid()
        {
            var guidArray = ArrayPool<byte>.Shared.Rent(16);
            var nowTicks = DateTime.UtcNow.Ticks;
            var sequenceNumber = Interlocked.Increment(ref ClockSequenceNumber) % 65536;

            var ticksDiff = nowTicks - baseDateTicks;
            var ticksDiffBytes = BitConverter.GetBytes(ticksDiff);

            // Copy the bytes into the guid

            // mac
            guidArray[15] = macBytes[5];
            guidArray[14] = macBytes[4];
            guidArray[13] = macBytes[3];
            guidArray[12] = macBytes[2];
            guidArray[11] = macBytes[1];
            guidArray[10] = macBytes[0];

            // sequence number
            guidArray[8] = (byte)(sequenceNumber >> 8);
            guidArray[9] = (byte)(sequenceNumber);

            // time
            guidArray[7] = ticksDiffBytes[0];
            guidArray[6] = ticksDiffBytes[1];
            guidArray[5] = ticksDiffBytes[2];
            guidArray[4] = ticksDiffBytes[3];
            guidArray[3] = ticksDiffBytes[4];
            guidArray[2] = ticksDiffBytes[5];
            guidArray[1] = ticksDiffBytes[6];
            guidArray[0] = ticksDiffBytes[7];

            var guid = new Guid(guidArray);

            ArrayPool<byte>.Shared.Return(guidArray);

            return guid;
        }

        private static byte[] GetDefaultMacAdress()
        {
            var nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();

            if (nic != null)
            {
                return nic.GetPhysicalAddress().GetAddressBytes();
            }

            var fallback = Guid.NewGuid().ToByteArray();
            return fallback.Take(6).ToArray();
        }
    }
}


texts:
I have a simple atomic access class designed to work with Windows threads:

template <class aa_type>
class AtomicAccess{
private:
    CRITICAL_SECTION lock;
    aa_type value;
public:
    AtomicAccess(){
        InitializeCriticalSection(&lock);
    }

    ~AtomicAccess(){
        DeleteCriticalSection(&lock);
    }

    AtomicAccess &operator=(const aa_type &val){
        EnterCriticalSection(&lock);
        value = val;
        LeaveCriticalSection(&lock);
        return *this;
    }

    AtomicAccess &operator++(int){
        EnterCriticalSection(&lock);
        value++;
        LeaveCriticalSection(&lock);
        return *this;
    }

    AtomicAccess &operator--(int){
        EnterCriticalSection(&lock);
        value--;
        LeaveCriticalSection(&lock);
        return *this;
    }

    bool operator==(const aa_type &val){
        aa_type current;
        EnterCriticalSection(&lock);
        current = value;
        LeaveCriticalSection(&lock);
        return current == val;
    }

    bool operator!=(const aa_type &val){
        aa_type current;
        EnterCriticalSection(&lock);
        current = value;
        LeaveCriticalSection(&lock);
        return current != val;
    }
};

typedef AtomicAccess<int> int_aa;

Right now I am using it to only atomic-access integers, and the only operators I need are = (for assignment), ++, --, == and !=. If I decide I need more operators, I will add them.

Testing race conditions is very tricky, so I would like to ask here if my approach will work or if I am missing something.


texts:
I'm happy to hear thoughts and ideas on structure/performance/testing/whatever and multi-threading, which I haven't gotten into yet with Python.

Full code here. Assignment file and a test file included in the folder.

Excerpt:

import unittest
import sys

def Merge_and_CountSplitInv(A,start_index,len_1st,len_2nd):
    """
    Merges two similar length pre-sorted sub-slices of array A while counting
    inversions.
    Input:
    array A, start_index (location of first sub-slice)
    len_1st,len_2nd (subslice_lengths).
    Output: inversions (values where i<j, but A[i]>A[j])
    Side Effect: two consecutive A subsections are sorted.
    """
    inversions=0
    temp_array=[]
    index_1st=start_index
    index_2nd=start_index+len_1st
    #while both indices are in range
    while ((index_1st < start_index+len_1st) and
          (index_2nd < start_index+len_1st+len_2nd)):
        #place smaller value in temp_array, increase inversions
        if A[index_1st]<=A[index_2nd]:
            temp_array.append(A[index_1st])
            index_1st += 1
        else:
            temp_array.append(A[index_2nd])
            index_2nd += 1
            inversions+=(start_index+len_1st-index_1st)
    #one index is out of range:
    if index_2nd == start_index+len_1st+len_2nd: # 2nd index complete
        #add leftover 1st half values to temp_array
        #before destroying them by the write process.
        temp_array.extend(A[index_1st:start_index+len_1st])
    else: # 1st index complete
        pass #no need to write over leftovers in 2nd sub-array
    #write temp_array over A[start_index:start_index+len(temp_array)]
    write_index=start_index
    for value in temp_array:
        A[write_index]=value
        write_index +=1
    return inversions

def Sort_and_Count(A, n, start_index=0):
    """
    Input: array A, length n, start_index(default=0)
    Output: inversions (values where i<j, but A[i]>A[j])
    Side Effect: A is sorted.
    """
    if n==1:
        return 0    # base case, array of length 1
    else:
        # Input: 1st and 2nd halves of current sub-array
        len_1st=n//2
        len_2nd=n//2+n%2
        x=Sort_and_Count(A, len_1st, start_index)
        y=Sort_and_Count(A, len_2nd, start_index+len_1st)
        # merge the (newly sorted) half-sized sub-arrays
        z=Merge_and_CountSplitInv(A,start_index,len_1st,len_2nd)
    return x+y+z

class TestSort_and_Count(unittest.TestCase):
    """
    Basic test class
    """

    def test_Sort_and_Count(self):
        A=[1]
        res1 = Sort_and_Count(A,len(A))  # single element
        self.assertEqual(res1, 0)
        B=[1,3,5,2,4,6]
        res2 = Sort_and_Count(B,len(B))  # even length
        self.assertEqual(res2, 3)
        C=[1,3,5,2,4,6,3]
        res3 = Sort_and_Count(C,len(C))  # odd length, duplicate value
        self.assertEqual(res3, 6)

def main(file_name):
    #TODO: take values from file and run sort_and_count
    with open(file_name) as fh:
        if file_name[:4] == 'test':
            print(fh.readline())  # get rid of first answer line from debug file
        A = list(map(int, [line.strip() for line in fh]))
        print(Sort_and_Count(A,len(A)))

if __name__ == '__main__':

    #TODO: working with argv to accept file input
    if len(sys.argv) > 2:
        sys.exit("Usage: inv_count <file_name> (leave empty for testing)")
    if len(sys.argv) == 1:
        print("No filename input, testing...")
        unittest.main()
    # else: argv == 2
    main(sys.argv[1])


texts:
I have a code snippet which performs an SQL-style join on objects in two arrays based on a specific field (in the code below, .id).

let preprocessed_array = [
  {id: 1,category:'a'},
  {id: 2,category:'b'},
  {id: 3,category:'b'}
]

let new_array = [
  {id: 4},
  {id: 1,category:'b'},
  {id: 5}
]

 for(let i=0;i< preprocessed_array.length;i++)
 {
   for(let j=0;j<new_array.length;j++)
   {
     if( preprocessed_array[i].id===new_array[j].id)
     {
       new_array[j]=preprocessed_array[i]
     }
   }
 }

 console.log(new_array)

Although this snippet is straightforward, I don't like the imperative style.  Is there a more declarative way to do this just with javascript / ECMA6 arrays?


texts: Culling strings from a list that are substrings of other list elements

texts:
I'm bothered by my answer to this SO question.
I'm pretty sure it's more efficient than the sort-and-cull implementations, but I'm having trouble expressing that in a way that I trust.
Also, it's rather convoluted by python standards.
Is there a way to express the same process more clearly, without pages of comments?
The problem statement:

Given a subject list of strings, make a list containing every element of the subject that isn't a substring of a different element of the subject.

Original Current solution:
from itertools import groupby
from operator import itemgetter
from typing import Dict, Generator, Iterable, List, Union

# Exploded is a recursive data type representing a culled list of strings as a tree of character-by-character common prefixes. The leaves are the non-common suffixes.
Exploded = None
Exploded = Dict[str, Union[Exploded, str]]

def explode(subject:typing.Iterable[str])->Exploded:
    heads_to_tails = dict()
    for s in subject:
        if s:
            head = s[0]
            tail = s[1:]
            if head in heads_to_tails:
                heads_to_tails[head].append(tail)
            else:
                heads_to_tails[head] = [tail]
    return {
        h: prune_or_follow(t)
        for (h, t) in heads_to_tails.items()
    }

def prune_or_follow(tails: List[str]) -> Union[Exploded, str]:
    if 1 < len(tails):
        return explode(tails)
    else: #we just assume it's not empty.
        return tails[0]

def implode(e: Exploded) -> Generator[str, None, None]:
    for (head, continued) in e.items():
        if isinstance(continued, str):
            yield head + continued
        else:
            for tail in implode(continued):
                yield head + tail

def cull(subject: List[str]) -> List[str]:
    return list(implode(explode(subject)))

print(cull(['a','ab','ac','add']))
print(cull([ 'a boy ran' , 'green apples are worse' , 'a boy ran towards the mill' ,  ' this is another sentence ' , 'a boy ran towards the mill and fell']))
print(cull(['a', 'ab', 'ac', 'b', 'add']))

I know that it works for the two three test cases.


texts: Build object from database without a discriminator column?

texts:
I currently have a basic application that has a database backing it. I originally connected to the database with Entity Framework, but my tutor has requested from me to recreate the functionality with ADO.NET SQL. This has gone well so far using the SqlDataReader, however I have come across a problem.

My database stores a list of animals, the animals are Dog, Cat and Mouse, they all inherit from the Animal class. With entity framework when I wanted to get an animal from the database, it used the discriminator column automatically and I didn't have to worry about any logic to detect what type of animal the animal was. However so far the only way I can think of doing this with SQL is to manually check the discriminator column.

This works well for the moment but if I start adding say a hundred animals, it will become an impossible task to keep it working efficiently. My question is, is there another way to do this which is more elegant and will scale appropriately? The code for how I currently do the task is below:

if (reader.HasRows)
            {
                while (reader.Read())
                {
                    if (reader.GetString(3) == "Dog")
                    {
                        list.Add(
                            new Dog()
                            {
                                AnimalID = (int)reader.GetInt32(reader.GetOrdinal("AnimalID")),
                                Name = (string)reader.GetString(reader.GetOrdinal("Name")),
                                Age = (int)reader.GetInt32(reader.GetOrdinal("Age")),
                            });
                    }

                    if (reader.GetString(3) == "Cat")
                    {
                        list.Add(
                            new Cat()
                            {
                                AnimalID = (int)reader.GetInt32(reader.GetOrdinal("AnimalID")),
                                Name = (string)reader.GetString(reader.GetOrdinal("Name")),
                                Age = (int)reader.GetInt32(reader.GetOrdinal("Age")),
                            });
                    }

                    if (reader.GetString(3) == "Mouse")
                    {
                        list.Add(
                            new Mouse()
                            {
                                AnimalID = (int)reader.GetInt32(reader.GetOrdinal("AnimalID")),
                                Name = (string)reader.GetString(reader.GetOrdinal("Name")),
                                Age = (int)reader.GetInt32(reader.GetOrdinal("Age")),
                            });
                    }
                }
            }
            else
            {
                //no rows
            }


texts: Show one form that corresponds to the selected radio button

texts:
This piece of code I have written works, but I don't think its the best solution.

What I am doing is check if a certain radio is checked if it is show this div if else show this div if this radio is checked etc.

Can someone point me in the right direction on this one? I would love to know how to write less do more.

$(document).ready(function () {
    $('.Form').hide();
    $('input').click(function () {
        <!--check if its One-->
        if ($('input[value=informed]:checked').length) {
            $('#ContactFormOne').show();
            $("#ContactFormTwo, #ContactFormThree, #ContactFormFour, #ContactFormFive, #ContactSix'").hide();
            <!--check if its Two-->
        } else if ($('input[value=release]:checked').length) {
            $('#ContactFormTwo').show();
            $("#ContactFormOne, #ContactFormThree, #ContactFormFour, #ContactFormFive, #ContactSix'").hide();
            <!--check if its Three-->
        } else if ($('input[value=intake]:checked').length) {
            $('#ContactFormThree').show();
            $("#ContactFormTwo, #ContactFormOne, #ContactFormFour, #ContactFormFive, #ContactSix'").hide();
            <!--check if its Four-->
        } else if ($('input[value=checklist]:checked').length) {
            $('#ContactFormFour').show();
            $("#ContactFormTwo, #ContactFormOne, #ContactFormThree, #ContactFormFive, #ContactSix'").hide();
            <!--check if its Fiver-->
        } else if ($('input[value=health]:checked').length) {
            $('#ContactFormFive').show();
            $("#ContactFormTwo, #ContactFormOne, #ContactFormThree, #ContactFormFour, #ContactSix'").hide();
        }
    })
});


texts:
I'm using Searchkick in a situation where a user might write the location they are searching for, or the thing they are searching for, or both.

I've been working on the below code for most of the day. As you can tell, I'm quite the beginner.

Ideally, what I want is something like this:

@portfolios = Portfolio.where(:published => true)
@portfolios = @portfolios.search
    params[:search] unless params[:search].nil?,
    where: {location: {near: coords, within: "300mi"}} unless params[:where].nil?

Is there any way to do that?

I'm asking because, currently this search uses two options. It's about to become quite a bit more complicated. The next step for instance, is to let the user select the range to search in.

Here's my code:

class SearchController < ApplicationController
  def index
        # Search functionality
        if params[:search].nil? or params[:search].empty? && params[:where].empty?
            @portfolios = Portfolio.where(:published => true).includes([:user, :portrait]).order('created_at DESC')
            return
        end

        if params[:where].empty?
            # User entered a query but not a location
            @portfolios = Portfolio.search params[:search], include: [:user, :portrait]

        elsif params[:search].empty?
            # User entered a location but not a query
            coords = Geocoder.coordinates(params[:where])
            @portfolios = Portfolio.search where: {location: {near: coords, within: "300mi"}}, include: [:user, :portrait]

        else
            # User entered a location and a query
            coords = Geocoder.coordinates(params[:where])
            @portfolios = Portfolio.search params[:search], where: {location: {near: coords, within: "300mi"}}, include: [:user, :portrait]
        end
  end
end


texts: Convert tri-gram of type wchar_t to an integer type

texts:
I am trying to convert a tri-gram containing 3 characters of type wchar_t to an integer type (an uint64_t at the present time).

It's been quiet a while I've been working with shifting and squeezing bytes. Here's what I've come up with so far and it - at least the few test cases in the tri-gram list - seems to work so far. But actually I am not very confident with this code, also I have the feeling I may have complicated things more than needed. Code verbosity came out of experimenting.

In this version I am just taking 3-byte chars into account and there's not much of error checking yet. I should mention that portability is not much of a point, as this code will only run on Unix/Linux boxes. Endianess should be properly implemented then.

Please some suggestions or maybe more simple / reliable solution the one or other line.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <locale.h>
#include <stdint.h>
#include <inttypes.h>
#include <math.h>

/**
 * Reconstruct trigram from uint64_t value
 */
void to_wchar(const uint64_t v, wchar_t *s)
{
    uint32_t v32_4 = (uint16_t) ((v) >> 16);
    uint32_t v32_3 = (uint16_t) ((v) >> 32);
    uint32_t v32_2 = (uint16_t) ((v) >> 48);
    uint32_t v32_1 = (uint16_t) ((v)  & 0x001FFFFF); //0x0000FFFFuL);

    s[3] = v32_1; //'\0';
    s[2] = v32_4;
    s[1] = v32_3;
    s[0] = v32_2;
}

/**
 * Convert byte array to uint64, storing 3 uint32_t values
 */
uint64_t to_uint64(const uint8_t *v)
{
    uint64_t ui64 =
    /* wchar */
    ((int64_t) v[2]  << 56) |
    ((int64_t) v[3]  << 48) |
    /* wchar */
    ((int64_t) v[6]  << 40) |
    ((int64_t) v[7]  << 32) |
    /* wchar */
    ((int64_t) v[10] << 24) |
    ((int64_t) v[11] << 16) |
    /* unused */
    ((int64_t) 0 << 8)      |
    (int64_t) 0;

    fprintf(stderr, "0x%" PRIx64 " (%ld)\n", ui64, ui64);

    return ui64;
}

int trigram_to_ui64(const wchar_t *v, uint64_t *ui64)
{
    uint8_t *z = NULL;
    int i;

    if ((WCHAR_MIN > 0) || (WCHAR_MAX < 0x10FFFF)) {
        fprintf(stderr, "Unprocessable rare UTF8 character. Found WCHAR_MIN=%d and WCHAR_MAX=%d", WCHAR_MIN, WCHAR_MAX);
        return 0;
    }

    z = malloc(3 * sizeof(wchar_t));
    memset(z, 0, sizeof(*z));

    uint32_t *ptr = (uint32_t *)z;
    for (i = 0; i < wcslen(v); i++) {
        wchar_t wc = v[i];

        /* Replace 4-byte and more chars, 0x007f = DEL */
        if (wc >= 0x10000)
            wc = (count_bytes(wc) > 3 ? 0x007f : wc);

        /* Pack */
        uint8_t* data = (uint8_t*)ptr;
        data[0] = (uint8_t)((wc >> 24) & 0xff);
        data[1] = (uint8_t)((wc >> 16) & 0xff);
        data[2] = (uint8_t)((wc >> 8) & 0xff);
        data[3] = (uint8_t)(wc & 0xff);

        ptr++;
    }

    *ui64 = to_uint64(z);

    free(z);

    return 1;
}

int ui64_to_trigram(const uint64_t ui64, wchar_t *trigram)
{
    to_wchar(ui64, trigram);

    return 1;
}

int main(int argc, char **argv)
{
    static const wchar_t *trigrams[] =
    {
        L"öx再",
        L"©¥c",
        L"再学习",
        L"AiB",
        L"a—c",
        L"екс",
        L"öbä"
        L"",
        L"A B",
        L" 学习",
        L"AB ",
        L"xy",
        NULL
    };

    int i;
    const wchar_t **str;
    uint64_t ui64;
    wchar_t aux[3] = {0};

    setlocale(LC_CTYPE, "");
    setlocale(LC_COLLATE, "");

    /* Basic testing ... */
    for (str = trigrams; *str; str++) {
            printf("==> '%ls'\n", *str);

            /* Convert to uint64_t */
            trigram_to_ui64(*str, &ui64);

            /* Convert back to wchar_t string */
            ui64_to_trigram(ui64, aux);

            printf("<== '%ls': ", aux);
            if (wcscmp(*str, aux) == 0)
                    printf("OK\n");
            else
                    printf("NOT OK\n");
    }

    return 0;
}


texts: Opencv forEach with lambda expression for parallel processing

texts:
I'm using forEach function to access pixels in parallel like so:

// build look up table
cv::Mat dst=cv::imread(argv[1]); //png image 1288*728

unsigned char lut[256];
for (int i = 0; i < 256; i++)
    lut[i] = cv::saturate_cast<uchar>(pow((float)(i / 255.0), fGamma) * 255.0f); //pow: power exponent

dst.forEach<cv::Vec3b>
(
    [&lut](cv::Vec3b &pixel, const int* po) -> void
    {
        pixel[0] = lut[(pixel[0])];
        pixel[1] = lut[(pixel[1])];
        pixel[2] = lut[(pixel[2])];
    }
);

My question is how can I make sure that it is accessing pixels in parallel?

I'm processing RGB images so I would like to make sure it is working in parallel.

And also in lambda expression without forEach function:

std::vector<std::vector<int> > histSum(3, std::vector<int>(256,0));
dst.forEach<cv::Vec3b>
(
  [&histSum](cv::Vec3b &pixel, const int* po) -> void
  {
    ++histSum[0][pixel[0]];
    ++histSum[1][pixel[1]];
    ++histSum[2][pixel[2]];
  }
);

std::vector<int> A(3, 255);
auto A_estim_lambda([&A, rows, cols, &histSum]{

    for (auto index = rows*cols/500; index>histSum[0][A[0]]; --A[0])
         index -= histSum[0][A[0]];
    for (auto index = rows*cols/500; index>histSum[1][A[1]]; --A[1])
         index -= histSum[1][A[1]];
    for (auto index = rows*cols/500; index>histSum[2][A[2]]; --A[2])
         index -= histSum[2][A[2]];

return A;
});

auto AA=A_estim_lambda();

I'm not sure if this is processing in parallel and also I think I can write the last three loops in one loop but I don't know how or if it is possible.

Do you have any other remarks about my code?

Compilation:

g++ -std=c++1z -Wall -Ofast -march=native test3.cpp -o test3 `pkg-config --cflags --libs opencv`


texts: Reading new data from a constantly updating file in Java

texts:
I have a log file which is constantly updated with new lines of data. I need to get new added data in java as soon as it's written. For now my solution is:

public static void readNonStop(String filename, boolean goToEnd, FileReadCallback readCallback) {
    if(readCallback == null) {
        return;
    }
    try {
        BufferedReader br = new BufferedReader(new FileReader(filename));
        try {
            String line = br.readLine();
            int lineNumber = 0;

            if(goToEnd) {
                while(br.readLine() != null) {}
            }

            while (true) {
                if(line != null) {
                    readCallback.onRead(lineNumber++, line);
                } else {
                    Thread.sleep(1);
                }
                line = br.readLine();
            }
        } finally {
            br.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But I have a feeling that there should be a better way. I don't like the idea of a constant running loop with a "sleep" inside and would prefer some sort of an event driven approach.

If I rely on FileSystem events to reopen the file each time it is modified, it introduces a delay.

What is the correct way of doing it for this situation?


texts: play_card() method in an Exploding Kittens card game

texts:
I wrote a library for card games.  To demonstrate how it can be used, I also wrote an Exploding Kittens card game as an example.

I'm using CodeClimate to determine cyclomatic complexity. This method in the Exploding Kittens game has complexity too high (6):

def play_card(self, card: KittenCard, player: Player = None, target: Player = None):
    if card.selfcast and player is None:
        raise Exception("You must pass a player who owns the card!")
    if card.targetable and target is None:
        raise Exception("You must pass a target!")
    if not self.ask_for_nope():
        card.effect(player, target)
    else:
        print("Card was noped :(")

My question is, how would you reduce it? It seems really readable and maintainable now, but I want to get rid of the Codeclimate issue. Should I be splitting it up to two functions or does it defeat its purpose and makes the code less maintainable?


texts: await user input with async/await syntax

texts:
for clarity: moved here from stackoverflow after being pointed to Code Review being the better place for this question
I love async/await and Promises since I got my hands on them. And I might be overdoing it, but it feels like there should be a good and readable way to utilize async/await to get a little closer to a flow like, functionalISH programming style.
I would love to not have to only use async/await to wait for web resources to come back but also to wait for user input when I await it.
So far i have some code working similar to this shortened demo where I wrap a one time only EventListener into a Promise:

//// MAIN ///////

(async function(){

    //...do some async await stuff here... fetching stuff from a server
    // let services = await fetch(...) for example
    let services = [{url:"x",label:"1"},{url:"y",label:"2"},{url:"z",label:"3"}]

    let service_chosen = await showServicesToUserAndAwaitInput(services);
    console.log("service_chosen:",service_chosen);
    // ... go on....
})()

//// END MAIN /////

async function showServicesToUserAndAwaitInput(services){

    if (services.length < 1){return null}

    let choice = null;

    let serviceList = document.querySelector("#serviceList");

    // show list element
    serviceList.classList.remove("hidden")

    // create some elements for the user to interact with
    for (let service of services){
        let button = document.createElement("BUTTON");
        button.innerHTML = service.label;
        button.addEventListener("click",function(){
          document.dispatchEvent(
            new CustomEvent('serviceChosen', { detail:service })
          )
        });
        serviceList.appendChild(button);
    }

    // returns promise with one time only event listener
    return new Promise((resolve,reject)=>{
        document.addEventListener("serviceChosen",function(e){
            serviceList.classList.add("hidden") // hide again for we are done
            resolve(e.detail)
        },{ once: true })
    })
}
.hidden{
  visibility: hidden
}
<div id="serviceList" class="hidden">

</div>

But something about this use of the EventListener bugs me. Also: I use a promise that always resolves, which also seems strange.
On the upside: I get to read the code top to bottom and can follow the user flow within the MAIN without having to chase down events, callbacks and so on.
Yet, it feels like I am reinventing something somebody else might have already normed. So:
Is there a better way to achieve this? Are there best practices to work with user interactions or other DOM events in a async and/or thenable way?


texts: Implementation of generic unordered list in java

texts:
This question is a follow-up question of this question. These features are added to the new class -

Generic class
User is capable of setting the size
List interface has been added
Iterator class has been added

As of now I still have some questions after developing this class.

Does this list interface have enough methods/behavior?
Why do I have to type cast from next() while returning data?
When I am testing this class I have to do this Iterator<Integer> itr = ((UnorderedList) ul).iterator(); why?

Thanks to him to open my eyes to design a class to iterate over a structure. My prof of Data Structure even did not specify or taught students important things like this.

If this class is still lacking anything then as always suggestions and advice are appreciated.

//List interface

package lists.arrayLists;

public interface List<T>
{
    boolean isFull();
    boolean isEmpty();
    boolean add(T data);
    void remove(T data);
    boolean find(T data);
    int size();
}

// Unordered List class

package lists.arrayLists.unorderedList;

import lists.arrayLists.List;
import java.lang.IndexOutOfBoundsException;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class UnorderedList<T> implements List<T>, Iterable<T>
{
    private static int MAX_SIZE = 100;
    private int size;
    private Node<T>[] nodeElements;

    public UnorderedList()
    {
        nodeElements = new Node[MAX_SIZE];
    }

    public UnorderedList(int capacity)
    {
        MAX_SIZE = capacity;
        nodeElements = new Node[MAX_SIZE];
    }

    @Override
    public boolean isFull()
    {
        return (size() == MAX_SIZE);
    }

    @Override
    public boolean isEmpty()
    {
        return (size() == 0);
    }

    @Override
    public int size()
    {
        return size;
    }

    @Override
    public boolean add(T data)
    {
        try
        {
            Node<T> node = new Node<>(data);
            nodeElements[size++] = node;
            return true;
        }
        catch (IndexOutOfBoundsException ex)
        {
            System.out.println(ex.getMessage());
            throw new IndexOutOfBoundsException();
        }
    }

    @Override
    public void remove(T data)
    {
        int index = locate(data);
        try
        {
            nodeElements[index] = nodeElements[size() - 1];
            size--;
        }
        catch (IndexOutOfBoundsException ex)
        {
            throw new NoSuchElementException();
        }
    }

    @Override
    public boolean find(T data)
    {
        return (locate(data) >= 0);
    }

    private int locate(T data)
    {
        for (int index = 0; index < size(); index++)
        {
            if (data == nodeElements[index].getData())
            {
                return index;
            }
        }
        return - 1;
    }

    @Override
    public Iterator<T> iterator()
    {
        return new ULIterator<T>();
    }

    private class ULIterator<T> implements Iterator<T>
    {
        private int currentIndex = 0;

        @Override
        public boolean hasNext()
        {
            return (currentIndex < size());
        }

        @Override
        public T next()
        {
            if(hasNext())
            {
                return (T)nodeElements[currentIndex++].getData();
            }
            else
            {
                throw new NoSuchElementException();
            }
        }
    }
}

// Node class

package lists.arrayLists.unorderedList;

public class Node<T>
{
    private T data;

    public Node(T data)
    {
        this.data = data;
    }

    public T getData()
    {
        return data;
    }
}


texts:
I'm learning C and I've got to a point learning about different sorting algorithms.  Before seeing how it was done, I wanted to try doing it myself based on what I read on how it's working.

int temp;
    for(int i = 0; i < SIZE - 1; i++)
    {
        for(int j = 0; j < SIZE - 1 - i; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }

This is what the code from where I learn looks like:

for(int i = 0; i < SIZE; i++)
{
       if((i < SIZE - 1) && (arr[i] > arr[i+1]))
       {
                  int tmp = arr[i];
                  arr[i] = arr[i + 1];
                  arr[i + 1] = tmp;
                  i = -1;
       }
}

Now, obviously they're different, but is one more efficient in someway than the other?  Did I do something that is less efficient than their code?


texts: Java method refactoring: getting the file name or path

texts:
I have been learning about refactoring and I have this method that I'm wondering if I should split into two for code cleanness. First, the method as one, next the method split in two:

Method not split:

public static ArrayList<String> getFilePathOrName(String pathOrName) {
    ArrayList<String> files = new ArrayList<>();
    File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld");
    File[] listOfFiles = folder.listFiles();

    if(pathOrName.equalsIgnoreCase("path")) {
        for (File file : listOfFiles) {
            if (file.isFile()) {
                files.add(file.toString());
            }
        }
    } else if(pathOrName.equalsIgnoreCase("name")) {
        for (File file : listOfFiles) {
            if (file.isFile()) {
                files.add(file.getName());
            }
        }
    }
    return files;
}

Method split:

public static ArrayList<String> getAllUndistributedFilesNames() {
    ArrayList<String> files = new ArrayList<>();
    File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld");
    File[] listOfFiles = folder.listFiles();

    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(file.getName());
        }
    }
    return files;
}

public static ArrayList<String> getAllUndistributedFilesPaths() {
    ArrayList<String> files = new ArrayList<>();
    File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld");
    File[] listOfFiles = folder.listFiles();

    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(file.toString());
        }
    }
    return files;
}

I feel like the method names when they are split is more intuitive. However, I'm not sure if that is enough justification to have this much duplicate code.


texts:
The below is a class designed to implement Rememember the Milk's task priorities. I'm using it partly as an exercise in "Pythonic" programming, so it's fairly simple already, but advice on how to make it simpler or more Pythonic would be particularly appreciated.

I'm using Python 2.6.5 in case it makes any difference.

class Pri(int):    # Subclass int to get handy comparison functions etc.
    '''Task priority'''

    public_from_internal = {1: 1, 2: 2, 3: 3, 4: 'N'}
    internal_from_public_str = {'N': 4, '1': 1, '2': 2, '3': 3}
    _dict = dict()

    def __new__(cls, level):
        try:
            level = Pri.internal_from_public_str[str(level)]
        except KeyError:
            raise ValueError, "Pri must be 'N', '1', '2', or '3'"

        # If there's already an instance of this priority, don't create a new one.
        if level in Pri._dict: return Pri._dict[level]
        else: return super(Pri, cls).__new__(cls, level)

    def __init__(self, level):
        super(Pri, self).__init__()
        Pri._dict[self] = self

    def __repr__(self): return "Pri('" + str(Pri.public_from_internal[self]) + "')"

    # Priority 1 is clearly greater than priority 3, so invert cmp
    def __cmp__(self, other): return (-cmp(int(self), int(other)))

Some selected output, for the curious:

>>> Pri(1)
Pri('1')
>>> Pri('N')
Pri('N')
>>> Pri(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "rtm.py", line 10, in __new__
    raise ValueError, "Pri must be 'N', '1', '2', or '3'"
ValueError: Pri must be 'N', '1', '2', or '3'
>>> Pri._dict
{Pri('1'): Pri('1'), Pri('N'): Pri('N')}
>>> Pri(1) > Pri(2)
True
>>> bool(Pri('N'))
True
>>> repr(Pri("2"))
"Pri('2')"
>>> print repr(Pri('N'))
Pri('N')
>>> Pri(1)._dict
{Pri('1'): Pri('1'), Pri('2'): Pri('2'), Pri('N'): Pri('N')}


texts: C++ library to compile-time merge sets to a single array

texts:
I built this small library to create a compile-time assembled array from several hard-coded sequences (of unequal length) of a type T:

mergeable_set.hpp

#pragma once

template <typename T>
class mergeable {
public:
    template <T... Ts>
    struct set {
        static constexpr T values[] {Ts...};

        constexpr const auto& operator[](const int i) const noexcept { return values[i]; }
        constexpr auto size() const noexcept { return sizeof...(Ts); }

        class iterator {
        public:
            constexpr explicit iterator(set& _ref, const int i = 0) : ref{_ref}, index{i} {}
            constexpr iterator& operator++() noexcept { ++index; return *this; }
            constexpr bool      operator!=(const iterator& other) const noexcept { return index != other.index; }
            constexpr auto&     operator* () noexcept { return ref[index]; }
        private:
            set& ref;
            int index;
        };
        class citerator {
        public:
            constexpr citerator(const set& _ref, const int i) : ref{_ref}, index{i} {}
            constexpr citerator&  operator++() noexcept { ++index; return *this; }
            constexpr bool        operator!=(const citerator& other) const noexcept { return index != other.index; }
            constexpr const auto& operator* () const noexcept { return ref[index]; }
        private:
            const set& ref;
            int index;
        };
        constexpr iterator begin() noexcept { return iterator{*this, 0}; }
        constexpr citerator begin() const noexcept { return citerator{*this, 0}; }
        constexpr iterator end()   noexcept { return iterator{*this, sizeof...(Ts)}; }
        constexpr citerator end()   const noexcept { return citerator{*this, sizeof...(Ts)}; }
    };

private:
    template <typename, typename...> struct concat{};
    template<T... A, T... B>
    struct concat<set<A...>, set<B...>> {
        using type = set<A..., B...>;
    };
    template<T... A>
    struct concat<set<A...>> {
        using type = set<A...>;
    };

    template <typename...> struct _combine {};
    template <typename A, typename B, typename... C>
    struct _combine<A, B, C...> {
        using type = typename concat<A, typename _combine<B, C...>::type>::type;
    };
    template <typename A, typename B>
    struct _combine<A, B> {
        using type = typename concat<A, B>::type;
    };
    template <typename A>
    struct _combine<A> {
        using type = typename concat<A>::type;
    };

public:
    template <typename...U>
    using combine = typename _combine<U...>::type;
};

Usable like this:

#include "mergeable_set.hpp"

int main() {
    mergeable<int>::set<1, 2, 3> a;
    mergeable<int>::set<4, 5, 6> b;
    mergeable<int>::set<1, 2, 3> c;
    mergeable<int>::set<4, 5, 6> d;
    mergeable<int>::combine<decltype(a),
                            decltype(b),
                            decltype(c),
                            decltype(d)> z;

    int temp = 0;

    for (auto e : z) {
        temp += e;
    }

    volatile int l = temp;
}

With z behaving like a plain array (const int z[12]).
Interestingly this exposes some strange behaviour in GCC. When compiling x86 code any array over 7 elements generates SIMD bulk add instructions. While this sounds great, disabling SSE actually compiles out all instructions, straight up to the final result. The latter is obviously preferable. Did I just hit a logic bug in GCC here?

A live example of this effect: https://godbolt.org/g/4LAJXV
Remove -mno-sse to see the difference.

I'd love to hear what can be improved to make this into a more general purpose library.


texts:
From Hackerrank:

  Given a string S, find the number of "unordered anagrammatic pairs" of substrings. In other words, find the number of unordered pairs of substrings of  S that are anagrams of each other.

  Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string.

  Input Format

  First line contains T, the number of testcases. Each testcase consists of string  S in one line.

  Constraints

  1 <= t <= 10

  2 <= length(s) <= 100

  String S contains only the lowercase letters of the English alphabet.

  Output Format

  For each testcase, print the required answer in one line.

I am losing two test cases with Time Limit Exceeded. Can somebody please tell me how to optimize the code?

#include <bits/stdc++.h>

using namespace std;

int sherlockAndAnagrams(string s)
{

    unordered_map<char,int> count1,count2;
    unordered_map<char,int>::iterator it;
    int l=s.length();
    int len1,len2;
    int wall1,wall2;
    int cnt=0;
    int flg=0;
    int i,j;
    int dflg;
    wall1=0,wall2=l-1;
    for(wall1=0;wall1<l-1;++wall1)
    {
        len1=1;
        count1.clear();
        for(i=wall1;i<l-1;++i,++len1)
        {
            ++count1[s[i]];
            for(wall2=l-1;wall2>wall1;--wall2)
            {
                len2=1;
                count2.clear();
                flg=0;
                dflg=0;
                for(j=wall2;j>wall1;--j,++len2)
                {
                    ++count2[s[j]];
                    if(len2>len1)
                        break;
                    if(len2==len1)
                    {
                        dflg=1;
                        for(it=count1.begin();it!=count1.end();++it)
                        {
                            if(it->second!=count2[it->first])
                            {
                                flg=1;
                                break;
                            }
                        }
                        break;
                    }
                }
                if(dflg==1 && flg==0)
                        ++cnt;
            }
        }
    }
    return cnt;
}

int main() {
        int q;
        cin >> q;
        for(int a0 = 0; a0 < q; a0++){
            string s;
            cin >> s;
            int result = sherlockAndAnagrams(s);
            cout << result << endl;
        }
        return 0;
    }


texts: "Causes" Puzzle solution (network of words with Levenshtein distance 1)

texts:
The "Causes" puzzle is to recursively find, starting with the word "causes", the number of words that can be formed by substituting one letter.

sub addMember {
my ( $self, $newMember ) = @_;
my $len = length($newMember->{'_data'});
my $newMemberIndex = push(@{$self->{'_MemberList'}}, $newMember) - 1;
$self->{'_MemberHash'}->{$newMember->{'_data'}} = \$newMember;

#Fetch bucket of same length and check for distance
my $memberList = $self->{'_Bucket'}->getBucket($len);

foreach my $index (@$memberList){
  if($index eq $newMemberIndex) {
    next;
  }
  my $memberObj = $self->{'_MemberList'}[$index];
  if($self->isFriend($newMember->{'_data'}, $memberObj->{'_data'}) eq true) {
    $newMember->addNeighbour($index);
    $memberObj->addNeighbour($newMemberIndex);
  }
}

#Fetch bucket of length - 1 and check for distance
$memberList = $self->{'_Bucket'}->getBucket($len-1);
foreach my $index (@$memberList){
  if($index eq $newMemberIndex) {
    next;
  }
  my $memberObj = $self->{'_MemberList'}[$index];
  if($self->isFriend($newMember->{'_data'}, $memberObj->{'_data'}) eq true) {
    $newMember->addNeighbour($index);
    $memberObj->addNeighbour($newMemberIndex);
  }
}
#Fetch Bucket of length + 1 and check for distance
$memberList = $self->{'_Bucket'}->getBucket($len+1);
foreach my $index (@$memberList){
  if($index eq $newMemberIndex) {
    next;
  }
  my $memberObj = $self->{'_MemberList'}->[$index];
  if($self->isFriend($newMember->{'_data'}, $memberObj->{'_data'}) eq true) {
    $newMember->addNeighbour($index);
    $memberObj->addNeighbour($newMemberIndex);
  }
}

#Add to the member list
$self->{_Bucket}->addToBucket($len, $newMemberIndex);

}


texts: Random Winner Based on Percentage Weighting

texts:
I have 3 variables and each one has their own percentage to win out of 99.99...%. (The 3 percentages don't act up to 100% perfectly)

When button1 is clicked, it will go through 100,000 simulations and afterwards it will output how many times each variable "won" in a MessageBox.

I would like some help optimizing my code. I feel like it's too clunky and maybe there's an easier way to complete the same task with far less lines.

private Random rand = new Random();

private int aWon = 0;
private int bWon = 0;
private int cWon = 0;

private void button1_Click(object sender, EventArgs e)
{
    // loop 100000 times for an accurate sample size output
    for (int i = 0; i < 100000; i++)
    {
        // randomNumber == a random number between 0 and 0.9999999999999999
        double randomNumber = rand.NextDouble() * (0.9999999999999999 - 0) + 0;
        // a + b + c == 0.9999999999999999
        double a = 0.4917127071823204; // ~49% to win
        double b = 0.3922651933701657; // ~39% to win
        double c = 0.1160220994475138; // ~11% to win

        // if randomNumber is less than or equal to 0.9999999999999999
        // AND greater than 0.5082872928176795
        //
        // 0.9999999999999999   -   0.5082872928176795   =   0.4917127071823204 ( a's value )
        if (randomNumber <= a + b + c && randomNumber > b + c)
        {
            aWon += 1;
        }

        // if randomNumber is less than or equal to 0.5082872928176795
        // AND greater than 0.1160220994475138
        //
        // 0.5082872928176795   -   0.1160220994475138   =   0.3922651933701657 ( b's value )
        if (randomNumber <= b + c && randomNumber > c)
        {
            bWon += 1;
        }

        // if randomNumber is less than or equal to 0.1160220994475138
        //
        // 0.1160220994475138   -   0   =   0.1160220994475138 ( c's value )
        if (randomNumber <= c)
        {
            cWon += 1;
        }
    }

    // show how many times each variable won
    MessageBox.Show(aWon + "\n" + bWon + "\n" + cWon);
}


texts: Proper capitalization for surname like McDonald

texts:
I am using the code below to capitalize a string properly. I would like to know if there is a better way to code the surname portion, as the way it stands now can become very bloated depending on how many surnames I plan on adding.

This is a follow up to: Capitalize string except for conjunction words

Dim conjunctions
Dim suffixes
Dim surnames
Set conjunctions = CreateObject("System.Collections.Arraylist")
Set suffixes = CreateObject("System.Collections.Arraylist")
Set surnames = CreateObject("System.Collections.Arraylist")

conjunctions.Add("a")
conjunctions.Add("an")
conjunctions.Add("and")
conjunctions.Add("as")
conjunctions.Add("at")
' etc....

suffixes.Add("ii")
suffixes.Add("iii")
suffixes.Add("iv")
suffixes.Add("vi")
suffixes.Add("vii")
suffixes.Add("viii")
suffixes.Add("ix")

surnames.Add("mcdonald")

for each item in xTextSplit
    xWord = item
    if conjunctions.contains(lcase(item)) then
        xWord = lcase(item)
    elseif suffixes.contains(lcase(item)) then
        xWord = ucase(item)
    elseif surnames.contains(lcase(item)) then
        xWord = "Mc" & UCase(Mid(item, 3, 1)) & Mid(item, 4)
    end if
    xCompleteWord = xCompleteWord & " " & xWord
next

queryForHeading = xCompleteWord
queryForHeading = Mid(queryForHeading, 2)
queryForHeading = UCase(Mid(queryForHeading, 1, 1)) & Mid(queryForHeading, 2)


texts:
# Alex Grattan
# 17/10/14

message = input("Enter your message to have it printed backwards:")
split_message = list(message.split())
reverse_message_list = []
reverse_message = ""

for i in range(len(split_message)):
    reverse_message_list.append(split_message.pop())

reverse_message_list = [x + ' ' for x in reverse_message_list]

for i in reverse_message_list:
    reverse_message += i

print (reverse_message)


texts:
I am writing Rijndael for academic purpose, following wikipedia's description.

https://en.wikipedia.org/wiki/Rijndael_key_schedule

I would like to know, if up to this point it is correct, both from pragmatic programmer and strict cryptographer views.

class KeyExpander
{
    private static final int COLUMN_SIZE = 4
    private static final int BLOCK_SIZE = 4 * COLUMN_SIZE

    private final KeyScheduler keyScheduler = new KeyScheduler()

    byte[] expand(byte[] key)
    {
        int expandedKeyLength = deductExpandedKeyLength(key.length)
        byte[] expandedKey = new byte[expandedKeyLength]
        System.arraycopy(key, 0, expandedKey, 0, BLOCK_SIZE)

        for(int activeBlock = BLOCK_SIZE; activeBlock < expandedKeyLength; activeBlock += BLOCK_SIZE)
        {
            byte[] core = Arrays.copyOfRange(expandedKey, activeBlock - COLUMN_SIZE, activeBlock)
            byte[] buffer = Arrays.copyOfRange(expandedKey, activeBlock - BLOCK_SIZE, activeBlock)

            int roundNumber = activeBlock / BLOCK_SIZE
            core = keyScheduler.scheduleCore(core, roundNumber)

            for(int activeByte = 0; activeByte < BLOCK_SIZE; activeByte++)
            {
                buffer[activeByte] ^= core[activeByte % COLUMN_SIZE]
                expandedKey[activeBlock + activeByte] = buffer[activeByte]
            }
        }

        expandedKey
    }

    private int deductExpandedKeyLength(int primeKeyLength)
    {
        switch(primeKeyLength)
        {
            case 16: return 176
            case 24: return 208
            case 32: return 240
            default: throw new RuntimeException("Invalid key length " + primeKeyLength)
        }
    }
}

Method expand accepts user's key and returns expanded key for all rounds.
I am looking for way to divide further this method, but unfortunately, inner loop requires access to expandedKey, and I think that passing it by value 100-200 times isn't best idea.
My second idea was to extract it to private field, but it would make whole class state-full (now it is stateless).

class KeyScheduler
{
    private final SubstitutionBox substitutionBox = new SubstitutionBox()
    private final RoundConstant roundConstant = new RoundConstant()

    byte[] scheduleCore(byte[] column, int round)
    {
        column = rotate(column)
        column = substitute(column)
        column[0] ^= roundConstant.of(round)

        column
    }

    private byte[] rotate(byte[] column)
    {
        [column[1], column[2], column[3], column[0]]
    }

    private byte[] substitute(byte[] column)
    {
        for(int i = 0; i < 4; i++)
        {
            column[i] = substitutionBox.substitute(column[i])
        }

        column
    }
}

Code is written in groovy, but I am using strong types (so it's nearly java).

Beside mentioned defects, I am open for other suggestions.


texts: Updating an auto-generated invoice (future) when current plan changes

texts:
I've built-out a mechanism to go and find an auto-generated invoice and update it with new information when a plan is changed or if users are added to the plan for the current billing period. It will make it a lot easier than having to remember to change it a month, quarter, 6 months, or even a year from now. And this also reduces the burden on the finance department from having to go find the future invoice and manually updating it. I hope my comments in the code are clear.

I'm mainly looking for feedback on my code. It does work. I will need to write tests for this though.

Model

def new_amount(max_users, item)
  amount = ((max_users.to_i * item.amount) / item.quantity)
  # Returns the new adjusted amount
  case term_type
  when 'month'      then amount / 12
  when 'quarter'    then amount / 4
  when 'semiannual' then amount / 2
  when 'annual'     then amount / 1
  else                   amount
  end
end

Controller

  # Finds the upcoming / unpaid system invoice.
  manual_invoice = @subscription.manual_invoices.system.not_paid.latest.first

  # TODO: This is very hacky. If I use dup or clone on manual_invoice, and
  #   when change_plan is executed, the calculation runs, regardless if
  #   there were any updates. Also, chaining these scopes brings back all
  #   of the records when using .latest... so, I end up with an invoice
  #   where paid_at is nil.
  first_manual_invoice = @subscription.manual_invoices.system.paid.first

  # Guards changing of plan from blowing up if manual_invoice.nil?
  if manual_invoice
    # Iterate through the invoice's items.
    first_manual_invoice.items.each do |item|
      # Set new_amount by taking the new max_users quantity and multiply it
      #   by the previous amount. Then divide it by the previous max_users
      #   quantity. Finally, divide by payment frequency per term.
      new_amount = @subscription.new_amount(max_users, item)
      # Update the manual_invoice items with the calcuated new_amount and
      #   user quantity.
      manual_invoice.items.first.update_attributes(quantity: max_users,
                                                   amount: new_amount)
      # Update the manual_invoice.
      manual_invoice.update_attributes(amount_in_cents: new_amount,
                                       term_type: term_type,
                                       term_start_date: term_start_date,
                                       term_end_date: term_end_date,
                                       due_on: term_end_date)
    end
  end


texts: Access resolve function outside of a JavaScript Promise

texts:
I have an object that needs to have a single point of initialization, and other callers need to wait until the initialization is complete before continuing.

I have done this with jQuery, and it feels like I'm working with the design, but the same approach with a native JavaScript Promise seems like it is going against the grain.

I need to replace use of jQuery promise with a native JS Promise.

Is this initialization pattern OK, or is there a better approach?

On the surface it seems that an event pub/sub pattern would be a better fit, but I can't guarantee that the init() will be called before the ready() is called, which would result in missed events.

jQuery

function Foo() {

    var dfd= $.Deferred();
    this.ready = function () {
        return dfd.promise();
    }
    this.init = function(){
        setTimeout(function(){
            dfd.resolve();
        }, 2000);
    }
};

var foo = new Foo();

//foo.ready() may be called from multiple places.
foo.ready().then(function () {
    alert('foo.ready');
});

//foo.init would only be called once.
foo.init();

JavaScript Promise

function Foo() {

    var resolver,
        rejector,
        readyPromise = new Promise(function (resolve, reject) {
            resolver = resolve;
            rejector = reject;
        });

    this.ready = function () {
        return readyPromise;
    }
    this.init = function () {
        setTimeout(function () {
            resolver();
        }, 2000);
    }
};

var foo = new Foo();

//foo.ready() may be called from multiple places.
foo.ready().then(function () {
    alert('foo.ready');
});

//foo.init would only be called once.
foo.init();


texts:
Today I went to an interview with the Cleartrip software company. For the first round programming, we need to build a mini bank application.

In the question paper they clearly mentioned that no data persistence is required.

Create an account
Deposit money
Withdraw money, honor daily withdrawal limit.
Check the balance

This is what I did on my own, and I was getting rejected.

import java.util.Scanner;

public class CreateAccount {
    int accountid;
    String accountantname;
    String IFSCcode;

   public CreateAccount(int accountid,String accountantname,String IFSCcode){
    this.accountid = accountid;
    this.accountantname = accountantname;
    this.IFSCcode = IFSCcode;
   }

    /*//adding deposit money with the balance
    public double despositMoney() throws MiniumAmountDeposit{

        double Currentbalance = 0.00;
        Scanner scn = new Scanner(System.in);
        System.out.println("please enter the deposit amount");
        double Depositamount = scn.nextDouble();
        Currentbalance += Depositamount ;
        System.out.println("your currentbalance="+Currentbalance);

        return Currentbalance;
    }*/

    //withdrawl money  and set daily withdrawl limit
    public void WithdrawMoney() throws InsufficientBalException, MiniumAmountDeposit{

        double Currentbalance = 0.00;
        Scanner deposit = new Scanner(System.in);
        System.out.println("please enter the deposit amount");
        double Depositamount = deposit.nextDouble();
        Currentbalance += Depositamount ;
        System.out.println("your currentbalance="+Currentbalance);

        /*double Currentbalanace = despositMoney();*/

        //setDaily Withdrawl limit
           final double setDailyLimit = 2500.00;

            Scanner withDraw = new Scanner(System.in);
            System.out.println("please enter the withdraw amount");
            double WithdrawMoney =withDraw.nextDouble();

        if(Currentbalance < WithdrawMoney)
            System.out.println("you have less amount : your current balance is="+Currentbalance);

        else if (WithdrawMoney > setDailyLimit)
            System.out.println("you have entered amount exceed than daily limit : your dailyLimit="+setDailyLimit);

        else
            Currentbalance -= WithdrawMoney;
            System.out.println("your current balance is="+Currentbalance);

    }

    /*public void setWithdrawlLimit()throws exceedLimit{
        Scanner scn = new Scanner(System.in);
        System.out.println("please enter the withdraw amount");
           double  enterAmount = scn.nextDouble();
        double DailysetLimit = 2500;

        if(enterAmount>DailysetLimit)
            System.out.println("you have exceed daily limit : your dailyLimit"+DailysetLimit);

    }*/

    public String toString(){

        return "accountid="+this.accountid + "accountantname="+this.accountantname + "IFSCcode="+this.IFSCcode;
    }

    public static void main(String[] args){
        CreateAccount account = new CreateAccount(1234455533,"samy","ICIC09");
        System.out.println("you have created account : " +account);
    /*
        try {
            account.despositMoney();
        } catch (MiniumAmountDeposit e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

        try {
            account.WithdrawMoney();
        } catch (InsufficientBalException | MiniumAmountDeposit e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*try {
            account.setWithdrawlLimit();
        } catch (exceedLimit e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

*/
    }

}


texts: Apply discount changes with Strategy pattern

texts:
I am implementing  strategy pattern. I have defined a strategy as interfaces and concrete classes to implement the strategy. Based on user selection/configuration, the algorithm to apply the discount changes.

  public interface IStrategy
    {
        double calculate(double x, double y);
    }

concrete classes implementing the gold strategy is listed below -

public class clsGoldDiscountStrategy : IStrategy
    {
        public double calculate(double x, double y)
        {
            return (x * y) * 0.8;
        }
    }
}

concrete classes implementing the platinumstrategy is listed below -

public class clsPlatinumDiscountStrategy : IStrategy
    {
        public double calculate(double x, double y)
        {
            return (x * y) * 0.7;
        }
    }

The business logic to apply

public class clsBL
    {
        public double costPrice { get; set; }
        public double qty { get; set; }
        IStrategy _strategy;

        public clsBL(IStrategy strategy)
        {
            _strategy = strategy;
        }

        public double GetfinalPrice(double cp, double qty)
        {
            return _strategy.calculate(cp, qty);
        }

    }

//Main method

static void Main(string[] args)
        {
            Console.WriteLine("Enter the discount Plan (Gold/Platinum)");
            string filter = Console.ReadLine().ToUpper();
            double result = 0;

            if (filter.Length > 0)
            {
                switch (filter)
                {
                    case "GOLD":
                        //Gold
                        clsBL blgold = new clsBL(new clsGoldDiscountStrategy());
                        blgold.costPrice = 5;
                        blgold.qty = 10;

                        result = blgold.GetfinalPrice(blgold.costPrice, blgold.qty);
                        break;

                    case "PLATINUM":
                        //Platinum
                        clsBL blplatinum = new clsBL(new clsPlatinumDiscountStrategy());
                        blplatinum.costPrice = 10;
                        blplatinum.qty = 8;

                        result = blplatinum.GetfinalPrice(blplatinum.costPrice, blplatinum.qty);
                        break;
                    default:
                        Console.WriteLine("Enter the discount value as either  gold or platinum");
                        break;
                }

                Console.WriteLine("The result for " + filter + " is " + result);

            }
            else
            {
                Console.WriteLine("Enter the discount value");
                return;
            }

            Console.ReadLine();

        }


texts:
I've been reading "Head First Java" and some of the early projects surround basic swing and basic MIDI.

So I've put the two together and written a basic "Synthesiser"/"Piano" using what I have learned.

I know that I need to add some safety features and there's probably some method optimisation staring me in the face but would love to know what you all think!

import javax.swing.*;
import javax.sound.midi.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class VirtualKeyboard implements ActionListener {

    public static ArrayList<String> note = new ArrayList<String>();
    public static ArrayList<String> extendedNote = new ArrayList<String>();
    JTextField octaveChoice;
    JTextField instrumentChoice;

    public static void main (String[] args) {
        VirtualKeyboard gui = new VirtualKeyboard();

        String[] preNote = {"C","D","E","F","G","A","B"};
        String[] preExtendedNote = {"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"};

        for (int i = 0; i < 7; i++) {
            note.add(preNote[i]);
        }

        for (int i = 0; i < 12; i++) {
            extendedNote.add(preExtendedNote[i]);
        }

        gui.setGUI();
    }

    public void setGUI() {
        JFrame frame = new JFrame("Rhysy's Virtual Keyboard!!!");
        JPanel keyPanel = new JPanel();
        JPanel controlPanel = new JPanel();

        JButton[] key = new JButton[7];

        for (int i = 0; i < 7; i++) {
            key[i] = new JButton(note.get(i));
            key[i].addActionListener(this);
            keyPanel.add(key[i]);
        }

        JLabel instrumentChoiceLabel = new JLabel("Instrument Choice: ");
        instrumentChoice = new JTextField(1);

        JLabel octaveChoiceLabel = new JLabel("Octave: ");
        octaveChoice = new JTextField(1);

        controlPanel.add(instrumentChoiceLabel);
        controlPanel.add(instrumentChoice);
        controlPanel.add(octaveChoiceLabel);
        controlPanel.add(octaveChoice);

        frame.getContentPane().add(BorderLayout.NORTH, keyPanel);
        frame.getContentPane().add(BorderLayout.SOUTH, controlPanel);
        frame.setSize(500,200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        int finalNote = 0;
        Object source = e.getSource();
        if (source instanceof JButton) {
            JButton but = (JButton) source;
            System.out.print(but.getText());

            finalNote = (Integer.parseInt(octaveChoice.getText()) * 12) + extendedNote.indexOf(but.getText());

            System.out.print(" (" + finalNote + ")\n");

            playNote(finalNote, Integer.parseInt(instrumentChoice.getText()));
        }
    }

    public void playNote(int finalNote, int finalInstrument) {
        try {

            Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.open();
            Sequence sequence = new Sequence(Sequence.PPQ,4);
            Track track = sequence.createTrack();

            MidiEvent event = null;

            ShortMessage first = new ShortMessage();
            first.setMessage(192,1,finalInstrument,0);
            MidiEvent changeInstrument = new MidiEvent(first, 1);
            track.add(changeInstrument);

            ShortMessage a = new ShortMessage();
            a.setMessage(144,1,finalNote,100);
            MidiEvent noteOn = new MidiEvent(a, 1);
            track.add(noteOn);

            ShortMessage b = new ShortMessage();
            b.setMessage(128,1,finalNote,100);
            MidiEvent noteOff = new MidiEvent(b, 16);
            track.add(noteOff);

            sequencer.setSequence(sequence);
            sequencer.start();
        } catch (Exception ex) { ex.printStackTrace(); }

    }
}


texts:
I was working on the following interview question:

  Given an array of integers, return a new array such that each element
  at index i of the new array is the product of all the numbers in the
  original array except the one at i.

  For example, if our input was [1, 2, 3, 4, 5], the expected output
  would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the
  expected output would be [2, 3, 6].

  Follow-up: what if you can't use division?

I decided to do the followup question in Haskell:

{-# LANGUAGE ViewPatterns, PatternSynonyms #-}
import Control.Monad (join)
import Control.Arrow ((***))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Monoid (Product(..), getProduct)

mapTuple = join (***)

pattern Empty   <- (Seq.viewl -> Seq.EmptyL)
pattern x :< xs <- (Seq.viewl -> x Seq.:< xs)

data Tree a = Leaf a | Branch a (Tree a, Tree a)
label :: Tree a -> a
label (Leaf a) = a
label (Branch a _) = a

{- Create a complete binary tree, such that each subtree contains the concat of all
 - elements under it. -}
makeTree :: Monoid a => Seq a -> Tree a
makeTree Empty = undefined
makeTree (label :< Empty) = Leaf label
makeTree s =
  let midpoint = Seq.length s `div` 2 in
  let subseq = Seq.splitAt midpoint s in
  let subtrees = mapTuple makeTree subseq in
  let subtreeLabels = mapTuple label subtrees in
  let label = uncurry mappend subtreeLabels in
  Branch label subtrees

{- Zippers. -}
data Crumb a = LeftCrumb a (Tree a) | RightCrumb a (Tree a)
type Breadcrumbs a = [Crumb a]
type Zipper a = (Tree a, Breadcrumbs a)

goLeft :: Zipper a -> Zipper a
goLeft (Branch x (l, r), bs) = (l, LeftCrumb x r:bs)
goLeft (Leaf _, _) = error "Nothing to go left into"

goRight :: Zipper a -> Zipper a
goRight (Branch x (l, r), bs) = (r, RightCrumb x l:bs)
goRight (Leaf _, _) = error "Nothing to go right into"

-- Concat of all elements except the one corresponding to the given crumbs
concatAllExcept :: Monoid a => Breadcrumbs a -> a
concatAllExcept = concatAllExceptRev . reverse where
  concatAllExceptRev [] = mempty
  concatAllExceptRev ((LeftCrumb _ subtree) : xs) =
    concatAllExceptRev xs <> label subtree
  concatAllExceptRev ((RightCrumb _ subtree) : xs) =
    label subtree <> concatAllExceptRev xs

-- Return a list of zippers pointing to the leafs of the tree
dfsList :: Tree a -> [Zipper a]
dfsList t =
  reverse $ dfsListHelper (t, []) [] where
    dfsListHelper zipper@(Leaf _, _) accum = zipper : accum
    dfsListHelper zipper@(Branch _ _, _) accum =
      -- Since this is a Branch node, both [goLeft] and [goRight] will work.
      let l = goLeft zipper
          r = goRight zipper in
      dfsListHelper r (dfsListHelper l accum)

{- Produces a list such that the ith element is the concat of all elements in the
 - original list, excluding the ith element. -}
concatAllExceptEach :: Monoid a => [a] -> [a]
concatAllExceptEach = map (concatAllExcept . snd) . dfsList . makeTree . Seq.fromList

answer :: [Integer] -> [Integer]
answer = map getProduct . concatAllExceptEach . fmap Product

main = do
  print $ answer [3, 10, 33, 4, 31, 31, 1, 7]
  print $ answer [1, 2, 3, 4, 5]
  print $ concatAllExceptEach ["A", "B", "C", "D"]

Algorithm runs in Θ(n log n) which I believe is optimal. New to Haskell so all feedback welcome.


texts:
This function takes a list/array of booleans and converts them to an array that counts the number of either True/False values found next to each other.
I'd like to see this optimized for performance. It's not too slow, but I do use multiple loops with embedded if-else statements, I'm wondering if they're absolutely necessary.
import numpy as np

x = np.random.uniform(1,100,100)
b = x > x.mean()

#function start, input is b
endarray = []
count = 0
instance = True
while True:
    subarray = 0
    while True:
        if count >= len(b):
            endarray.append(subarray)
            break
        if b[count] == instance:
            subarray += 1
            count += 1
        else:
            endarray.append(subarray)
            instance = not instance
            break
    if count >= len(b):
        break

if len(endarray) % 2 != 0:
    endarray = np.append(endarray, 0)
else:
    endarray = np.asarray(endarray)

endarray = endarray.reshape(-1,2)

The output is a Nx2 array, where the left-hand values are always a count of Trues, and the right-hand values are always a count of Falses.
After a sequence of False values are no longer continuous(a True value pops up), the next count of True values begin, and vice versa.
Example input
b
Out[31]:
array([ True,  True,  True, False,  True,  True,  True,  True, False,
       False,  True, False, False,  True, False, False, False, False,
        True, False, False, False,  True,  True,  True,  True, False,
       False,  True, False, False, False, False, False, False,  True,
        True, False,  True,  True, False, False,  True, False, False,
        True, False, False,  True, False,  True, False,  True, False,
        True,  True,  True, False,  True, False,  True,  True,  True,
        True, False, False,  True, False,  True,  True,  True,  True,
        True,  True, False,  True,  True, False,  True,  True, False,
       False,  True, False,  True, False, False,  True,  True,  True,
        True, False, False, False, False, False,  True,  True,  True,
        True])

Example output
endarray
Out[32]:
array([[3, 1],
       [4, 2],
       [1, 2],
       [1, 4],
       [1, 3],
       [4, 2],
       [1, 6],
       [2, 1],
       [2, 2],
       [1, 2],
       [1, 2],
       [1, 1],
       [1, 1],
       [1, 1],
       [3, 1],
       [1, 1],
       [4, 2],
       [1, 1],
       [6, 1],
       [2, 1],
       [2, 2],
       [1, 1],
       [1, 2],
       [4, 5],
       [4, 0]])

Edit:
I wanted to add an updated version of this code, the one in the answer below is not technically correct in all regards. But this was entirely derived from it:
m = np.append(b[0], np.diff(b))
_, c = np.unique(m.cumsum(), return_index=True)
out = np.diff(np.append(c, len(b)))
if b[0] == False:
    out = np.append(0, out)
if len(out) % 2:
    out = np.append(out, 0)
out = out.reshape(-1, 2)


texts: Coding on Point interfaces/superclasses instead of implementations

texts:
From pretty much any book I've read it always said to code on interfaces/superclasses and rarely on implementations, today though that advice made a bit confused about how I should format my code.
Questions:

Should I be using Point2DAdvanced or Point2D.Double in the the methods of MedianPoint (like JavaRDD<>, the 2 private methods, the variables)? Same goes for FlagPointPairProducer.
Should I be using MedianPoint or Point2D.Double in the FlagPointPairProducer class?
Should I store the MedianPoint from the static method in a MedianPoint or Point2D.Double?

The Code:
First off I have a MedianPoint class which extends Point2D.Double. This class is responsible for outputting a median point out of a collection of points (for now only an RDD).
public class MedianPoint extends Point2D.Double {

    public MedianPoint(double x, double y) {
        super(x, y);
    }

    public static MedianPoint fromPointRDD(JavaRDD<Point2DAdvanced> points) {
        Point2DAdvanced biggestPointByXDimension = points.reduce((a, b) -> getBiggestPointByXDimension(a, b));
        Point2DAdvanced biggestPointByYDimension = points.reduce((a, b) -> getBiggestPointByYDimension(a, b));

        double xDimensionMedian = biggestPointByXDimension.getX() / 2.0;
        double yDimensionMedian = biggestPointByYDimension.getY() / 2.0;

        return new MedianPoint(xDimensionMedian, yDimensionMedian);
    }

    private static Point2DAdvanced getBiggestPointByXDimension(Point2DAdvanced first, Point2DAdvanced second) {
        return first.getX() > second.getX() ? first : second;
    }

    private static Point2DAdvanced getBiggestPointByYDimension(Point2DAdvanced first, Point2DAdvanced second) {
        return first.getY() > second.getY() ? first : second;
    }
}

I also have a FlagPointPairProducer class which according to a median point it calculates a subspace flag for a given Point2DAdvanced (another Point2D.Double extension) and returns a tuple of the flag and the point.
public class FlagPointPairProducer implements Serializable {

    private final Point2D.Double medianPoint;

    public FlagPointPairProducer(Point2D.Double medianPoint) {
        this.medianPoint = medianPoint;
    }

    public Tuple2<PointFlag, Point2DAdvanced> getFlagPointPair(Point2DAdvanced point) {
        PointFlag flag = calculateFlag(point);
        return new Tuple2<>(flag, point);
    }

    private PointFlag calculateFlag(Point2DAdvanced point) {
        double x = point.getX();
        double y = point.getY();
        double medianX = medianPoint.getX();
        double medianY = medianPoint.getY();

        int xBit = x < medianX ? 0 : 1;
        int yBit = y < medianY ? 0 : 1;

        return new PointFlag(xBit, yBit);
    }
}

So I can initialize a FlagPointPairProducer like so:
Point2D.Double medianPoint = MedianPoint.fromPointRDD(points);
FlagPointPairProducer producer = new FlagPointPairProducer(medianPoint);

Code requested for Point2DAdvanced:
public class Point2DAdvanced extends Point2D.Double implements Serializable {

    public Point2DAdvanced(double x, double y) {
        super(x, y);
    }

    public boolean dominates(Point2D.Double point) {
        return (x <= point.getX() && y < point.getY())
                || (y <= point.getY() && x < point.getX());
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append('(').append(x).append(", ").append(y).append(')');
        return builder.toString();
    }

    public static Point2DAdvanced fromTextLine(String textLine, String delimiter) {
        textLine = textLine.trim();
        String[] lineArray = textLine.split(delimiter);
        double x = java.lang.Double.parseDouble(lineArray[0]);
        double y = java.lang.Double.parseDouble(lineArray[1]);
        return new Point2DAdvanced(x, y);
    }
}


texts: Parsing user name and password from binary in Erlang + Cowboy

texts:
I am working on a web app that uses a WebSocket to log in users. I would like to minimize bandwidth usage by using binary messages. I came up with the following, and would like to know whether there is something better I could be doing:

-define(LOGIN, 1).

websocket_handle({binary, <<?LOGIN:8,LengthUser:8, Rest/bitstring>>}, Req, State) ->
    LU2 = LengthUser*8,
    <<Username:LU2/bitstring, Password/bitstring>> = Rest,
    % Do the actual logging in...

I did a decent amount of research, and couldn't find a way to avoid using the Rest piece in order to accommodate variable length bitstring patterns. The web app uses an ArrayBuffer and a few DataViews in order to construct the message.


texts: Pick a column for each row by column-header name

texts:
I am parsing a table:

    |-------|
    |Bar|Foo|
    |-------|
    | 5 | 6 |
    |'f'|'g'|
    | 1 | 8 |
    |_______|

I've tried a number of ways of writing a pick function in Python:

#!/usr/bin/env python

from collections import OrderedDict

def pick0(r, k):
    Bar, Foo = r
    return locals().get(k)

def pick1(r, k, h):
    try:
        return r[h.index(k)]
    except ValueError:
        return None

pick2 = lambda r, k, h: OrderedDict(zip(h, r)).get(k)

pick3 = lambda r, ks, h: map(lambda t: t[0] in ks and t[1] or None,
                             OrderedDict(zip(h, r)).iteritems())

if __name__ == '__main__':
    key = 'Foo'
    headers = 'Bar', 'Foo'
    for row in ((5, 6), ('f', 'g'), (1, 8)):
        # Method 0
        print OrderedDict(Bar=row[0], Foo=row[1]).get(key)

        # Method 1
        print pick0(row, key)

        # Method 2
        print pick1(row, key, headers)

        # Method 3
        print pick2(row, key, headers)

        # Method 4
        print pick3(row, ('Foo', 'Bar'), headers)

The last three methods are generalised. The last method allows you to specify multiple keys to pick out.


texts:
All colors can be represented by an int, and often you want to get the individual red, green and blue values from that int.

I have a method int2rgb (and another called rgb2int) that does this. Is this a clear/good name?

public static int[] int2rgb(final int color) {
    return new int[] { (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF };
}

public static int rgb2int(final int red, final int green, final int blue) {
    return (red << 16) + (green << 8) + blue;
}

public static int rgb2int(final int[] color) {
    return (color[0] << 16) + (color[1] << 8) + color[2];
}

And in case you are interested, the rest of the class is here.


texts:
I have a small animation with Raphael using a large amount of code.  Is there any way to reduce it?

Demo

window.onload = function () {
    var elements = document.querySelectorAll('.colbr');
    for (i=0; i<elements.length; i++) {
        var loadSpinner = spinner(elements[i], 7, 12, 10, 3, "#000");
    }
};

function spinner(holderid, R1, R2, count, stroke_width, colour) {
    var sectorsCount = count || 12,
        // color = colour || "#000",
        color = "#000",
        width = stroke_width || 15,
        r1 = Math.min(R1, R2) || 35,
        r2 = Math.max(R1, R2) || 60,
        cx = r2 + width,
        cy = r2 + width,
        r = Raphael(holderid, r2 * 2 + width * 2, r2 * 2 + width * 2),

        sectors = [],
        opacity = [],
        beta = 2 * Math.PI / sectorsCount,

        pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
        Raphael.getColor.reset();
    for (var i = 0; i < sectorsCount; i++) {
        var alpha = beta * i - Math.PI / 2,
            cos = Math.cos(alpha),
            sin = Math.sin(alpha);
        opacity[i] = 1 / sectorsCount * i;
        sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
        if (color == "rainbow") {
            sectors[i].attr("stroke", Raphael.getColor());
        }
    }
    var tick;
    (function ticker() {
        opacity.unshift(opacity.pop());
        for (var i = 0; i < sectorsCount; i++) {
            sectors[i].attr("opacity", opacity[i]);
        }
        r.safari();
        tick = setTimeout(ticker, 1000 / sectorsCount);
    })();
    return function () {
        clearTimeout(tick);
        r.remove();
    };
}


texts:
I try to implement the encryption by Columnar transposition.

Input: key_secret and Text_to_encrypt, both of them are in lower.

Output: encrypted_text.

The code works fine but I have some questions:

it warns: "Function 'begin' could not be resolved", Function 'end' could not be resolved, Function 'copy_if' could not be resolved. How can I get rid of it?
it creates mapOriginAlphabet slowly. How can I improve it?

I use gcc 5.3.0

Here the code: .h file

#ifndef TRANSPOSITIONCIPHER_H_
#define TRANSPOSITIONCIPHER_H_

#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <set>

#define log(s) std::cout << s << std::endl

class transpositioncipher {
private:
    std::map<char,bool> mapOriginAlphabet;
    std::map<char,char> mapAlphabet;
    std::vector<int> vecOrder;
    std::string mKeySecret;

    std::string removeDuplicates(const std::string strOrigin);
    void createOrder();
    void createSubstitution();

public:
    transpositioncipher(std::string KeySecret);
    virtual ~transpositioncipher();

    std::string encrypt(const std::string strOrigin);
    std::string decrypt(const std::string strOrigin);
    void print();
};

#endif /* TRANSPOSITIONCIPHER_H_ */

.cpp file

#include "transpositioncipher.h"

transpositioncipher::transpositioncipher(std::string KeySecret) {

    mKeySecret = removeDuplicates(KeySecret);
    createOrder();
    for (int i = 97; i < 123; ++i) {
        char c = (char) i;
        std::size_t found = mKeySecret.find(c);
        if (found != std::string::npos) {
            mapOriginAlphabet[c] = false;
        } else {
            mapOriginAlphabet[c] = true;
        }
    }
     createSubstitution();
}

transpositioncipher::~transpositioncipher() {
}

std::string transpositioncipher::removeDuplicates(const std::string strOrigin) {

    std::set<char> moved;
    std::string result;
    result.reserve(strOrigin.size());

    //Only copy one character of each type to the new string
    std::copy_if(std::begin(strOrigin), std::end(strOrigin),
        std::back_inserter(result),
        [&moved](const auto& value) {return moved.insert(value).second;});

     return result;
}

void transpositioncipher::createOrder() {

    std::set<char> chars { mKeySecret.begin(), mKeySecret.end() };

    std::string strTemp = std::string(chars.begin(), chars.end());

    for (auto& x : strTemp) {
        std::size_t found = mKeySecret.find(x);

        vecOrder.push_back(found);
    }

}

void transpositioncipher::createSubstitution() {

    int iCols = mKeySecret.length();
    int iRows = 26 / iCols + 1;

    std::vector<std::vector<char>> vecTemp;

    std::vector<char> vecFirstRow;
    for (auto& x : mKeySecret) {
        vecFirstRow.push_back(x);
    }
    vecTemp.push_back(vecFirstRow);

    int index = 97;
    int iNumRow = 0;

    while (iNumRow < iRows) {
        std::vector<char> row;
        int iNumCol = 0;
        while (iNumCol < iCols) {
            if (mapOriginAlphabet[(char) index]) {
                row.push_back((char) index);
                iNumCol++;
            }
            index++;
            if (index > 123) {
                break;
            }
        }
        vecTemp.push_back(row);
        iNumRow++;
    }

    index = 97;
    for (auto& indexCol: vecOrder) {
        for (auto& vec: vecTemp) {
            if (indexCol >= vec.size())
                continue;
            else {
                mapAlphabet[(char)index] = vec.at(indexCol);
                index ++;
            }
        }
    }
}

std::string transpositioncipher::encrypt(const std::string strOrigin) {
    std::string ret;
    for (auto& x: strOrigin) {
        ret += mapAlphabet[x];
    }

    return ret;
}


texts:
I'm trying to figure out whether I should do the following:

This class (over-simplified version) retrieves  information about an order by having 1 main query function that select a specific column from the table and throws out the value for that column and that specific order ID.

class jobinfo
{

    protected $id;

    function __construct($job_id)
    {
        $this->id-$job_id;

    }

    protected function query_s($table, $col = '*', $where_col , $where, $return_col)
    {
        $SQL = mysql_query("SELECT $col FROM ".$table." WHERE $where_col='$where' LIMIT 1") or die(mysql_error());
        $data = mysql_fetch_array($SQL);
        return $data[$return_col];
    }

    public function qtyOrdered()
    {
        return $this->query_s('job_sheet','qty', 'job_id',$this->id, 1, 'qty');
    }

    public function dueDate()
    {
        return $this->query_s('job_sheet','due', 'job_id',$this->id, 1, 'due');
    }

}

The way I have it set up now is that I have this running in a while loop over 10,000 different orders like so:

$sql = mysql_query("SELECT job_id FROM job_sheet");
while($data = mysql_fetch_array($sql))
{
    $job_data = new jobinfo($data['job_id']);

    //table goes here to output values
    echo $job_data->dueDate();
    echo $job_data->qtyOrdered();
    ///
}

The one issue with this is that for every row that comes up, there are 2 queries that are happening in the back: one for the quantity and one for the due date. This ultimately causes to slow things down, especially when I'm outputting almost 11 columns for 11 different things. It adds up to a lot of queries per row.

My question is, should I go with something like this:

class jobinfo
{

    protected $id;
    protected $due;
    protected $qty;

    function __construct($job_id)
    {
        $this->id-$job_id;

        $this->retrieve();

    }

    protected function retrieve()
    {
        $sql = mysql_query("SELECT qty, due FROM job_sheet WHERE job_id=".$this->id." LIMIT 1");
        $data = mysql_fetch_array($sql);
        $this->due = $data['due'];
        $this->qty = $data['qty'];

        /// etc etc etc

    }

    public function qtyOrdered()
    {
        return $this->qty;
    }

    public function dueDate()
    {
        return $this->due;
    }
}

Which would do only one query per row in this case.

My dilemma is that the only time I find the second class more efficient is when some of this information is called via Ajax on a refresh rate of 5 seconds to be displayed somewhere. There are 15 users and most of the stay on one page that refreshes data every 5 seconds for statistical purposes.The other time is when the user searches for something in a custom search engine. The rest of the site is primarily showing only a few things and don't need to search the entire database to retrieve one specific value like the second class would have been doing. And so, this is the reason why I've set up my class as the first one: 'retrieve as you go' basically:

$job = new jobinfo(123); echo $job->qty();

I'm not sure what to do at this point and need some advice/suggestions.


texts: Security of the login code on the website

texts:
I wrote the code to log in php to the admin panel. Everything works as it should. But I am not sure if it is well written code and if it is safe. I care about security. I have read a lot about it but I am still not sure. Please, help me.
<form method="post">
   <input type="email" name="email" placeholder="Email">
   <input type="password" name="password" placeholder="Password">
   <button type="submit" name="submit">Submit</button>
</form>

LOGIN PAGE:
session_start();
session_regenerate_id();
if(isset($_POST['submit'])){
   unset($_POST['submit']);
      if(in_array('', $_POST)){
         //Errors for empty input
      } else {
         if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            if(Check if the user exists in the database){
               if(password_verify($_POST['password'], Password field in db)){
                  $_SESSION['loggedin'] = 1;
                  header('Location: welcome');
                  exit();
               } else {
                  //Wrong login credentials
               }
            } else {
               //Wrong login credentials
            }
         } else {
            //Wrong email
         }
      }
   }
}

PAGE AFTER LOGIN:
session_start();
session_regenerate_id();
if(empty($_SESSION['loggedin'])){
   header('Location: login');
   exit();
}


texts:
For following input string:

"VISITOR_INFO1_LIVE=USv90B-7CzI; LOGIN_INFO=e486e37a395be3f0e3b3237d090a6829c1oAAAB7IjQiOiAiREVMRUdBVEVEIiwgIjciOiAwLCAiMSI6IDEsICIzIjogMjAxMTk0MTMwNiwgIjgiOiA2MDgwMTg0NTEzNjQsICIxMCI6IDIzOTYyMTEyODczNH0=; PREF=f5=30;HSID=AHuJQBOVR0lQoRt_3; APISID=QaParXGsQcEPCzKg/A1smCfYrfMjxvfEPT; YSC=Vm3Amq5loFM";

I want to remove all the patterns that contains *SID (HSID,APISID here) upto ';'. I also want to remove substring "LOGIN_INFO= ....;"

So, output string should be:

"VISITOR_INFO1_LIVE=L80EDuHCEF8; PREF=f5=30";`

 const char *str ="VISITOR_INFO1_LIVE=USv90B-7CzI; LOGIN_INFO=e486e37a395be3f0e3b3237d090a6829c1oAAAB7IjQiOiAiREVMRUdBVEVEIiwgIjciOiAwLCAiMSI6IDEsICIzIjogMjAxMTk0MTMwNiwgIjgiOiA2MDgwMTg0NTEzNjQsICIxMCI6IDIzOTYyMTEyODczNH0=; PREF=f5=30;HSID=AHuJQBOVR0lQoRt_3; APISID=QaParXGsQcEPCzKg/A1smCfYrfMjxvfEPT; YSC=Vm3Amq5loFM";
 char *Cookie = NULL;
 cout << "original string is:\n" << str << "\n";
 int len = strlen(str)+1;
 cout << "length of original string is : " << len << "\n";
 Cookie = new char[strlen(str)];
 strncpy(Cookie,str,len);

 char *p1 = strstr(Cookie,"LOGIN_INFO");
 char *p2 = NULL;
 if(p1){
      p2 = strstr(p1,";")+1;
      while(*p2 == ' ') p2++;
 }
 if(p1 && p2)
      memmove(p1,p2,strlen(p2)+1);

 char *ID = strstr(Cookie,"SID");
 while( ID != NULL){
      char *start_pos = NULL, *end_pos = NULL;
      while((*ID != ';') && (*ID != Cookie[0]) && (*ID != ' ')){
           --ID;
      }
      if(*ID == Cookie[0]) start_pos = ID;
      else start_pos = ID+1;
      end_pos = strstr(start_pos,";")+1;
      while(*end_pos == ' ')
           end_pos++;
      memmove(start_pos,end_pos,strlen(end_pos)+1);
    //  }
      /*else
           std::cout << "does not find substr " << "\n";*/

    //  cout << "modified string is :" << Cookie << "\n";
      ID = strstr(Cookie,"SID");
 }
      //cout << "final modified string is : " << Cookie << "\n";
 char *Cookie_modified = NULL;
 const char *pch = strstr(Cookie,"PREF");
 if(pch != NULL){
      const char *append = "&f2=8000000";
      int len = strlen(Cookie) + strlen(append) + 1;
      Cookie_modified = new char[len];
      strncpy(Cookie_modified,Cookie,len);
      Cookie_modified[len-1] = '\0';
      char *p = strstr(Cookie_modified,"PREF");
      strncpy(p+(strlen(p)),append,strlen(append));
      cout << "modified Cookie is : " << Cookie_modified << "\n";
  //    cout << "length of modified cookie is : " << strlen(Cookie_modified) << "\n";
 }

 else{
      cout << "do not find reference: " << "\n";
      const char *append = ";PERF=f2=8000000";
      int len = strlen(Cookie) + strlen(append) + 1;
      Cookie_modified = new char[len];
      Cookie_modified[len-1] = '\0';
      strcat(Cookie_modified,Cookie);
      strcat(Cookie_modified,append);
      cout << "case 2: modified Cookie is: " << Cookie_modified << "\n";

 }
 delete[] Cookie;
 delete[] Cookie_modified;
 return 0;


texts:
I've been working on this task (see screenshot).

Here's my answer to it so far:

var sum_pairs=function(ints, s){
  //your code here

  var ptr_1 = 0,
      ptr_2 = 0,
      i = 0,
      j = 0,
      len = ints.length,
      j_min = len,
      arr_sum = [];

  for (i; i < len-1; i++){
    for (j = i+1; j < len; j++){
      if(ints[i] + ints[j] === s){
        if (j < j_min){
          j_min = j;
          arr_sum = [parseInt(ints[i]), parseInt(ints[j])]
        }
      }
    }
  }

return ( (arr_sum.length === 0)? undefined : arr_sum );

}

However, while the tests all pass, it throws an STDERR about 'optimising the code':

How might I be able to optimise my code further?


texts:
I've finally got all my code working as expected and it handles the data quickly.  But now I'm looking to refactor it because there is some duplicate sections that just looks like can be broken down for more efficiency and readability.  With out making this too long, here is the original:

I created functions createNumLabel and createPctLabel to basically do what is in the if statement.  So if codeID = 1,32,28,33,10 call createNumLabel else call createPctLabel.  While that doesn't crash the map no labels on the map are drawn.  Any ideas would be helpful.

    function labels(graphics) {
    globals.map.on("update-end", function () {

        var font = new esri.symbol.Font(10, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_BOLDER, "Arial");//create font object
        //var gl = globals.featureLayers[1].graphics;//low res
        var gl2 = globals.featureLayers[2].graphics;//high res

        console.log("Initial zoom level is :" + globals.map.getZoom());
        console.log("Scale is :" + globals.map.getScale());

        globals.map.graphics.clear();
        if(globals.map.getZoom() >=9)  {
            console.log(gl2.length);
            //globals.featureLayers[1].setVisibility(false);
            for (var i = 0; i < gl2.length; i++) {

                if (codeID == 1 || codeID == 32 || codeID == 28 || codeID == 33 || codeID == 10) {
                    //createNumLabel(graphics);
                    var g2 = globals.featureLayers[2].graphics[i];
                    var strLabel2 = g2.attributes.NAME + ":" + $.formatNumber(findFips(g2), { format: '#,###', locale: "us" });//creates string label formatted
                    var textSymbol2 = new esri.symbol.TextSymbol(strLabel2, font);

                    textSymbol2.setColor(new dojo.Color([0, 0, 0]));

                    var pt2 = g2.geometry.getExtent().getCenter();
                    var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2);
                    //add label to the map
                    globals.map.graphics.add(labelPointGraphic2);
                }//end if
                else {
                    //createPctLabel(graphics);
                    var g2 = globals.featureLayers[2].graphics[i];
                    var strLabelPct2 = g2.attributes.NAME + " : " + $.formatNumber(findFips(g2), { format: '#,###.0', locale: "us" }) + "%";
                    var textSymbol2 = new esri.symbol.TextSymbol(strLabelPct2, font);//create symbol with attribute name

                    textSymbol2.setColor(new dojo.Color([0, 0, 0]));//set the color

                    var pt2 = g2.geometry.getExtent().getCenter(); //get center of county
                    var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2); //create label graphic

                    //add label to the map
                    globals.map.graphics.add(labelPointGraphic2);

                }//end else
            }//end for
        }//ends if
    });//ends update end
}//ends labels function


texts: Shell command for the normal program termination of Skype from the command line

texts:
Would the following be the right way to do it in your opinion? Can you suggest a better alternative or, if not, is there something that can be done to make the existing version better?

ps -e | grep skype | cut -d" " -f1 | xargs kill -s term


texts: SQL Procedure to populate or create tables from views - performance issues

texts:
I have written the below to populate/create tables (t_) from all of the corresponding views (v_) in my database. I converted a previous script from using a cursor to improve running speed. Is there anything else I can do to make this more performant.

Any help is appreciated.

Please see code below.

USE [Database]
GO
/****** Object:  StoredProcedure [dbo].[P_populate_tables_from_views]    Script Date: 22/11/2016 16:15:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER   PROCEDURE [dbo].[P_populate_tables_from_views]

@dropTables BIT

AS

DECLARE @viewName NVARCHAR(100);
DECLARE @formattedTableName NVARCHAR(100);
DECLARE @dropTableSql NVARCHAR(MAX);

DECLARE @viewId int

SET @viewId = (SELECT MIN(object_id)
FROM sys.views)

WHILE @viewId IS NOT NULL
BEGIN

SET @viewName = (SELECT name FROM sys.views where object_id = @viewId)

PRINT 'Time: ' + CONVERT(varchar, SYSDATETIME(), 121)
PRINT('Processing ' + @viewName)
SET @formattedTableName = REPLACE(@viewName,'v_','t_');

IF @dropTables = 1
BEGIN
    SET @dropTableSql = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '''+@formattedTableName+''')) DROP TABLE '+@formattedTableName
    EXEC (@dropTableSql);
END

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @formattedTableName))
    BEGIN
        EXEC('TRUNCATE TABLE '+@formattedTableName)
        EXEC('INSERT INTO '+@formattedTableName +' SELECT * FROM '+ @viewName)
    END
    ELSE
    BEGIN
        EXEC ('SELECT * INTO '+@formattedTableName+' FROM '+@viewName);
    END
SET @viewId = (SELECT MIN(object_id)
FROM sys.views WHERE object_id > @viewId)
END


texts:
I would like help in optimizing this calculation, which is from the Lazy Hobo Riddle:

  There once were 4 hoboes travelling across the country.  During their
  journey, they ran short on funds, so they stopped at a farm to look
  for some work.  The farmer said there were 200 hours of work that
  could be done over the next several weeks.  The farmer went on to say
  that how they divided up the work was up to them.  The hoboes agreed
  to start the next day.

  The following morning, one of the hoboes - who was markedly smarter
  and lazier than the other 3 - said there was no reason for them all to
  do the same amount of work.  This hobo went on to suggest the
  following scheme:

  The hoboes would all draw straws.
  A straw would be marked with a number.
  The number would indicate both the number of days the drawer must work and the number of hours to be worked on each of those days.  For
  example, if the straw was marked with a 3, the hobo who drew it would
  work 3 hours a day for 3 days.

  It goes without saying that the lazy hobo convinced the others to
  agree to this scheme and that through sleight of hand, the lazy hobo
  drew the best straw.

  The riddle is to determine the possible ways to divide up the work
  according to the preceding scheme.

It basically just involves finding all possible solutions of \$a,b,c,d\$ such that \$a^{2} + b^{2} + c^{2} + d^{2} = 200 \$

for(int a = 1;a<=100; a++)
    for(int b = 1; b<=100; b++)
        for(int c = 1; c<=100; c++)
            for(int d = 1; d<=100; d++){
                ++counter;
                if(a*a + b*b + c*c + d*d == 200)
                    cout << "a: " << a << " b: " << b << " c: " << c << " d: " << d << endl;
            }