texts: Continually process results of multi-thread worker

texts:
Let's say we've got some SQL queries and want to display the results. Processing takes some time, so I do it multi-threaded.
The following works quite well for me. I reduced the code to the important parts and would be glad to get some comments on it:

Queries and results are stored in thread safe collections.

ConcurrentLinkedQueue<String> sqlQueries;
ConcurrentLinkedQueue<ResultSet> sqlResults;

In the GUI thread I start the worker threads which continuously get new queries from the sqlQueries, execute them, and put the results into sqlResults.

ExecutorService executorService = Executors.newFixedThreadPool(4);
for(int i=0; i<4; i++){
    executorService.execute(new QueryThread(sqlResults, sqlQueries));
}
executorService.shutdown(); //threads terminate after they finish

//Result processing
while ((!executorService.isTerminated() || !sqlResults.isEmpty())) {
    Thread.Sleep(100); //sleep for some time
    while(!sqlResults.isEmpty()) {
        //process available results
    }
}

Within the threads I do sth like:

do{
    currentSqlQuery = sqlQueries.poll();
    if(currentSqlQuery != null) {
        sqlResults.add(executeQuery(currentSqlQuery));
    }
} while (currentSqlQuery != null)


texts: Faking a pass method when building an array

texts:
Ruby doesn't have a pass method to 'do nothing' the way Python does - if I want a ternary statement to do something on true, but nothing on false (as in the code below). Is it bad practice in Ruby to fake it this way?

beverage_links = []

beverage_info.each do |bvg|
   self.is_menu_item?(bvg) ? beverage_links << bvg["href"] : "pass"
end


texts: Game combo press model (substring search)

texts:
I'm trying to make a model for checking combo presses in a game. Given a list of Button (enum) presses, it returns the list of possible combos completed. I tried using a suffix tree, but I'm not sure if this is the best solution. It's also my first time writing a suffix tree, and I don't know if this is the correct usage.

Also, could someone help me analyze the runtime of registering combos and searching combos? I think registering combos is O(n), but what about searching for combos?

Button enum:

public enum Button {
        Left, Right, Down, Up, A, B, X, Y;
}

Registering combos and for searching for the completed combos:

public class SuffixTree {
    private class SuffixTreeNode {
        Map<Button, SuffixTreeNode> children = new HashMap<Button, SuffixTreeNode>();
        List<Button> indices = new ArrayList<Button>();

        public void insert(List<Button> lob) {
            if (lob != null && lob.size() > 0) {
                indices.add(lob.get(0));
                Button value = lob.get(0);
                SuffixTreeNode child = null;
                if (children.containsKey(value)) {
                    child = children.get(value);
                } else {
                    child = new SuffixTreeNode();
                    children.put(value, child);
                }
                List<Button> remainder = lob.subList(1, lob.size());
                child.insert(remainder);
            }
        }

        public List<Button> search(List<Button> lob, List<Button> parents) {
            if (lob == null || lob.isEmpty()) {
                return parents;
            } else {
                Button first = lob.get(0);
                if (children.containsKey(first)) {
                    parents.add(first);
                    List<Button> remainder = lob.subList(1, lob.size());
                    return children.get(first).search(remainder, parents);
                }
            }
            return null;
        }
    }

    SuffixTreeNode root = new SuffixTreeNode();

    public void registerCombos(List<List<Button>> combos) {
        for (List<Button> combo : combos) {
            root.insert(combo);
        }
    }

    public List<List<Button>> search(List<Button> buttonPresses) {
        List<List<Button>> res = new ArrayList<List<Button>>();
        int len = buttonPresses.size();
        for (int i = 0; i < len; i++) {
            List<Button> partial = root.search(buttonPresses.subList(i, len), new ArrayList<Button>());
            if (partial != null && !partial.isEmpty()) {
                res.add(partial);
            }
        }
        return res;
    }
}


texts: Number of sub strings with same first and last character

texts:
Problem Statement:

  You are given a function \$f(x)\$, where \$f(x)\$ is \$1\$ if the first and last characters of string \$x\$ are equal; else it is \$0\$.
  You are given a string \$S\$ and you have to find the sum of \$f(x)\$ for all substrings \$x\$ of given string \$S\$.

Sample Input:

7
ababaca

Sample Output:

14

Explanation:

f("a")=1, f("aba")=1, f("abaca")=1 but f("ab")=0, f("bac")=0. Hence counting all substrings we get 14.

The 14 substring are

a - 4(times)
b - 2
c - 1
aba - 2
bab - 1
aca - 1
ababa - 1
abaca - 1
ababaca - 1

My code:

l = int(input())
s = [x for x in input().strip()]
print(l + sum([1 for i in range(0,l-1) for j in range(i+1,l) if s[i] == s[j]]))

I have tried the following snippets too:

Timeout:

from collections import Counter
import math
l, s = int(input()), [x for x in input()]
print(l + sum([math.factorial(value-1) for value in Counter(s).values() if value != 1]))

Wrong answer:

import itertools
l, s = int(input()), input()
print(sum(int(i[0] == i[-1]) for i in itertools.combinations_with_replacement(s,2)))

The solutions is working fine except that it times out in certain test cases. Can anyone suggest a better way to do this?


texts:
My concern with this code is the excessive use of .encode('utf-8').  Any advice on refining these functions would be very helpful.

rss2html GitHub repo

#!/usr/bin/env python

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

from feedparser import parse as parsefeed
import StringIO

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """

{title}

    {title}
    {description}
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >>out, entry2html(title=title, link=link,
                                description=description)
    return out.getvalue()

print convert_feed(url='http://stackoverflow.com/feeds')


texts: From scratch pub sub definition and implementation

texts:
I am finished with my implementation of PUB/SUB or Observer pattern, however I just want to see any ways that I may be able to improve this pattern. I wanted to be able to use the typical PubSub pattern except add performance enhancements by using the new key word to instantiate each new instance of a PubSub object, as well as make sure that the initialize fn as well as all of the public methods are chain-able.

Here is my PubSub definition:

(function(global) {
'use strict';

var newPubSub;
global.PubSub = {
    core: function core() {},
    init: function(moduleNs) {
        if (!global[moduleNs]) global[moduleNs] = new PubSub.core();
        else throw new Error('A module has already been initialized under this namespace');
        newPubSub = global[moduleNs];
        return newPubSub;
    }
};

var instance = PubSub.core.prototype;

/**
 * Will check for the existance of prev array under this ns and if none exists it will create
 * a new prop with the ns and the function as the sole member of the array. If an array already
 * exists under this namespace then the function is simply pushed into that namespaces array of
 * methods that it will be triggered when that ns becomes published.
 **/
instance.sub = function(ns, fn) {
    if (!newPubSub[ns]) {
        newPubSub[ns] = [fn];
    }
    else if (Array.isArray(newPubSub[ns]) && newPubSub[ns].length > 0) {
        newPubSub[ns].forEach(function(savedFn) {
            if (fn === savedFn) throw new TypeError('This function already exists under this namespace, please provide a new method for this namespace or add a new namespace to hold this method/fn');
            else {
                newPubSub[ns].push(fn);
            }
        });
    }
    return this;
};

/**
 * Will remove all methods for a listener and the listener ns is not provided,
 * or will remove a single method from a listener if the ns provided has a matching method/fn
 **/
instance.unsub = function(ns, fn) {
    function revokeAllMethods(ns) {
            if (newPubSub[ns]) {
                delete newPubSub[ns];
            }
    }
    // loops through all the methods in a namespace provided and compares to see if the method provided exists, if it does it will be removed
    function revokeSpecificMethod(ns, fn) {
        newPubSub[ns].forEach(function(savedMethod, idx) {
            // Remove the method that matches the one provided to unsubscribe
            if (fn === savedMethod) newPubSub[ns].splice(idx, 1);
            // Otherwise an error will be thrown
            else throw new Error('No method match found under the namespace '+ns);
        });
    }
    if (typeof ns === 'string') {
        if (!fn) {
            revokeAllMethods(ns);
        }
        else if (typeof fn === 'function') {
            revokeSpecificMethod(ns, fn);
        }
    }
  return this;
};

/**
 * Will trigger an event with provided params on any methods under the ns triggered
 */
instance.pub = function(ns, params) {
    if (!newPubSub[ns]) throw new TypeError('No method found under the namespace "' + ns + '" inside of Object. It has either been unsubscribed or never existed.');

    newPubSub[ns].forEach(function(fn) {
        fn.apply(null, params);
    });
    return this;
};

})(window);

Implementation:

PubSub.init('test');

test.sub('alert', function(msg){
    alert(msg);
}).pub('alert',['bob']).sub('somethingelse', function(){
    alert('look ma no params');
}).pub('somethingelse').pub('alert',['bob']).unsub('alert').pub('alert',[12]);


texts:
I am relatively new to classes. This one uses one.
I am pretty sure this is not the correct way to do this. But I also do not know the correct way.
You can use the certified_secure function when you make an instance of crawler that has the URL of hackthissite.org.
Do I have to many comments? Are they too verbose?
#! usr/bin/env python

import bs4
import requests

users = ['user1', 'user2']
certified_secure_url = 'https://www.certifiedsecure.com/profile?alias='
hack_this_site_url = 'https://www.hackthissite.org/user/view/'

# this function takes a string as input and outputs a list with all the integers in the string
def get_num(string):

    # get the numbers from string
    lst = ''.join([x if x.isdigit() else ' ' for x in string]).split()

    # change to list of ints instead of strings
    new_lst = []
    for item in lst:
        new_lst.append(int(item))

    return new_lst

class Crawler(object):
    def __init__(self, url):
        self.url = url

    # retrieve data from site and
    def get_site_data(self, user):
        request = requests.get(self.url + user)
        return bs4.BeautifulSoup(request.text, 'lxml')

    def certified_secure(self, user):
        experience = self.get_site_data(user).select('.level_progress_details')[0].getText()
        # get the points from the string
        return get_num(experience)[1]

    def hack_this_site(self, user):
        experience = self.get_site_data(user).select('.blight-td')[1].getText()
        return get_num(experience)[0]

# make to instances to crawl
cs = Crawler(certified_secure_url)
hts = Crawler(hack_this_site_url)

for user in users:
    print cs.certified_secure(user)
    print hts.hack_this_site(user)


texts: Music management app, mashing data from various APIs

texts:
I am basically getting data from various APIs and using PHP to put them together - like a web mashup. I am currently using 4 foreach statements to insert the gathered data into their individual arrays. I believe that the current code is inefficient because it takes probably around 3 seconds to load the page which is displaying the PHP data. In the past I had just one big foreach loop to go through all the data at once and also print them. But that too felt inefficient to me.

So how can I make my code more efficient in term of it processing faster? I have seen a few mashup websites such as Soundeer which load around a second. Is that becuase of their code efficiency?

The code which I am using is:

$echonest_uri = simplexml_load_file("http://developer.echonest.com/api/v4/artist/search?api_key=$APIkey&style=rap&results=10&start=$element_num&bucket=id:deezer&bucket=images&sort=familiarity-desc&format=xml");

//Swap the comments for when in UWE or not
//$echonest_xml =  new SimpleXMLElement($echonest_uri);
$echonest_xml = $echonest_uri;

$artist_name = array();
$artist_image = array();
$echonest_id = array();
$full_deezer_id = array();
$deezer_id = array();
$num_of_albums = array();

//Loop through each entries in the id_arr and make each image of the artist a link to the album page passing all the relevant information.
foreach($echonest_xml->artists->artist as $artist){
    $artist_name[] = $artist->name;
    $artist_image[] = $artist->images->image[0]->url;
    $echonest_id[] = $artist->id;
    $full_deezer_id[] = $artist->foreign_ids->foreign_id->foreign_id;
}

foreach($full_deezer_id as $key => $value){
    preg_match('#deezer:artist:([A-Z,a-z,0-9]+)#', $value, $id);
    $deezer_id[] = (string)$id[1];
}

foreach($deezer_id as $id_index => $id){
    $deezer_xml = simplexml_load_file("http://api.deezer.com/2.0/artist/$id/albums&output=xml");
    $num_of_albums[] = $deezer_xml->total;
}

//The variable which will contain the HTML code to display the artists.
$output = null;

foreach($deezer_id as $key => $value){

    $fav_count_query = "SELECT COUNT(user_index) FROM fav_artist WHERE artist_deezer_id = '$value'";
    $fav_count_resource = $mysqli->query($fav_count_query);
    $fav_count = $fav_count_resource->fetch_assoc();

    $output .=  <<<HERE

                        {$artist_name[$key]}

                    Albums:
                        {$num_of_albums[$key]}

HERE;

}


texts:
I use this Bash script to rename specified files to all lowercase letters:

#!/bin/bash

usage() {
    test $# = 0 || echo "$@"
    echo "Usage: $0 [OPTION]... FILE..."
    echo
    echo "Rename files to all lowercase letters."
    echo
    echo "  -n, --dry-run         Dry run, show what would happen"
    echo
    echo "  -h, --help            Print this help"
    echo
    exit 1
}

args=
dryrun=off
while [ $# != 0 ]; do
    case $1 in
    -h|--help) usage ;;
    -n|--dry-run) dryrun=on ;;
    --) shift; while [ $# != 0 ]; do args="$args \"$1\""; shift; done; break ;;
    -?*) usage "Unknown option: $1" ;;
    *) args="$args \"$1\"" ;;
    esac
    shift
done

eval "set -- $args"

test $# -gt 0 || usage

for path; do
    test -e "$path" || continue
    origfile=$(basename "$path")
    newfile=$(tr '[:upper:]' '[:lower:]' <<< "$origfile")
    origdir=$(dirname "$path")
    origpath=$origdir/$origfile
    newpath=$origdir/$newfile
    test "$origpath" != "$newpath" || continue
    echo "$path -> $newpath"
    test $dryrun = on || mv -i -- "$path" "$newpath"
done

Is there a better way I missed? Anything to improve?

(This script, along with many other utility scripts I use are on GitHub.)


texts:
I want to access some of the methods from outside of the plugins scope, namely showPopup(), hidePopup() and updateColor(newcolor).

Initialization

What I want to do

Something like

cp.updateColor('red');

or

$(".cp").ColorPickerSliders('updateColor', 'red');

Which one is the preferred way, and how to refactor the code to accomplish it?

I achieved it using triggers, but don't know if it has any downsides or is a good way to do these kind of interaction. So I registered a custom event handler inside the plugin's code (Line 320, triggerelement is the original element the plugin is called on):

triggerelement.on('jquerycolorpickersliders.updateColor', function(e, newcolor) {
    updateColor(newcolor);
});

And call it using this code (where cp is the element the plugin is called on):

cp.trigger('jquerycolorpickersliders.updateColor', 'red');

jsFiddle.

What do you think of it? Is it an acceptable solution for the problem, or is there a better one?


texts: Build an entity, based on a defined model by comparing table column to entity names and building

texts:
Can I optimize the BuildEntity method more?

protected IEnumerable<GroupTitle> BuildProductGroup()
    {
        var productGroups = new List<GroupTitle>();
        using (var connection = new SqlConnection(_dbConnection))
        using (var command = new SqlCommand(_getProductGroups, connection))
        {
            connection.Open();
            command.CommandType = CommandType.StoredProcedure;
            using (var reader = command.ExecuteReader())
                while(reader.Read())
                {
                    var productGroup = new GroupTitle();
                    BuildEntity<GroupTitle>(reader, ref productGroup);
                    productGroups.Add(productGroup);
                }
        }

        return productGroups;
    }

    protected TEntity BuildEntity<TEntity>(IDataReader reader, TEntity model)
    {
        var type = model.GetType();
        var table = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();

        foreach (var column in table)
        {
            var matchColumnToProperty = type.GetProperties().FirstOrDefault(property => String.Compare(property.Name, column, true) == 0);
            if (matchColumnToProperty != null && !reader.IsDBNull(reader.GetOrdinal(matchColumnToProperty.Name)))
                matchColumnToProperty.SetValue(model, reader.GetValue(reader.GetOrdinal(matchColumnToProperty.Name)), null);
        }

        return model;
    }


texts:
I was writing a basic calculator program to practice my skills at python.
I'm a beginner at Python and was wondering if there is a way to simplify this code of mine? It seems a little bit too long and messy in some sort of way.
Again, I'm still a beginner so I don't know all the tricks in the book!

import math
import time

def add(x,y):
  return x + y

def subtract(x,y):
  return x - y

def divide(x,y):
  return x / y

def multiply(x,y):
  return x * y

def sqrt(x):
  if math.sqrt(x) * math.sqrt(x):
     return False
  else:
     return math.sqrt(x)

def power(x,y):
  return math.pow(x,y)

def repeat():
  print('Would you like to perform another calculation? y/n')
  rep = input('')
  if rep.lower() == 'y':
     time.sleep(0.5)
     main()
  elif rep.lower() == 'n':
     print('Goodbye!')
     time.sleep(1)
     exit()
  else:
     print('Please enter y/n.')
     time.sleep(1)
     repeat()

def numCheck(x):
  try:
     int(x)
  except ValueError:
     print("Please enter a valid number.")
     print('')
     time.sleep(1)
     main()

def choiceCheck(y, z):
   for x in y:
       if x == z:
           return True
           break
       else:
           pass

def main():
  choices = ['1', '2', '3', '4']
  print('Choose your operation: ')
  print('1. Add')
  print('2. Subtract')
  print('3. Divide')
  print('4. Multiply')
  print('5. Square Root')
  print('6. Exponent')
  print('1/2/3/4/5/6')
  choice = input('')
  if choice == '5':
     print('Please choose the number you would like to square root.')
     rt = input('')
     numCheck(rt)
     rt = int(rt)
     rts = sqrt(rt)
     if rts == False:
        print('%d is an irrational number.' % (rt))
     else:
        print('The square root of %d is %d' % (rt, rts))
        repeat()
  elif choice == '6':
     print('Choose the number you would like to raise to a power: ')
     base = input('')
     numCheck(base)
     base = int(base)
     print('')
     print('Now please choose the indice: ')
     ind = input('')
     numCheck(ind)
     ind = int(ind)
     time.sleep(1)
     print('%d to the power of %d is %d' % (base, ind, power(base,ind)))
     repeat()
  elif choiceCheck(choices, choice) != True:
     print('Please choose a valid number.')
     print('')
     time.sleep(1)
     main()
  a = input('Please choose your first number: ')
  numCheck(a)
  a = int(a)
  print('')
  b = input('Please choose your second number: ')
  numCheck(b)
  b = int(b)
  if choice == '1':
     print('%d + %d = %d' % (a, b, add(a,b)))
  elif choice == '2':
     print('%d - %d = %d' % (a, b, subtract(a,b)))
  elif choice == '3':
     print('%r / %r = %r' % (a, b, divide(a,b)))
  elif choice == '4':
     print('%d * %d = %d' % (a, b, multiply(a,b)))
  else:
     print('Please choose a valid number')
     print('')
     time.sleep(1)
     main()
  repeat()

main()

All help is appreciated!


texts:
I'm formatting price string with the following method:

   def price_formatter(price)
     return if price.nil?
     formatted = '$'
     if price.length > 8 || price.length == 6
       price_separated = price.scan(/.{3}|.+/).join(',')
     elsif price.length == 8
       price_separated = price.insert(2, ',').insert(6, ',')
     elsif price.length == 7
       price_separated = price.insert(1, ',').insert(5, ',')
     elsif price.length == 5
       price_separated = price.insert(2, ',')
     elsif price.length == 4
       price_separated = price.insert(1, ',')
     else
       price_separated = price
     end
     formatted << price_separated
  end

Specs:

  it { expect(@listing.price_formatter('300000000')).to eq '$300,000,000' }
  it { expect(@listing.price_formatter('30000000')).to eq '$30,000,000' }
  it { expect(@listing.price_formatter('3000000')).to eq '$3,000,000' }
  it { expect(@listing.price_formatter('300000')).to eq '$300,000' }
  it { expect(@listing.price_formatter('30000')).to eq '$30,000' }
  it { expect(@listing.price_formatter('3000')).to eq '$3,000' }
  it { expect(@listing.price_formatter('300')).to eq '$300' }
  it { expect(@listing.price_formatter(nil)).to eq nil }

specs are passing, but I hate the long if statement and using a case is not accomplishing much either. What would be a good way to refactor the price_formatter method?


texts:
This function checks an array for duplicated values. If it finds a duplicate value, it increments the variable name repeatedTime and then if repeatedTime is greater than 1 it calls a randomize function which produce different values in the array that was passed to the function. It repeats these steps until a duplicated value free array is produced and then notDuplicate becomes true and the function ends.

Are there any improvements that can be made to the function? I am thinking about making it into a recursive function. Is that feasible?

private void CheckForDuplicates(int[] selectedWordIds, List<Integer> answersTempId) {
    boolean notDuplicate = false;

    while(notDuplicate != true){
        int repeatedTime = 0;
        for(int x = 0; x < selectedWordIds.length ; x++)
        {
            for(int y =0; x < selectedWordIds.length;x++)
            {
                if(selectedWordIds[x] == selectedWordIds[y])
                {
                    repeatedTime++;
                }
            }
        }
      if(repeatedTime > 1)
      {
          notDuplicate = false;
          RandomizeFunction(selectedWordIds, answersTempId);
      }
      else{
          notDuplicate    = true;
      }
    }
}


texts: Comparing phone numbers across CSVs Python

texts:
(continuation from Speeding up and fixing phone numbers from CSVs with Regex)

I'm pulling all of the phone numbers from all CSVs in two different directories, outputting them in a single simple format to two different files, and then comparing those two files for which numbers are in one but not the other.

I'm failing in speed (of execution), style, and results.  Here's what I was trying:

import csv
import re
import glob
import string

with open('Firstlist.csv', 'wb') as out:
    with open('Secondlist.csv', 'wb') as out2:
        with open('SecondnotinFirst.csv', 'wb') as out3:
            with open('FirstnotinSecond.csv', 'wb') as out4:
                seen = set()
                regex = re.compile(r'(\+?[2-9]\d{2}\)?[ -]?\d{3}[ -]?\d{4})')
                out_writer = csv.writer(out)
                out_writer.writerow([])
                csv_files = glob.glob('First\*.csv')
                for filename in csv_files:
                    with open(filename, 'rbU') as ifile:
                        read = csv.reader(ifile)
                        for row in read:
                            for column in row:
                                s1 = column.strip()
                                match = regex.search(s1)
                                if match:
                                    canonical_phone = re.sub(r'\D', '', match.group(0))
                                    if canonical_phone not in seen:
                                        seen.add(canonical_phone)
                for val in seen:
                    out_writer.writerow([val])

                seen2 = set()
                out_writer2 = csv.writer(out2)
                out_writer2.writerow([])
                csv_files2 = glob.glob('Second\*.csv')
                for filename in csv_files2:
                    with open(filename, 'rbU') as ifile2:
                        read2 = csv.reader(ifile2)
                        for row in read2:
                            for column in row:
                                s2 = column.strip()
                                match2 = regex.search(s2)
                                if match2:
                                    canonical_phone2 = re.sub(r'\D', '', match2.group(0))
                                    if canonical_phone2 not in seen2:
                                        seen2.add(canonical_phone2)

                for val in seen2:
                    out_writer2.writerow([val])

                out_writer3 = csv.writer(out3)
                for val in seen2 not in seen:
                    out_writer3.writerow([val])

                out_writer4 = csv.writer(out4)
                for val in seen not in seen2:
                    out_writer4.writerow([val])


texts: Fast API path parameters from Enum Class

texts:
from enum import Enum
from fastapi import FastAPI
app = FastAPI()

Hi Defined a route and a Enum Class for the same but the Enum Class looks ugly.
class Subjects(str, Enum):
    path1="AcceptedEventRelation"
    path2="Account"
    path3="AccountChangeEvent"
    path4="AccountCleanInfo"
    path5="AccountContactRole"
    ...
    ...
    path100

@app.get("/subjects/{sobjectname:str}")
async def process_subjects(sobjectname:Subjects):
    endpoint_subjects = "/services/data/v49.0/sobjects"
    url_to_request = endpoint_subjects + "/" + sobjectname
    return {
        "subject" : sobjectname,
        "url_to_request": url_to_request
        }

Is there a better way to implement the Subjects Class. Thanks


texts: Is there anything to improve in this MergeSort code in Java?

texts:
I have written an implementation of the merge sort algorithm in Java.

Here is the MergeSort class that I created.

public class MergeSort{

    public static void sort(Comparable[] a){
        Comparable[] b = new Comparable[a.length];
        sort(a, b, 0, a.length-1);
    }

    private static void sort(Comparable[] a, Comparable[] b, int lo, int hi){
        if(lo>=hi) return;
        int mid = lo+(hi-lo)/2;
        sort(a, b, lo, mid);
        sort(a, b, mid+1, hi);
        merge(a, b, lo, hi, mid);
    }

    private static void merge(Comparable[] a, Comparable[] b, int lo, int hi, int mid){
        int i=lo;
        int j=mid+1;

        for(int k=lo;k<=hi;k++){
            if(i<=mid && j<=hi){
                if(a[i].compareTo(a[j])>0) {b[k]=a[j++];continue;}
                else if(a[i].compareTo(a[j])<0) {b[k]=a[i++]; continue;}
                else {
                    b[k]=a[i++];
                    j++;
                    continue;
                }
            }
            if(j>hi && i<=mid) {b[k]=a[i++];continue;}
            if(i>mid && j<=hi) {b[k]=a[j++];continue;}
        }

        for(int n=lo;n<=hi;n++){
            a[n]=b[n];
        }
    }
}

The code passed some simple tests. I wonder is there anything wrong or missing out? Anywhere to improve?


texts:
Since I'm venturing more and more into the multithreading, I now need to think about how to protect my precious OdbcConnection from breaking at random times.

The project specifications:

.NET-2.0
ODBC-Connection via MySQL-Connector 3.51 to MySQL 5.0

The main structure of my project in question looks like this:

+ Assembly
+--+> Namespace1
   +--> Data-Layer
+--+> Namespace2
   +--> Data-Layer
...

There's also an abstraction layer in place with interfaces and implementations, but I think that doesn't matter, because my question is about the ODBC implementation. They do also implement IDisposable.

This means I'm passing around an OdbcConnection to different classes and create these Data classes if asked to, like this:

public class MainDataSource
{
    private OdbcConnection _conn = <Yes, It's initialized>;

    public Namespace1.Data CreateNamespace1Data()
    {
        return new Namespace1.Data(_conn);
    }

    public Namespace2.Data CreateNamespace2Data()
    {
        return new Namespace2.Data(_conn);
    }
}

The Data classes itself are containing methods to fetch objects from the database. The only interesting thing here is that every Data class is holding its very own OdbcCommand objects, none of these are shared in any way. The only thing they have in common is the source OdbcConnection.

Since some of these classes (like the Setting class) might be called from multiple threads at the same time, I need to think about the best way to lock and protect these. My first idea was to lock the whole OdbcConnection:

public class Data
{
    private OdbcConnection _conn;
    private OdbcCommand _cmd;

    public Data(OdbcConnection conn)
    {
        _conn = conn;

        _cmd = _conn.CreateCommand();
        _cmd.CommandText = <FromResource>;
        _cmd.Parametersblabla;
    }

    public MyDataObject GetObjects(String searchterm)
    {
        lock(_conn)
        {
            _cmd.Parameters[0].Value = searchterm;
            using(OdbcDataReader reader = _cmd.ExecuteReader())
            {
                // Do stuff here and return MyDataObject
            }
        }
    }
}

This seems a little bit too strict to me, so I also thought about only locking the OdbcCommand:

public class Data
{
    private OdbcCommand _cmd;

    public Data(OdbcConnection conn)
    {
        _cmd = conn.CreateCommand();
        _cmd.CommandText = <FromResource>;
        _cmd.Parametersblabla;
    }

    public MyDataObject GetObjects(String searchterm)
    {
        lock(_cmd)
        {
            _cmd.Parameters[0].Value = searchterm;
            using(OdbcDataReader reader = _cmd.ExecuteReader())
            {
                // Do stuff here and return MyDataObject
            }
        }
    }
}

But I still feel like I've missed something very important here. Do I have other options? Did I miss something important?


texts:
I wrote a program that prompts users to enter one string per line and stores it into an array. It also checks for duplicate entries as data are fed and renames those to become distinct by appending an incrementing number. Imagine that it will be used by a large number of people in some name registration event. I am concerned about how slow it will run because of all the comparisons as more and more strings are put.

About the code below, the first line scans how many times inputs will be scanned. I have yet to finish the input validation part as I noticed the above performance issue halfway through writing it.

How can I reduce the number of comparisons and make the program run faster?

import java.util.*;

public class Temp {
    public static void main (String[] args){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        String[] names = new String[n];
        int namesPoint = 0;
        for(int i=0;i<n;i++) {
            String name = scanner.next();
            int k=0;
            boolean dupe = false;
            for(int j=0;j<namesPoint;j++) {
                if(names[j].equals(name)) {
                    dupe=true;
                    break;
                }
            }
            if(dupe) {
                String newname="";
                while(dupe){
                    dupe=false;
                    k++;
                    StringBuilder sb = new StringBuilder();
                    sb.append(name);
                    sb.append(k);
                    newname = sb.toString();
                    for(int j=0;j<namesPoint;j++) {
                        if(names[j].equals(newname)) {
                            dupe=true;
                            break;
                        }
                    }
                }
                System.out.printf("%s\n",newname);
                names[namesPoint]=newname;
                namesPoint++;
                k=0;
            }else {
                names[namesPoint]=name;
                namesPoint++;
                System.out.printf("OK\n");
            }
        }
        scanner.close();
    }
}


texts: Optimize calculation of string self-similarly with its suffixes

texts:
I am trying to solve a Hacker Rank problem about string suffixes:

  For two strings A and B, we define the similarity of the strings to be
  the length of the longest prefix common to both strings. For example,
  the similarity of strings "abc" and "abd" is 2, while the similarity
  of strings "aaa" and "aaab" is 3.

  Calculate the sum of similarities of a string S with each of its
  suffixes.

I have the following code:

import System.IO
import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BSC

main = do
    n <- liftM getIntFromBS BSC.getLine
    replicateM_ n $ do
        s <- BSC.getLine
        putStrLn . show $ sum $ map (cntPrefix s) $ tail $ sort $ BSC.tails s
    where
        getIntFromBS = fst.fromJust.BSC.readInt
        cntPrefix str pref = length $ takeWhile (\t -> fst t == snd t) $ BSC.zip pref str

But performance is really bad. I am doing this challenges to learn Haskell and thus my skills aren't good enough to optimize this program. Any help is appreciated.


texts: File upload in AngularJS causes browser out of memory error

texts:
I have an AngularJS code to perform upload of files. At first I thought it works OK but when I've tried to upload bigger files (e.g. 5 files, 10 MB each) then I saw that this code has very poor performance regarding memory handling.

For example: when I attach 5 files (10 MB each = 50 MB in total) then peak browser process memory demand reaches 2 GB!
I've tested it in Firefox, Chrome and IE. Additionally, in Chrome when browser process reaches 3 GB of memory committed then the page crashes.
In Firefox I can see an error in console when trying to upload more than 80 MB at once:
out of memory

I've tried to modify the parts where the actual request is made and removed data: JSON.stringify(formattedData) which was the first bottleneck. And it turned out that stringifying is redundant there.

But the second bottleneck still exists which is the function binArrayToJson which takes the ArrayBuffer and reads the data into the byte array.

var binArrayToJson = function (binArray) {
   var str = [binArray.length];
   for (var i = 0, binLength = binArray.length; i < binLength; i++) {
   str[i] = binArray[i];
   }
   return str;
}

var applyAttachments = function (data1) {
   angular.forEach(data1,
       function (value, key) {
           if (key === "Attachments") {
               for (var i = 0; i < value.length; i++) {
                   if (value[i].file) { //already saved item don't contain 'file' property
                       var reader = new FileReader();

                       reader.onloadend = (function (f) {
                           return function (result) {

                               var arrayBuffer = result.target.result;
                               value[f].fileContent = binArrayToJson(new Uint8Array(arrayBuffer));
                               value[f].isUploaded = true;
                           };
                       })(i);

                       reader.readAsArrayBuffer(value[i].file);
                   }
               }
           }
       });
};

var createMVCModel = function (output) {
   var defaultStringValue = "";
   return {
       id: output.id,
       Name: output.name || defaultStringValue,
       Status: output.status || "Draft",
       Date: output.date || null
       Attachments: output.attachments || []
   };
};

var saveModel = function (data, url) {
   var formattedData = createMVCModel(data);
   var deferred = $q.defer();

   applyAttachments(formattedData);

   var check = function () {
       if (allNewFilesUploaded(formattedData) === true) {
           $http({
                   url: url,
                   method: "POST",
                   data: formattedData,
                   headers: { 'Content-Type': undefined }
               })
               .then(function (result) {
                       deferred.resolve(result);
                   },
                   function (result) {
                       deferred.reject(result);
                   });
       } else {
           setTimeout(check, 1000);
       }

   }
   check();
   return deferred.promise;
};

I omitted the parts where the following requirements are being met:

checking number of files (limit is 10)
checking size of each file (limit is 10 MB each)
checking permitted file extensions
sending rest of the (text) data along with files to the server (ASP.NET MVC method)


texts:
This method finds all permutations of a string and stores them in a sorted array. It then returns the element in the middle of the array.

def middle_permutation(string)
  sorted = string.chars.to_a.permutation.map(&:join).sort
  sorted[sorted.length / 2 - 1]
end

For strings over 10+ characters this code is too slow. How can I speed it up?

Here are my tests. They pass, but I'd like it to be more efficient:

describe "Basic tests" do
  Test.assert_equals(middle_permutation("abc"),"bac")
  Test.assert_equals(middle_permutation("abcd"),"bdca")
  Test.assert_equals(middle_permutation("abcdx"),"cbxda")
  Test.assert_equals(middle_permutation("abcdxg"),"cxgdba")
  Test.assert_equals(middle_permutation("abcdxgz"),"dczxgba")
end


texts:
Given a list of time intervals, I want to return the intervals with the most overlaps (i.e. most people free). My solution runs in \$O(n \log n)\$, but I made a bunch of "tracker" variables. How can I avoid creating all these variables?

Interval class:

public class Interval {
    int start;
    int finish;

    public Interval(int start, int finish) {
        this.start = start;
        this.finish = finish;
    }
}

Point class (used in my algorithm):

public class Point implements Comparable<Point> {
    int time;
    TimeType type;

    public Point(int time, TimeType type) {
        this.time = time;
        this.type = type;
    }

    public int compareTo(Point p) {
        if (time == p.time) {
            if (!type.equals(p.type)) {
                if (type == TimeType.Finish) {
                    return -1;
                }
                return 1;
            }
            return 0;
        }
        return time - p.time;
    }
}

TimeType enum:

public enum TimeType {
    Start, Finish
}

The method that returns overlapping intervals:

public List<Interval> getOverlappingIntervals(List<Interval> intervals) {
        List<Point> sortedTimes = new ArrayList<Point>();
        Map<Point, Interval> map = new HashMap<Point, Interval>();
        Map<Point, Point> pointMap = new HashMap<Point, Point>();
        List<Interval> res = new ArrayList<Interval>();
        List<Point> currPartial = new LinkedList<Point>();
        List<Point> bestPartial = new LinkedList<Point>();
        int overallBest = 0;
        int currBest = 0;

        for (Interval i : intervals) {
            Point startPoint = new Point(i.start, TimeType.Start);
            Point endPoint = new Point(i.finish, TimeType.Finish);
            sortedTimes.add(startPoint);
            sortedTimes.add(endPoint);
            map.put(startPoint, i);
            pointMap.put(endPoint, startPoint);
        }

        Collections.sort(sortedTimes);

        for (int i = 0; i < sortedTimes.size(); i++) {
            Point curr = sortedTimes.get(i);
            if (curr.type.equals(TimeType.Start)) {
                currBest++;
                currPartial.add(sortedTimes.get(i));
            } else {
                currBest--;
                if (currBest == 0) {
                    currPartial.clear();
                } else {
                    currPartial.remove(pointMap.get(sortedTimes.get(i)));
                }
            }
            if (currBest > overallBest) {
                overallBest = currBest;
                bestPartial = new LinkedList<Point>(currPartial);
            }
        }

        for (Point p : bestPartial) {
            res.add(map.get(p));
        }

        return res;
    }


texts:
Am I commenting enough? Are my variables properly following correct styling format? Is there a more efficient way to code my "Label coloring" conditions?

from tkinter import *
import subprocess
import re

running = False # Infinite loop condition
idle_status = 'To begin, please press "Start"' # Message for Idle Status

# Start, Stop & Scanning functions
def start():
    Status.configure(text='Loading, please wait...')
    global running
    running = True

def stop():
    global running
    running = False
    Status.configure(text=idle_status, background="Grey")
    StatusPing.configure(text="", background="Grey")

def scanning():
    if running:
        output = subprocess.check_output("ping 104.160.131.1", shell = False, universal_newlines=True).splitlines()
        for i in output:
            if "Packets" in i: var1 = int(re.search(r'\d+', str(re.findall(r'Lost =\s\d*',i))).group())
            if "Minimum" in i: var2 = int(re.search(r'\d+', str(re.findall(r'Average =\s\d*',i))).group())
    Status.configure(text="Packet lost: {0}".format(var1))
    StatusPing.configure(text="Average ms: {0}".format(var2))

    # Packet loss label coloring
    if var1 == 0:
        Status.configure(background="Green")
    else:
        Status.configure(background="Red")

    # Ping Status label coloring
    if var2 <= 35:
        StatusPing.configure(background="Green")
    if 35 < var2 < 70:
        StatusPing.configure(background="Yellow")
    if var2 >= 70:
        StatusPing.configure(background="Red")
    root.after(10000, scanning)

# GUI
root = Tk()
root.geometry("200x120")
root.wm_title("Ping Checker")

# Ping Check Label
Status = Label(root, text = idle_status, height="0", width="30", background="Grey")
Status.pack(pady=1) # For visible division between two labels
StatusPing = Label(root, height="0", width="30", background="Grey")
StatusPing.pack()

# Start & Stop Buttons
Start = Button (root, text = "Turn on", command = start).pack()
Stop = Button (root, text = "Turn off", command = stop).pack()

root.after(10000, scanning) # Global Loop
root.mainloop()


texts: Take first 12 bits of a number if longer than 12

texts:
I need to only take first 12 bits of a number if its longer than a 12 bit number and convert it to a decimal number. So if 7000 is entered than it will return 3500. I also print out the binary form of the new number to check if its converting and far as I can tell it is.

I am wondering if there is a better way to write this code?

#include <iostream>
#include <sstream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    int num, total = 0, x = 0, sizeOfStack, foo[12], i = 0;
    stack <int>  s; // You need the stack;
    stringstream ss;
    unsigned long long int binaryNumber;

    cout << "Please enter a decimal: ";
    cin >> num;

    while (num > 0)
    {
        total = num % 2;
        num /= 2;
        s.push(total); // push 'total'(?) onto the stack
                       //cout << total;
    }
    sizeOfStack = s.size();
    while (x < 12 && x < sizeOfStack) // Another loop to get the values from the stack / now in the correct order
    {
        if (!s.empty())
        {
            foo[i] = s.top();
            s.pop();
        }
        x++; // increment while loop
        i++; //increment array

    }
    for (int w : foo)
    {
        ss << w; // Converting an Integer Array into a Number
    }
    string some = ss.str();
    const char *p = some.c_str();
    binaryNumber = strtoull(p, NULL, 10);
    cout << "The Binary Number is: " << binaryNumber << endl;
    unsigned long long int  dec = 0, rem, num2, base = 1;
    num2 = binaryNumber; //set binarynum2ber to num2
    while (num2 > 0)
    {
        rem = num2 % 10;
        dec = dec + rem * base;
        base = base * 2;
        num2 = num2 / 10;
    }
    cout << "The Decimal Number is: " << dec << endl;
    cout << endl;
    return 0;
}


texts:
Given such a structure the output should be

10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15.

  Given a linked list where in addition to the next pointer, each node
  has a child pointer, which may or may not point to a separate list.
  These child lists may have one or more children of their own, and so
  on, to produce a multilevel data structure, as shown in below
  figure.You are given the head of the first level of the list. Flatten
  the list so that all the nodes appear in a single-level linked list.
  You need to flatten the list in way that all nodes at first level
  should come first, then nodes of second level, and so on.

This question is attributed to GeekForGeeks. Looking for code-review, optimizations and best practices. Verifying complexity to be \$O(n)\$, where \$n\$ is the count of all the nodes in the input multilevel linked list.

class Nodes<T> {
    Nodes<T> right;
    T item;
    Nodes<T> down;

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

public final class FlattenMultiLevelList<T> {

    public static <T> List<T> flatten (Nodes<T> node) {
        final List<T> flattenedList = new ArrayList<>();
        final Queue<Nodes<T>> nodeHead = new LinkedList<>();
        nodeHead.add(node);

        // travese the all heads
        while (!nodeHead.isEmpty()) {
            Nodes<T> currNode = nodeHead.poll();
            // traverse all Linkedlists
            while (currNode != null) {
                if (currNode.down != null) { nodeHead.add(currNode.down);  }

                flattenedList.add(currNode.item);
                currNode = currNode.right;
            }
        }

        return flattenedList;
    }
}

public class FlattenMultiLevelListTest {

    @Test
    public void test() {
        // level 1 should contain only a single linkedlist.
        Nodes<Integer> node1_1_1 = new Nodes<>(10);
        Nodes<Integer> node1_1_2 = new Nodes<>(5);
        Nodes<Integer> node1_1_3 = new Nodes<>(12);
        Nodes<Integer> node14 = new Nodes<>(7);
        Nodes<Integer> node15 = new Nodes<>(11);

        node1_1_1.right = node1_1_2;
        node1_1_2.right = node1_1_3;
        node1_1_3.right = node14;
        node14.right = node15;

        // level 2, first linkedlist, first node
        Nodes<Integer> node2_1_1 = new Nodes<>(4);
        Nodes<Integer> node2_1_2 = new Nodes<>(20);
        Nodes<Integer> node2_1_3 = new Nodes<>(13);

        node2_1_1.right = node2_1_2;
        node2_1_2.right = node2_1_3;
        node1_1_1.down = node2_1_1;

        // level 2, second linkedlist, first node.
        Nodes<Integer> node2_2_1 = new Nodes<>(17);
        Nodes<Integer> node2_2_2 = new Nodes<>(6);
        node2_2_1.right = node2_2_2;
        node1_1_3.down = node2_2_1;

        Nodes<Integer> node3_1_1 = new Nodes<>(2);
        node2_1_2.down = node3_1_1;

        Nodes<Integer> node3_2_1 = new Nodes<>(16);
        node2_1_3.down = node3_2_1;

        Nodes<Integer> node3_3_1 = new Nodes<>(9);
        Nodes<Integer> node3_3_2 = new Nodes<>(8);
        node3_3_1.right = node3_3_2;
        node2_2_1.down = node3_3_1;

        Nodes<Integer> node4_1_1 = new Nodes<>(3);
        node3_2_1.down = node4_1_1;

        Nodes<Integer> node4_2_1 = new Nodes<>(19);
        Nodes<Integer> node4_2_2 = new Nodes<>(15);
        node4_2_1.right = node4_2_2;
        node3_3_1.down = node4_2_1;

        assertEquals(Arrays.asList(10,5,12,7,11,4,20,13,17,6,2,16,9,8,3,19,15), FlattenMultiLevelList.flatten(node1_1_1));
    }

}


texts:
Recently I wrote a program that was required to handle year and month data and so I wrote this class to encapsulate that handling.  What I needed was a way to initialize the Yearmonth object based on the current local time, and allow a simple method of calculating future Yearmonth values based on a duration in months.  This sample code illustrates how I use it:

ymtest.cpp

#include <iostream>
#include "Yearmonth.h"

int main()
{
    YM::Yearmonth ym;    // today
    std::cout << ym << '\n';
    ym += 2;         // 2 months from now
    std::cout << ym << '\n';
    ym += 14;        // test year increment
    std::cout << ym << '\n';
}

Yearmonth.h

#ifndef YEARMONTH_H
#define YEARMONTH_H
#include <iostream>

namespace YM {
class Yearmonth
{
public:
    // construct with today's year and month
    Yearmonth();
    // construct with year, month (1=Jan, 12=Dec)
    Yearmonth(unsigned ayear, unsigned amonth);
    // increment by given number of months
    Yearmonth &operator+=(const unsigned mon);
    // return year
    unsigned year() const;
    // return month (1=Jan, 12=Dec)
    unsigned month() const;
    // prints to ostream.  E.g. 2014 Dec ==> "201412"
    friend std::ostream& operator<<(std::ostream &out, const Yearmonth &ym);
private:
    unsigned myyear;
    unsigned mymonth;
};
}
#endif //YEARMONTH_H

Yearmonth.cpp

#include <ctime>
#include "Yearmonth.h"

namespace YM {
Yearmonth::Yearmonth()
{
    time_t tt;
    time(&tt);
    tm *t = localtime(&tt);
    myyear = t->tm_year + 1900;
    mymonth = t->tm_mon;
}

Yearmonth::Yearmonth(unsigned ayear, unsigned amonth)
    : myyear(ayear), mymonth(amonth-1)
{
    myyear += mymonth/12;
    mymonth %= 12;
}

unsigned Yearmonth::year() const
{
    return myyear;
}

unsigned Yearmonth::month() const
{
    return mymonth+1;
}

Yearmonth &Yearmonth::operator+=(const unsigned mon)
{
    mymonth += mon;
    myyear += mymonth/12;
    mymonth %= 12;
    return *this;
}

std::ostream& operator<<(std::ostream &out, const Yearmonth &ym)
{
    return out << ym.myyear * 100 + ym.mymonth+1;
}
}

The class seems sufficient for my needs and everything works.  Have I missed anything important?


texts: Saving a recommended web article from form in Rails controller

texts:
I need criticisms and refactoring advice for my controller code:

class ItemsController < ApplicationController

    def new

    end

    def create
        params = items_params
        if not titles_and_urls_are_same_length(params)
            render :new
        end

        collection = false
        if params[:titles].length > 1
            collection = true
        end

        element = nil
        if collection
            collection = RecommendedCollection.new
            params[:titles].each_with_index do |title, index|
                resource = RecommendedResource.new(title: title, url: params[:urls][index])
                collection.resources << resource
            end
            if not collection.save
                return render :new
            end
        else
            resource = RecommendedResource.new(title: params[:titles][0], url: params[:urls][0])
            if not resource.save
                return render :new
            end
        end

        if not RecommendedItem.create(element: element)
            return render :new
        end
        render :new

    end

    private
        def titles_and_urls_are_same_length(params)
            params[:titles].length == params[:urls].length
        end

        def items_params
            params.permit(:description, titles: [], urls: [])
        end
end

Parameter example:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"......", "titles"=>["Learning to program in ruby", "Refactoring Code blog"], "urls"=>["http://www.hi.com", "http://www.ruby-master.com"], "description"=>"Improve your ruby skills", "commit"=>"Recommend"}

The idea behind the controller is that the user submits a link along with a URL and description to a site they like. If you submit a single link, then it is just a RecommendedResource, if you submit multiple links then it is to be turned into a "collection" or RecommendedCollection. That is why I check for the length of the params (which is probably not a good way to write the code).

They all go into a RecommendedItem to show in the feed, so I loop through one model only.

Here is an image that explains the visual results:


texts:
fn_mat4 fn_multMat4(fn_mat4 a,fn_mat4 b)
  {

  fn_mat4 ret;

  for (j = 0;j < 4;j++)
  {

  #pragma omp simd
  for (i = 0;i < 4;i++)
     ret.m[i+j*4]= a.m[j*4]*b.m[i] + a.m[j*4 + 1]*b.m[i+4] + a.m[j*4 + 2]*b.m[i+8] + a.m[j*4 + 3]*b.m[i+12];

  }
  return ret;
  }

If anybody knows how to reduce this to one loop instead of nested loops it would be greatly appreciated.


texts:
I've been out of working in Java for quite some time now (almost two years), so I've been working on a fun side project just to get back into the swing of things.

Essentially, in the long term, the goal of this will to be to compile a library that can be used in to create basic platform-like 2D games.

I'm never dealt with the development of engines themselves, so I was wondering if I could get some feedback on how the engine itself actually runs. I'm also just looking for overall input - is this a well-written Java library so far?

package io.code.gm;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

import javax.swing.JFrame;

import io.code.gm.Input.GMInputHandler;

public abstract class GMEngine extends Canvas implements Runnable {

    private static final long serialVersionUID = 1L;

    public GMInputHandler inputHandler;

    private boolean executionStatus = false;

    private JFrame frame;
    private BufferedImage image;
    private int[] pixels;

    private int updateCount = 0;
    private int frameCount = 0;

    private int updates = 0;
    private int frames = 0;

    abstract void init();
    abstract void update();
    abstract void render();

    public GMEngine(String title, int width, int height) {
        super();

        this.frame = new JFrame(title);

        frame.setResizable(false);
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        frame.setLayout(new BorderLayout());
        frame.add(this, BorderLayout.CENTER);

        frame.setVisible(true);

        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        this.pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

        init();
    }

    public synchronized void start() {
        this.executionStatus = true;
        new Thread(this).start();
        init();
    }

    public synchronized void stop() {
        this.executionStatus = false;
    }

    /**
     * Implemented method run().
     */
    public void run() {
        long lastUpdate = System.nanoTime();
        double nanoPerUpdate = 1000000000D/60D;

        int updates = 0;
        int frames = 0;

        long timer = System.currentTimeMillis();
        double delta = 0D;

        while(executionStatus) {
            long currentUpdate = System.nanoTime();
            delta += (currentUpdate - lastUpdate) / nanoPerUpdate;
            lastUpdate = currentUpdate;

            boolean renderStatus = false;

            while(delta >= 1) {
                updates++;
                update();
                delta -= 1;
                renderStatus = true;
            }

            if(renderStatus) {
                frames++;
                render();
            }

            if(System.currentTimeMillis() - timer >= 1000) {
                timer += 1000;

                this.updates = updates;
                this.frames = frames;

                updates = 0;
                frames = 0;
            }
        }
    }

}

A representation of implementation as a library:

package io.code.gm;

public class FakeImplementation extends GMEngine {

    private static final long serialVersionUID = 1L;

    public FakeImplementation(String title, int width, int height) {
        super(title, width, height);
    }

    public static void main(String[] args) {
        new FakeImplementation("2D Engine", 800, 500);
    }

    void init() {
        this.start();
    }

    void update() {

    }

    void render() {

    }

}


texts:
open Core.Std;;

let print aofa =
    let s1 = ( Array.length aofa ) - 1 in
    for i = 0 to s1 do
        for j = 0 to (Array.length aofa.(i)) - 1 do
            printf "%d " aofa.(i).(j);
        done;
        printf "\n";
    done;
;;

let rec fact i =
    if i <= 1 then 1 else i * fact (i - 1)
;;

let rec permutations ints =
    let length = Array.length ints in

    if length < 2 then
        [|ints|]
    else begin
        let total = fact length in

        let result = Array.create total (Array.create length 0) in
        for i = 0 to total - 1 do
            result.(i) <- Array.create length 0
        done;

        let block_size = total / length in
        for i = 1 to length do
            let rest = Array.append (Array.sub ints 0 (i - 1)) (Array.sub ints i (length - i)) in
            let rights = permutations rest in
            for r = 0 to (Array.length rights) - 1 do
                let n = Array.append [|Array.get ints (i - 1) |] rights.(r) in
                result.((i - 1) * block_size + r) <- n
            done;
        done;

        result
    end
;;

let () =
    let aofa = permutations [|1; 2; 3|] in
    print aofa;
;;

And result:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

UPD:

As first step, I wrote naive implementaion on python and then make version in OCaml

def permutations(s):
    if len(s) > 1:
        for i, v in enumerate(s):
            for p in permutations(s[0: i] + s[i+1:]):
                yield [v] + p
    else:
        yield s

def main():
    for p in permutations([1, 2, 3]):
        print(p)

if __name__ == '__main__':
    main()


texts:
I need to find the largest interval with a value less than a limit Lt.

The data is as follows:

For every test case T:

Number of elements N, limit Lt
N number of elements data

I wrote the following algorithm:

Create a CF Table while taking input
While size of interval plus current_Pos < number of elements, increase the size of interval while interval value less than limit, else increase the current_Pos

#include <iostream>
typedef long long int ll;
using namespace std;
ll a[1000000+100]={0};
int main() {
    // your code goes here
    ll t;
    cin>>t;
    while(t--)
    {
        ll n,lt;
        cin>>n>>lt;
        for(ll i=0;i<n;i++)
            cin>>a[i],a[i]+=a[i-1];
        ll i=0,size=0,ans=0;
        while(i+size<n)
        {
            while(a[i+size]-a[i-1]<=lt && i+size<n){ans=a[i+size]-a[i-1];size++;
            }
            i++;
        }
        cout<<ans<<" "<<size<<endl;
    }
    return 0;
}

While a similar strategy here which increases the interval and shifts it by adding the next element and removing the previous one works:

#include <iostream>
#include <cstdio>
using namespace std;
int a[100006];
int main()
{
    int s,p,q,ans1,ans2,i,j,n,m,k,t,b,c,d;
    scanf("%d",&t);
    for(k=1;k<=t;k++)
    {
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        ans1=100000000;
        ans2=0;
        p=1;
        q=1;
        s=a[1];
        while(q<=n && p<n)
        {
            if(s<=m)
            {
                if(q-p+1>ans2)
                {
                    ans2=q-p+1;
                    ans1=s;
                }
                else
                    if(q-p+1==ans2)
                        ans1=min(ans1,s);
            }
            if(s<m)
            {
                q++;
                s=s+a[q];
            }
            else
            {
                p++;
                s=s-a[p-1];
            }
        }
        printf("%d %d\n",ans1,ans2);
    }
    return 0;
}

I'd like to know where my approach fails and its actual running time.


texts: Alerts system for Discord guilds using Discord.js

texts:
I have this code running on a Discord bot. It serves as an alerts system for an online game, where it queries an API every so often and appropriately parses a string and sends it to a guild if it matches certain conditions. Though I don't see any problems with it, I have a feeling it could be optimized or trimmed down. Feel free to visit the http://pso2.kaze.rip/eq/ url to see context for the response.

client is a Discord.js client object, and fs is a Promisified version of the standard module.

It's supposed to query the URL and parse the data it receives. First, it checks if the first element in the response is different to the one that's cached. If it is, it filters what guilds have the alerts system enabled, and what ships they want to be alerted for. (For example: I have a guild that is enabled for ships 3 and 8, so I'll only receive the objects contained in the eqs array where ship is either 3 or 8)

After that's done, it just builds the formatted message and sends it to the guild and updates the cache once every guild has received their alert.

setInterval(async () => {
    const response = await fetch('http://pso2.kaze.rip/eq/');
    if (response.status !== 200) return;

    const data = await response.json();
    const cache = JSON.parse(await fs.readFile("./cache.json"));

    if (data[0]["time"] !== cache["time"]) {
        const guilds = await client.guilds.filter(guild => { return client.provider.get(guild, "alerts") });

        for (let guild of guilds) {
            let settings = await client.provider.get(guild[1], "alerts");
            let eqs = data[0]["eqs"].filter(item => { return settings["ships"].includes(item["ship"]) });
            let format = [];

            if (eqs.length <= 0) return;
            if (eqs.length !== 10) {
                for (let eq of eqs) {
                    format.push(`\`SHIP ${eq['ship']}:\` ${eq['name']} (${eq['jpName']})`);
                }
            }
            else {
                format.push(`\`ALL SHIPS:\` ${eq['name']} (${eq['jpName']})`);
            }

            let time = moment(data[0]["when"]);
            let string = `:watch:**IN 40 MINUTES:** (${time.format("HH:mm")} JST)\n${format.join('\n')}`;
            await client.channels.get(settings['channel']).send(string);
        }

        await fs.writeFile("./cache.json", `{ "time" : "${data[0]["time"]}" }`);
    }
}, 50000, client);


texts: Executing certain code from a spreadsheet

texts:
Here is some code which loops through an area in a spreadsheet and executes the code based on the condition that the source cells do not contain the value "(blank)".

The code works, but it's very inefficient to run nested if statements in this manner.  I've tried to have a go at making it more efficient in the long run but I'm out of ideas.

Any suggestions?

Sub NestedIfStatement()
Dim lastrow1 As Long
Dim I As Integer, J As Integer, N As Integer, MaxPriority as Integer

N = 3
Set Maxnumber = WS1.Range("A" & I & ":A" & lastrow1)
    MaxPriority = Application.Max(Maxnumber)

For J = 1 To lastrow1
    If WS1.Cells(J, 1) <= MaxPriority Then
       If WS1.Cells(J, 6).Value <> "(blank)" Then
          WS3.Cells(N, 7).Value = WS1.Cells(J, 6).Value
       End If
       If WS1.Cells(J, 5).Value <> "(blank)" Then
          WS3.Cells(N, 6).Value = WS1.Cells(J, 5).Value
       End If
       If WS1.Cells(J, 4).Value <> "(blank)" Then
          WS3.Cells(N, 4).Value = WS1.Cells(J, 4).Value
       End If
       If WS1.Cells(J, 3).Value <> "(blank)" Then
          WS3.Cells(N, 3).Value = WS1.Cells(J, 3).Value
       End If
       If WS1.Cells(J, 2).Value <> "(blank)" Then
          WS3.Cells(N, 2).Value = WS1.Cells(J, 2).Value
       End If
       N = N + 1
    End If
Next J

End Sub


texts: Merging multiple JSON files using Python

texts:
I have multiple (1000+) JSON files each of which contain a JSON array. I want to merge all these files into a single file.

I came up with the following, which reads each of those files and creates a new object with all the contents. I then write this new object into a new file.

Is this approach efficient? Is there a better way to do so?

head = []
with open("result.json", "w") as outfile:
    for f in file_list:
        with open(f, 'rb') as infile:
            file_data = json.load(infile)
            head += file_data
    json.dump(head, outfile)


texts:
I'm trying to show a table, for each ID, to see if there is data available. In this case, its measurements. If there's no data, that means the logger isn't doing its job properly.

I currently have two tables: data and times. data contains id, datetime, sensor_id, and value. times contains id and value.

Times is filled with 00:00, 00:01, 00:02, etc., all the way through to 23:59.

I have this query:

SELECT t.`value`, d.`sensor_id`, COUNT(t.`value`) as `numrows`
FROM `data` d
RIGHT JOIN `times` t
ON d.`datetime` LIKE CONCAT('% ', t.`value`, '%')
WHERE d.`datetime` LIKE '%$2014-11-05%'
AND d.`sensor_id` IN(1,2,3,4,5,999)
GROUP BY d.`sensor_id`, t.`value`
ORDER BY d.`sensor_id` ASC, t.`id` ASC

while($s = $select->fetch_assoc()) {
    $checkArray[$s['sensor_id']][$s['value']] = $s['numrows'];
}

foreach($checkArray as $key => $arr) {
    echo 'Sensor: ' . $key;
    for($i = 0; $i <= 23; $i++) {
        for($j = 0; $j <= 59; $j++) {
            $time = strlen($i) == 1 ? '0' . $i : '' . $i;
            $time .= ':';
            $time .= strlen($j) == 1 ? '0' .$j : '' . $j;

            if(isset($arr[$time]) && $arr[$time] >= 1) { //See if has at least one row
                echo 'YES DATA FOR ' . $time . '<br>';
            }
        }
    }
}

Of course, I sort this in a table, and the result is this:

Just for sensors 1, 2, 3, 4, and 5, the load time is over 5.5 seconds. I don't know how to optimize this further. I've put indexes on the queried columns, but I can't think of anything else.

My SHOW CREATE TABLE for data:

CREATE TABLE `data` (
 `id` int(13) NOT NULL AUTO_INCREMENT,
 `sensor_id` int(13) NOT NULL,
 `datetime` datetime NOT NULL,
 `value` float NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `sensor_id_2` (`sensor_id`,`datetime`,`value`),
 KEY `sensor_id` (`sensor_id`),
 KEY `value` (`value`),
 KEY `datetime` (`datetime`),
 KEY `sensor_id_3` (`sensor_id`),
 KEY `datetime_2` (`datetime`)
) ENGINE=InnoDB AUTO_INCREMENT=103921 DEFAULT CHARSET=utf8

And my SHOW CREATE TABLE for times:

CREATE TABLE `minutes` (
 `id` int(13) NOT NULL AUTO_INCREMENT,
 `value` varchar(16) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_3` (`id`),
 KEY `value` (`value`),
 KEY `id` (`id`),
 KEY `value_2` (`value`),
 KEY `id_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1441 DEFAULT CHARSET=utf8


texts: Compact a comma delimited number list into ranges

texts:
I'm looking for a clever way to do the following operation:

Take a list of numbers:

1, 2, 3, 4, 5, 12, 13, 14, 19

and compact it into a string like so:

1-5, 12-14, 19

With the following rule: only compress into a range (i.e. use a dash) when the count of numbers in the range is 3 or more.

I.e.: 1, 2, 4, 5 would result in: 1, 2, 4, 5 and NOT: 1-2, 4-5

This is my implementation, but I feel like it could be improved upon greatly:

 public string CompactNumberRanges(IEnumerable<int> numbers,
                                   int requiredRangeCount)
 {
     if (requiredRangeCount <= 1)
         throw new ArgumentOutOfRangeException("requiredRangeCount");

     int[] sorted = numbers.OrderBy(e => e).ToArray();

     StringBuilder b = new StringBuilder();

     for (int i = 0; i < sorted.Length; i++)
     {
         int cv = sorted[i];
         int count = 0;

         for (int j = cv; ; j++)
         {
             if (Array.IndexOf(sorted, j) == -1)
                 break;
             else
                 count++;
         }

         if (count == 0)
             throw new InvalidOperationException();
         else if (count < requiredRangeCount)
             b.Append(", ").Append(cv);
         else if (count >= requiredRangeCount)
         {
             b.Append(", ").AppendFormat("{0}-{1}", cv, sorted[i + count - 1]);

             i += count - 1;
         }
     }

     return b.ToString().Trim(',', ' '); ;
 }

As an example:

List<int> numbers = new List<int>
    (
        new int[] { 1, 2, 3, 4, 5, 12, 13, 14, 19 }
    );

Console.WriteLine(CompactNumberRanges(numbers, 3));
//  output: 1-5, 12-14, 19

I have this working fine, I'm really just looking to find better ways to do the same operation because I think it's a fun one.


texts: Getting the remaining days of the current week

texts:
I'm trying to get the remaining days of the current week, excluding weekends and past days, and I'm lazily checking for possible continuity of the week in the next month. This is not the best solution that I can think of (and even so, perhaps there are flaws), is there a simpler and clean way to achieve what I want?

function getDaysInMonth(month, year, holidays) {
    var date = new Date(year, month, 1);
    var today = new Date();
    today.setHours(0, 0, 0, 0);
    var days = [];
    var firstDay = 0;
    var remaining = [];
    var isWeekend = (today.getDay() === 6) || (today.getDay() === 0);
    while (date.getMonth() === month) {
        if ((date >= today) && (date.getDay() != 0) && (date.getDay() != 6)) {
            days.push(new Date(date));
        }
        date.setDate(date.getDate() + 1);
    }
    month += 1;
    while (date.getMonth() === month) {
        if ((date.getDay() != 0) && (date.getDay() != 6)) {
            days.push(new Date(date));
        }
        date.setDate(date.getDate() + 1);
    }
    if (holidays) {
        for (var index = 0; index < holidays.length; index++) {
            var holiday = new Date(holidays[index]);
            for (var id = 0; id < days.length; id++) {
                if (holiday.getTime() === days[id].getTime()) {
                    days.splice(id, 1);
                    break;
                }
            }
        }
    }
    if (!isWeekend) firstDay = days[0].getDay();
    for (var index = 0; index < days.length; index++) {
        if (isWeekend) {
            remaining.push(new Date(days[index]));
            if (index === 4) break;
        } else {
            if (days[index].getDay() >= firstDay) {
                remaining.push(new Date(days[index]));
            } else {
                break;
            }
        }
    }
    return remaining;
}

Update: I've expanded the code to query for possible holidays, holidays an array of dates (mm/dd/YYY).


texts: IEnumerable of classes that implement a given interface at runtime

texts:
I am implementing the command pattern in a project that I am working on and I have an interface, ICommandFactory that all of my commands are implementing.

When I run the application I want to dynamically gather all classes in the current assembly that implement that interface, thus producing a list of all possible commands.

So I came up with the method below. This was the first thing that I could get to work. Is there a better way to do this?

    private static IEnumerable<ICommandFactory> GetAvailableCommands()
    {
        var interfaceType = typeof (ICommandFactory);
        var implementors = Assembly.GetExecutingAssembly().GetTypes().Where(
            i => interfaceType.IsAssignableFrom(i) && i != interfaceType);

        var commands = new List<ICommandFactory>();

        foreach(var implementor in implementors)
        {
            var ctor = implementor.GetConstructor(Type.EmptyTypes);
            if (ctor == null) continue;
            var instance = ctor.Invoke(null) as ICommandFactory;
            if (instance == null) continue;
            commands.Add(instance);
        }

        return commands;
    }


texts: Simplifying multiple click events into something more extendable

texts:
I have the following code which changes the text in a certain element on click depending on the text value present in the element at the time the event is fired.

http://jsfiddle.net/TNDhL/

$('#left').on('click', function (){
if ($("#textContainer:contains('something')").length) {
    $('#textContainer').text('third text replacement');
    $('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
    $('#textContainer').text('now the next item');
    $('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
    $('#textContainer').text('new text here');
    $('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
    $('#textContainer').text('something');
    $('.elsewhere').text('text here');
}
});

$('#right').on('click', function (){
if ($("#textContainer:contains('something')").length) {
    $('#textContainer').text('new text here');
    $('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
    $('#textContainer').text('now the next item');
    $('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
    $('#textContainer').text('third text replacement');
    $('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
    $('#textContainer').text('something');
    $('.elsewhere').text('text here');
}
});

Please see fiddle above for working version.

In this instance clicking on 'Left' or 'Right' would change the text above.

Is there a better way to handle this case? Main goal is to allow for easier extension of these simple functions into something more complex that involves several similar click events. Something less error prone and easier to maintain/grow. Any suggestions?


texts:
I was asked the following problem:

  What is the smallest positive integer n that can be written as a sum of three positive cubes in at least 12 ways?

Can this be coded better way such that it is easy to compute the smallest positive integer that is sum of m nth powers? I'm not a professional programmer, so I managed only to write one solution that works.

l = list()
for i in range(1,500):
    for j in range(i,500):
        for k in range(j,500):
            l.append(i**3+j**3+k**3)
l.sort()
for i in range(0,len(l)-12):
    if l[i] == l[i+12]:
        number = l[i]
for i in range(1,500):
    for j in range(i,500):
        for k in range(j,500):
            if i**3+j**3+k**3 == number:
                print(str(number)+"="+str(i)+"^3+"+str(j)+"^3+"+str(k)+"^3")


texts:
So the task is that a string being passed to one of my methods looks like this

<DIV><GKY><UID><END>

it is generated this way from another program, so it will always have that format. Now to sum up how it works is like this.. This is to represent 3 byte arrays a DIV key (short for diversification) a Guest Key (GKY), and a Unique ID (UID). This particular class that i made stores those byte arrays as a 2 character hex string. IE {0x03, 0xFE, 0xE0} would be stored as "03FEE0"

so those are the requirements of the class.. I have to be able to parse that string to store those byte arrays for access later. DIV (if present) will always be 16 bytes long. GKY is variable and can be at most 192 bytes. UID is required and will always be present and is always 7 bytes. so I came up with this... as far as I can tell it works.

#pragma once

class KeyInputParser
{
public:
    KeyInputParser(void)
    {
        //DIV will always be 16bytes... but it is either not required
        DIV = new char[32];
        //uid will ALWAYS be 7 bytes and is required
        UID = new char[14];
    }
    ~KeyInputParser(void)
    {
        delete[] DIV;
        delete[] GKY;
        delete[] UID;
    }
    char* DIV;
    char* GKY;
    char* UID;
    void SetKeyString(const char* str)
    {
        wcout << "KeyInputParser::SetString()+" << endl;
        wcout << "\t" << str << endl;

        char* div;
        char* gky;
        char* uid;

        div = (char*)memchr(str, '>', strlen(str));
        div++;

        gky = (char*)memchr(div, '>', strlen(div));
        gky++;

        uid = (char*)memchr(gky, '>', strlen(gky));
        uid++;

        for(int i=0; i<strlen(div); i++)
        {
            if(div[i] == '<')
            {//DIV will always be 16bytes... but it is either not required
                memcpy(DIV, div, i);
                DIV[i] = '\0';
                break;
            }
        }
        for(int i=0; i<strlen(gky); i++)
        {//gky will vary, but max out at 192 bytes
            if(gky[i] == '<')
            {
                GKY = new char[i+1];
                memcpy(GKY, gky, i);
                GKY[i] = '\0';
                break;
            }
        }
        for(int i=0; i<strlen(uid); i++)
        {//uid will ALWAYS be 7 bytes and is required
            if(uid[i] == '<')
            {
                memcpy(UID, uid, i);
                UID[i] = '\0';
                break;
            }
        }

        wcout << "KeyInputParser::SetString()-" << endl;
    }
};

I don't care for the way it came out, but I am very new to C++.


texts:
I have an object that is fairly expensive to create and has a tendency to get created multiple times because each distinct user may have one or many instances of this object. This object can expire as its internal authentication becomes stale and no longer valid.

Because of this, I want need to keep a dictionary so I can keep a list of objects for each user.... but....I need this dictionary to not retain objects indefinitely since they can expire. ( Managing the expiration is outside the scope of this )

I used this article as a starting point, but took the concept a little further to manage the number of objects stored internally to keep the pool from getting too large.

public sealed class PooledDictionary<TKey, TValue>
{
    private readonly byte m_poolSize;
    private readonly ConcurrentDictionary<TKey, ConcurrentQueue<TValue>> m_pool;
    private readonly ConcurrentQueue<TKey> m_keyQueue;
    public PooledDictionary(byte maxPoolSize)
    {
        if (maxPoolSize <= 0)
            maxPoolSize = (byte)Math.Min(Environment.ProcessorCount, byte.MaxValue);

        m_poolSize = maxPoolSize;
        m_keyQueue = new ConcurrentQueue<TKey>();
        m_pool = new ConcurrentDictionary<TKey, ConcurrentQueue<TValue>>(Environment.ProcessorCount * 2, m_poolSize);
    }

    public bool TryAdd(TKey key, TValue value)
    {
        if (key == null)
            return false;

        if (!m_pool.ContainsKey(key) && m_pool.TryAdd(key, new ConcurrentQueue<TValue>()))
        {
            m_keyQueue.Enqueue(key);

            while (m_pool.Count > m_poolSize)
            {
                TKey localKey;
                if (m_keyQueue.TryDequeue(out localKey))
                {
                    TryRemove(localKey);
                }
            }
        }

        ConcurrentQueue<TValue> q;
        if (m_pool.TryGetValue(key, out q))
        {
            q.Enqueue(value);
            while (q.Count > m_poolSize)
            {
                TValue localValue;
                q.TryDequeue(out localValue);
            }
        }
        else
        {
            return false;
        }
        return true;
    }

    public bool TryRemove(TKey key)
    {
        if (key == null)
            return false;

        ConcurrentQueue<TValue> value;
        return m_pool.TryRemove(key, out value);
    }

    public int Count(TKey key)
    {
        if (key == null)
            return 0;

        if (!m_pool.ContainsKey(key)) m_pool.TryAdd(key, new ConcurrentQueue<TValue>());
        ConcurrentQueue<TValue> q;
        if (m_pool.TryGetValue(key, out q))
        {
            return q.Count;
        }
        return 0;
    }

    public TValue Request(TKey key, Func<TValue> creator = null)
    {
        if (key == null)
            return default(TValue);

        if (!m_pool.ContainsKey(key)) m_pool.TryAdd(key, new ConcurrentQueue<TValue>());
        ConcurrentQueue<TValue> q;
        if (m_pool.TryGetValue(key, out q))
        {
            TValue v;
            if (q.TryDequeue(out v)) return v;
            if (null != creator) return creator();
        }
        return default(TValue);
    }

    public bool Release(TKey key, TValue value)
    {
        return TryAdd(key, value); //just adds it back to key's queue
    }
}


texts: Script to monitor a folder and compress the content

texts:
We have a Debian Squeeze server where we upload files through SFTP, and I wrote this script to automatically compress uploaded files.

The script is scheduled through a cron job in an unprivileged user's crontab.

As of now, the script works and does its job.

But I'm pretty novice to Bash scripting, and I'm wondering if it has any major flaws. (e.g. If the file name contains " what happens? Does it have security flaws?)

Also, am I doing it right, or there are better ways to do it?

#!/bin/bash

# Use the newline character
# as the field separator.
IFS=$'\n'

# The folder to watch.
dir="/path"

# Get the folder's content, recurively.
for item in $(find "${dir}")
do

        # If the item is a regular file.
        if [ -f "${item}" ]
        then

                # Check if the file is in use
                # by someone else. E.g. The SFTP
                # daemon because the user is still
                # uploading it.
                lsof -n "${item}" > /dev/null

                # If no one is using the file.
                if [ "$?" -ne 0 ]
                then

                        # Get the file extension.
                        ext=$(echo "${item}" | awk -F "." '{ print $NF }')

                        # If the file is not a zip archive
                        # and does not exists a zip archive for it
                        if [ "${ext}" != "zip" -a ! -f "${item}.zip" ]
                        then
                                # Create the zip archive.
                                zip "${item}.zip" "${item}" > /dev/null
                        fi

                fi

        fi

done


texts:
I've been given a task to create elements with some special corners, and those elements should be responsive.

This works, but am I wondering if something better could come up.
Less code to maintain.

I wish NOT to use any CSS Preprocessor.  I prefer the more readable pure and simple CSS.

jsFiddle

          Jump Session Outdoor Editon

Party

          London

CSS:

p{
  margin: 0;
  padding: 0;
}

.module-wrapper {
    width: 20%;
    margin: 40px auto;
}

.sub-module {
  margin: 0 -5px;
}

.sub-module p {
    padding: 10px;
    color: white;
    text-align: center;
}

.type {
    background-color: red;
}

.local {
  background: black;
  padding-bottom: 5px;
}

.local p {
    background-color: black;
}

.title {
  background: green;
  padding-top: 5px;
}

.title p {
    background-color: green;
}


texts: stability of an exponential moving average

texts:
I used the following code:

#include<vector>
class UltrasonicRecorder
{
public:
    UltrasonicRecorder(int referenceValue, Input referenceInput) :
        _referenceValue(referenceValue),
        _referenceInput(referenceInput)
    {}

    std::vector<int> GetData();

    void RecordData(Input);
    int CompensateTemperatur(int);

private:
    double _compensation;
    int _referenceValue;
    Input _referenceInput;
    std::vector<int> _data;
};

std::vector<int> UltrasonicRecorder::GetData()
{
    std::vector<int> ret;
    std::swap(ret, _data);

    return ret;
}

void UltrasonicRecorder::RecordData(Input input)
{
    int value = (ANALOG_VALUE_RANGE - 1) - GetAnalogValue(input);
    value = CompensateTemperature(value);
    _data.push_back(value);
}

int UltrasonicRecorder::CompensateTemperature(int value)
{
    int measuredValue = GetAnalogValue(_referenceInput);
    if(measuredValue > 0)
    {
        static const double delta = 1.0e-6;
        _compensation = (1.0 - delta) * _compensation +
            delta * _referenceValue / (double)measuredValue;
    }
    return static_cast<int>(value * _compensation);
}

int GetAnalogValue(Input) returns a 12 bit value from a ultrasonic sensor measuring distance (0-4095, ANALOG_VALUE_RANGE = 4096). double _compensation; is a member of the encapsulating class. _referenceValue is the initial reference value from _referenceInput (normally it has a low fluctuation, with a value somewhere in the middle of the 12 bit range, but it changes with temperature).

RecordData() is called every 2 milliseconds (more or less, running on Windows). So a high update rate for the reference value, but I wanted a gradual compensation over time. Therefore I used an exponential moving average, the delta is empirically determined and may need to be changed later.

GetData() is called approximately every second to flush _data and use the record for further evaluation.

We started testing this code on customer facilities, but got the feedback that values are drifting away after a few days. I think it's a numerical unstable algorithm that accumulates rounding errors. Can someone with more experience with the subtleties of floating-point arithmetic answer me:

Can this exponential moving average algorithm be improved to achieve better stability?

Notes for additional improvements of the code are welcomed as well.


texts:
https://leetcode.com/problems/implement-strstr/

I implemented Rabin-Karp algorithm
https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm

please review for performance, also if you were in an interview what do you think about using functions like GetHashCode()?
would you like the interviewee to implement the hashing on their own?

  Implement strStr().

  Return the index of the first occurrence of needle in haystack, or -1
  if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:

  What should we return when needle is an empty string? This is a great
  question to ask during an interview.

  For the purpose of this problem, we will return 0 when needle is an
  empty string. This is consistent to C's strstr() and Java's indexOf().

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StringQuestions
{
    /// <summary>
    ///https://leetcode.com/problems/implement-strstr/
    /// </summary>
    [TestClass]
    public class StrStrLeetCode
    {
        [TestMethod]
        public void ValidNeedleTest()
        {
            string haystack = "hello";
            string needle = "ll";
            Assert.AreEqual(2, StrStr(haystack, needle));
        }

        [TestMethod]
        public void NotValidNeedleTest()
        {
            string haystack = "aaaaa";
            string needle = "ba";
            Assert.AreEqual(-1, StrStr(haystack, needle));
        }

        public int StrStr(string haystack, string needle)
        {
            if (string.IsNullOrEmpty(needle))
            {
                return 0;
            }
            int n = haystack.Length;
            int m = needle.Length;
            var hash = needle.GetHashCode();
            for (int i = 0; i < n - m + 1; i++)
            {
                string tempStr = haystack.Substring(i, m);
                var hashTemp = tempStr.GetHashCode();
                if (hash == hashTemp)
                {
                    return i;
                }
            }

            return -1;
        }
    }
}


texts:
For continuity, my last question was with adding numbers together with a function call: Example x86-64 program. In this one I've tried to apply the lessons pointed out in the previous answer (stack alignment, using edx instead of rdx where the results will fit). I've tried to comment inline with the code:
# We are going to calculate 7^2 + 2^4 = 49 + 16 = 65
# The exponent function supports whole numbers (long) >= 0

.section .data
base_1: .long   7
exp_1:  .long   2
base_2: .long   2
exp_2:  .long   4

.section .text
.globl _start
_start:

    # We will do the first function call, 7^2
    mov base_1(%rip),   %edi
    mov exp_1(%rip),    %esi
    call exp

    # needs to be 16-byte aligned before the next function call so do two pushes
    pushq $0
    pushq %rax

    # Now do the second function call
    mov base_2(%rip),   %edi
    mov exp_2(%rip),    %esi
    call exp

    # We have the return value in %eax so let's add this with our previous function's value
    popq %rdi

    add %eax,   %edi
    mov $60,    %eax
    syscall

exp:
    # Initialize %eax to 1
    mov $1,     %eax

exp_op:
    cmp $0,     %esi
    je exp_ret
    imul %edi,  %eax
    dec %esi
    jmp exp_op

exp_ret:
    ret

I have a few specific questions about the code:

Is doing a raw push/pop common? Or is the convention always to do push rbp mov rsp rbp...pop rbp. Why is one method preferred over the other?
What if I wanted to store the result of the first calculation in a register: are there any registers that are guaranteed to be preserved between function calls? Or is this why the push...pop method is used so much?
Finally, does my exp seem ok? It feels a bit odd having three labels in what amounts to one function. How could that be improved?


texts:
So I need to update some certain values within text file based on actual values there. Any advice on making it more effective or just readable is appreciated.

Example text file:

Lalala
There is tons of text in this file log-12345sr
And somewhere within
There are log file names log-23456sr
Some more text here
I want to edit log file names within Java code
to change the log file names log-34567sr some text here as well
But I want to edit based on current value
For example add 100 to the number in the name
So log-45678sr
becomes log-45778sr
I can safely assume there is no more than one on a single line

My code:

public static void main(String[] args) throws Exception {
    doModification(new File("test.txt"));
}

public static ArrayList<String> findAllOccurrences(File file, String prefix, String suffix) throws IOException {
    ArrayList<String> occurrences = new ArrayList<>();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.contains(prefix) && line.contains(suffix)) {
            occurrences.add(line.split(prefix)[1].split(suffix)[0]);
        }
    }
    return occurrences;
}

public static HashMap<String,String> buildReplacementMap(ArrayList<String> values, Function<String, String> modification) throws Exception {
    HashMap<String,String> replacementMap = new HashMap<>();
    for(String value: values){
        replacementMap.put(value, modification.apply(value));
    }
    return replacementMap;
}

public static void doModification(File file) throws Exception {
    ArrayList<String> occurrences = findAllOccurrences(file, "log-", "sr");
    HashMap<String, String> replacementMap = buildReplacementMap(occurrences, (value) -> String.valueOf(Long.parseLong(value) - 100));
    String content = new String(Files.readAllBytes(file.toPath()));
    for (Map.Entry<String,String> pair : replacementMap.entrySet()){
        content = content.replaceAll(pair.getKey(), pair.getValue());
    }
    Files.write(file.toPath(),content.getBytes());
}

Text file after modification:

Lalala
There is tons of text in this file log-12445sr
And somewhere within
There are log file names log-23556sr
Some more text here
I want to edit log file names within Java code
to change the log file names log-34667sr some text here as well
But I want to edit based on current value
For example add 100 to the number in the name
So log-45778sr
becomes log-45878sr
I can safely assume there is no more than one on a single line


texts: MS Access SQL query for active assigned cases

texts:
I've inherited an Access database and am looking to start using it to do reporting. I've written a query that gets me the information I'm looking for, I'm just hoping someone can have a look over it and tell me if I'm doing it the wrong way or not.

Anyway, the query takes information from 3 tables:

sites - more detailed information on each workplace
employees - list of employees and their associated workplace
cases - holds the bulk of the information needed for the report

I want most fields from the cases table as this is how work is tracked, but I want to also group by the city which is in the sites table and by employee name from the employees table.

SELECT
    sites.city,
    employees.[first name],
    employees.[last name],
    cases.[assigned to],
    cases.ref,
    cases.status,
    cases.priority,
    cases.[opened date],
    Round(Now()-cases.[opened date],0) AS Age
FROM
    cases
LEFT JOIN
    (employees LEFT JOIN sites ON employees.site = sites.site)
ON
    cases.[assigned to] = employees.username
WHERE
    cases.[assigned to]<>"Not Assigned"
AND
    cases.status="Active"
AND
    cases.priority<>"first contact"
ORDER BY
    sites.city,
    employees.[first name],
    employees.[last name],
    cases.[opened date] desc;

Is there any stupid rookie mistakes in here that I've fallen prey to? Could that be done any better? Have I not given enough information in my question?


texts: Adding thousand separator to various number types

texts:
Am making a pure .net library with helper functions (GitHub).

However I wanted to have a thousand separator for all number types and here is what I am currently doing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Avo
{
    public static class Extension_Number
    {
        #region ThousandSeparator
        public static string ToThousandSeparator(this decimal value, int numberOfDecimalPlaces)
        {
            if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
            return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
        }
        public static string ToThousandSeparator(this int value, int numberOfDecimalPlaces)
        {
            if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
            return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
        }
        public static string ToThousandSeparator(this double value, int numberOfDecimalPlaces)
        {
            if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
            return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
        }
        public static string ToThousandSeparator(this long value, int numberOfDecimalPlaces)
        {
            if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
            return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
        }
        #endregion
    }
}

As you can see above ,

l have to repeat the same for
int , decimal , long

l can achieve the results l want but is it best

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Avo
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal tes = 294944.8484827M;
            int iint = 34;
            Console.WriteLine(tes.ToThousandSeparator(3));
            Console.WriteLine(iint.ToThousandSeparator(2));
            Console.ReadKey();
        }
    }
}

but is there an eloquent way of doing it , but allowing number types only.


texts: Select depart date, 5 days from today and return date, 6 days from today in Selenium

texts:
I am automating a scenario of flight booking on Cleartrip.com(https://www.cleartrip.com/flights) in which I have to enter depart date, 5 days from today and return date, 6 days from today. I have written below code.

Date dt = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.DATE, 5);
dt = calendar.getTime();
String departdate = new SimpleDateFormat("dd/mm/yyyy").format(dt);

//enter Journy date in the field
WebElement depart = driver.findElement(By.id("DepartDate"));
depart.sendKeys(departdate);

Date dt1 = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt1);
calendar.add(Calendar.DATE, 6);
dt1 = calendar.getTime();
String returndate = new SimpleDateFormat("dd/mm/yyyy").format(dt1);

//enter returndate in the field
WebElement return= driver.findElement(By.id("ReturnDate"));
return.sendKeys(returndate);