texts:
I have some files that I want to process, and I know how to do it in sed/awk (for each one):

awk '{if (index($0,"#")!=1) {line++; if (line%3==1) {print $2,$3}}}' q.post  > q

or

grep -v "#" q.post | awk '{if (NR%3==1) {print $2,$3}}'

It's one line, and rather beautiful and clear.

Now, my main program is in python (2.7). Calling sed/awk from python is a bit tedious—I get some error—and I'd rather use a nice pythonic way to do it.

So far I have:

    pp_files = glob.glob("*gauss.post")
    for pp in pp_files:
        ppf = open(pp)
        with open(pp[:pp.rfind(".post")] + "_clean.post", "w") as outfile:
            counter = 0
            temp = []
            for line in ppf.readlines():
                if not line.startswith("#"):
                    temp.append(line)
            for line in temp:
                if counter % 3 == 0:
                    outfile.write(" ".join(line.split()[1:3]) + '\n')
                counter += 1
        ppf.close()

Meh.

It works, but it's not beautiful. Is there a pythonic way, preferentially a clear one liner (not 10 imbricated list comprehension, to replace awk and sed ?

Thanks


texts: Storing hierarchical data into a data structure

texts:
With the following data in a table,

+----+-----------+-----------+---------+
| id | name      | parent_id | prev_id |
+----+-----------+-----------+---------+
| 1  | Section 1 | NULL      | NULL    |
| 2  | Item 1.1  | 1         | NULL    |
| 3  | Item 1.2  | 1         | 2       |
| 4  | Item 1.3  | 1         | 3       |
| 5  | Section 2 | NULL      | 1       |
| 6  | Item 2.1  | 5         | NULL    |
| 7  | Item 2.2  | 5         | 6       |
| 8  | Item 2.3  | 5         | 7       |
| 9  | Item 1.4  | 1         | 4       |
+----+-----------+-----------+---------+

I have created this data structure:

[
    1: stdClass Object (
        [id] => 1
        [name] => Section 1
        [parent_id] => NULL
        [prev_id] => NULL
        [children] => [
            2: stdClass Object ([id] => 2, [name] => Item 1.1, [parent_id] => 1, [prev_id] => NULL)
            3: stdClass Object ([id] => 3, [name] => Item 1.2, [parent_id] => 1, [prev_id] => 2)
            4: stdClass Object (...)
            9: stdClass Object (...)
        ]
    ),
    5: stdClass Object (
        [id] => 5
        [name] => Section 2
        [parent_id] => NULL
        [prev_id] => 1
        [children] => [
            6: stdClass Object (...)
            7: stdClass Object (...)
            8: stdClass Object (...)
        ]
    )
]

Here is the working code that I wrote:

function build_tree(array $rows)
{
    $accum = array();

    $rec = function ($parentId = null, $prevId = null) use (&$rec, &$accum, $rows) {
        foreach ($rows as $row) {
            if ($row->parent_id == $parentId && $row->prev_id == $prevId) {
                // add child
                if ($row->parent_id) {
                    if (!isset($accum[$row->parent_id]->children)) {
                        $accum[$row->parent_id]->children = array();
                    }
                    $accum[$row->parent_id]->children[$row->id] = $row;
                // add root
                } else {
                    $accum[$row->id] = $row;
                }
                // find children
                $rec($row->id);
                // find next root
                $rec($row->parent_id, $row->id);
            }
        }
    };
    $rec();

    return $accum;
}

// SELECT * FROM table ORDER BY parent_id, prev_id
$rows = $itemDAO->getItems();
$items = build_tree($rows);

I am terrible at recursion, so any suggestions on how to improve the code would be helpful.


texts: Checking for files that are mentioned as children of other files

texts:
I am working in JavaScript on a GruntFile script, and I am creating an object that holds a file class for each one of the following class structure:

class file = {
    path: string,
    name: string,
    children: string[],
    parents: string[],
    packages: string[]
}

I need to loop over each one of these files in the object, and for each one of the files loop over all of the other files and check if their children array contains the current file matching on name.

My coworker and I have come up with multiple solutions to this nasty business.

The first is a more "streamlined" approach, which is believed to "execute faster":

const fileArray = Object.keys(files).map( key => files[key]);
fileArray.forEach( fileOuter => fileArray.forEach( fileInner => { if ( fileInner.children.includes(fileOuter.name)) fileOuter.parents.push(fileInner.name) } ) );

The second solution is clearer:

// Loop over all files by key
Object.keys( files ).forEach( key => {

    // Get the current file name
    const curFileName = file.name;

    // Loop over all files again
    Object.keys(files).forEach( innerKey => {

        // Get the inner loop file
        const fileInner = files[innerKey];

        // If the file lists the current file as a dependency
        if ( fileInner.children.indexOf(curFileName) !== -1 ){

            // Push the file name into the parents array for the current file
            files[curFileName].parents.push(fileInner.name);
        }
    })
})

Or if we really wanted to make the loop as fast as possible:

// Get the object keys of the files object
const fileKeys = Object.keys(files);

// Loop over each file
for( var i=0, j=fileKeys.length; i<j; i++){

    // Get the current file name
    const curFileName = files[fileKeys[i]].name;

    // Loop over each file
    for( k=0, k<j, k++){

        // Get the inner file
        const fileInner = files[fileKeys[k]];

        // If the inner files children array matches the current file name, push the inner file name to the current files parents array
        if( fileInner.children.indexOf(curFileName) !== 1 ) files[curFileName].parents.push( fileInner.name );
    }
}

Is any of these methods objectively better than the other? Is there an even better approach we could be taking for this task?


texts: Compare result files from two different runs the smart way?

texts:
The program counts attributes of various (geo-)objects and prints them to different files.

One of the options compares two different datasets with each other.

parser.add_option("-c", "--compare datasets", dest="compare",
                  help="If you want to campare two datasets (from different years for example) set the c-flag to 1. Run both datasets\
                    one after the other. After the second run you will find a file named COMPARE_* in the output folder. The default\
                  behaviour is no comaprison.")

I am concerned about the behavior of my current implementation. The basic idea is to pickle a list of file names when the -c flag is set to 1. When the program is run for the second time with the -c flag it will load all file names needed for the comparison from the pickle file.

if options.compare == '1':
    # check if there is a pickle file
    p = glob.glob('%s/*.pikl' % data_output)
    if len(p) > 1:
        raise Exception('There are two pickle files. Comparison not possible.')
    elif len(p) == 1:
        pfiles_list = pickle.load(open(p[0],'rb'))
        if len(pfiles_list) == len(files_to_compare):
            for i,(f1,f2) in enumerate(zip(pfiles_list,files_to_compare)):
                print 'comparing files...'
                if i == 0:
                    csv_cmp_lazy(f1,f2, compare_file)
                else:
                    csv_cmp_lazy(f1,f2, compare_file, append_file = True)
            info_str = 'Deleting pickle file %s' % os.path.basename(p[0])
            print info_str
            logging.info(info_str)
            os.remove(p[0])
        else:
            raise ValueError('len of files current and last run are not equal: Number of file current run/last run: %s/%s' % (len(files_to_compare),len(pfiles_list))
    else:
        pickle.dump(files_to_compare, open(pikl_file,'wb'))

This implementation relies on a few assumptions:

that the pickle file won't be moved away from data_output
that os.remove(p[0]) will be successful

Not very secure, right? Besides, imagine the user finds an error in his data and wants to do the second run again: the comparison will fail because the pickle file won't be there anymore. This can be very annoying as the program may take longer than one hour to terminate (depending on input options and dataset).

Any suggestions on how to do this in a smarter way?


texts: Check if specific pattern exists in another array and save the index

texts:
Let's say I have this pattern and a large array:

String [] pattern = new String[]{"i","am","a", "pattern"};
String [] large_array = new String[]{"not","i","am","a", "pattern","pattern","i","am","a", "pattern", "whatever", "x", "y", i","am","a", "pattern",................, i","am","a", "pattern" ....};

As you can see the pattern appears multiple times in the array. The first time at index 1, the second time at index 6, etc...  I want to find out at which positions the pattern begins and return it in a collection (eg list).

In this case the position array is
1,6,13, etc...

Here is my current method:

private ArrayList<Integer> getStartPositionOfPattern(String[] headerArray, String[] pattern) {

    ArrayList<Integer> allPositions = new ArrayList<>();
    int idxP = 0, idxH = 0;
    int startPos = 0;
    while (idxH < headerArray.length) {
        if (pattern.length == 1) {
            if (pattern[0].equals(headerArray[idxH])) {
                allPositions.add(idxH);
            }
        } else {
            if (headerArray[idxH].equals(pattern[idxP])) {
                idxP++;
                if (idxP == pattern.length) { //you reached end of pattern
                    idxP = 0; //start Pattern from begining
                    allPositions.add(startPos); //you can save startPosition because pattern is finished
                }
            } else {
                idxP = 0;
                startPos = idxH + 1;
                if (pattern[idxP].equals(headerArray[idxH])) { //if current arrray.idxH is not pattern.idxP but array.idxH is begining of pattern
                    startPos = idxH;
                    idxP++;
                }
            }
        }

        idxH++;

    }
    return allPositions;
}

Is there a way to make my function more readable and faster? I believe it works correctly, but because the function is complex, I worry I might have an undetected bug.

NOTE: headerArray is the large array.


texts:
I'm writing Stringbuilder to file asynchronously. This code takes control of a file, writes a stream to it and releases it. It deals with requests from asynchronous operations, which may come in at any time.

The FilePath is set per class instances (so the lock Object is per instance), but there is potential for conflict since these classes may share FilePaths. That sort of conflict, as well as all other types from outside the class instance, would be dealt with with retries.

Is this code suitable for its purpose? Is there a better way to handle this that means less (or no) reliance on the catch and retry mechanic?

Also how do I avoid catching exceptions that have occurred for other reasons?

public string Filepath { get; set; }
private Object locker = new Object();

public async Task WriteToFile(StringBuilder text)
    {
        int timeOut = 100;
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        while (true)
        {
            try
            {
                //Wait for resource to be free
                lock (locker)
                {
                    using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                    using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                    {
                        writer.Write(text.ToString());
                    }
                }
                break;
            }
            catch
            {
                //File not available, conflict with other class instances or application
            }
            if (stopwatch.ElapsedMilliseconds > timeOut)
            {
                //Give up.
                break;
            }
            //Wait and Retry
            await Task.Delay(5);
        }
        stopwatch.Stop();
    }


texts: Implementation of a simple hash function

texts:
This is my implementation of a hash function described below. The (compiled) program can be run as follows:

$ java Hash1 < input.txt

The program reads a text file (of any size) with 8-digit student numbers on each line, splits each number into three numbers such that they have 3, 3 and 2 digits and then sums these numbers (e.g., for a student number 12345678, the hash is 123+456+78). Then, the hash is simply printed.

If the hash has already been used, the student number is reversed and the hash function is calculated from the reversed number (12345678 is reversed to 87654321 and the hash is 876+543+21). If this value has also been taken, it just prints "-1" and continues to the next value.

I use two external libraries for input and output:

edu.princeton.cs.algs4.stdin
edu.princeton.cs.algs4.stdout

The implementation:

public class Hash1 {

    // the main method reads student number and
    // gets the hash value. it outputs the hash
    // if it hasn't been used, reverse hash
    // or -1 if both hash values are taken
    public static void main(String[] args) {

        // the size is 2098 because the highest
        // hash (index) can be 999+999+99=2097
        String[] indexarray = new String[2098];

        while (!StdIn.isEmpty())
        {
            String key = StdIn.readLine();
            char[] charray =  key.toCharArray();
            int hash = hash(charray);

            if (indexarray[hash] != null) {
                int newhash = reverse_hash(charray);
                if (indexarray[newhash] != null) {
                    int errorFlag = -1;
                    StdOut.println(errorFlag);
                    }
                else {
                    indexarray[newhash] = key;
                    StdOut.println(newhash);
                    }
            }
            else {
                indexarray[hash] = key;
                StdOut.println(hash);
            }
        }
    }

    // this method performs the hash as specified
    // and returns the value of the hash
    private static int hash(char[] charray) {
        String[] numbers = {"", "", ""};

        for (int i = 0; i < charray.length; i++)
            if (i < 3)
                numbers[0] = numbers[0] + charray[i];
            else if (i >= 3 && i < 6)
                numbers[1] = numbers[1] + charray[i];
            else if (i >= 6 && i < 8)
                numbers[2] = numbers[2] + charray[i];

        int firstNumb = Integer.parseInt(numbers[0]);
        int secondNumb = Integer.parseInt(numbers[1]);
        int thirdNumb = Integer.parseInt(numbers[2]);
        int result = firstNumb + secondNumb + thirdNumb;

        return result;
    }

    // this method reverses the student number,
    // calls hash() method to hash the reversed
    // student number and returns the hash
    private static int reverse_hash(char[] charray) {
        char [] reverse = new char[charray.length];
        for (int i = 0; i < reverse.length; i++) {
            int index = reverse.length - i -1;
            reverse[i] = charray[index];
        }
        int hash = hash(reverse);
        return hash;
    }
    }

I am new to Java and would like to know how could I improve or optimize this program, if there are any issues with the code or I am using any bad (discouraged) practises etc.


texts: Fetching the total amount of SE reputation accumulated

texts:
Since I am new to R, I have pulled this code together in kind of a rag-tag way, but I am wondering, is there something similar to list comprehensions (in Python) I can use in R to make this simpler? Or a better way of doing this? I am trying to fetch the total amount of reputation a user has accumulated on Stack Exchange.  I am ideally looking for a way to remove the for loop and use the sum function on a subset of items (from the API response).

library(httr)
s = 0
for(i in content(GET(paste("http://api.stackexchange.com/users/",readline(),"/associated",sep="")))$items) {
  q=i$reputation
  if (q>101)
    s=s+q
}
print(s)

Sample input would be a user's id, like 10400443.


texts:
I've got a CSV that contains users and permissions in the below format, where users can have as little as one or as many as eight different permissions:

USER,PERM1,PERM2,PERM3,PERM4,PERM5,PERM6,PERM7,PERM8
jdoe,perm1,perm2
tsmith,perm1,perm2,perm3,perm4,perm5,perm6,perm7,perm8

This is the desired format, with each unique user and permission pair on a new line:

USER,PERM
jdoe,perm1
jdoe,perm2
tsmith,perm1
tsmith,perm2
tsmith,perm3
tsmith,perm4
tsmith,perm5
tsmith,perm6
tsmith,perm7
tsmith,perm8

My script below accomplishes this, but it's ugly, repetitive and I know there's a more Pythonic way to do it. Even worse, I had to bring the output file into Excel afterwards to filter and delete the rows with blank PERM values. Any recommendations to shorten this code and cut down on repetition would be much appreciated.

import csv

def reformat_ul(original_ul, formated_ul):
    with open(original_ul) as user_list:
        dict_reader = csv.DictReader(user_list)
        ul = []
        for row in dict_reader:
            ul.append(row)

    with open(formated_ul, 'w') as output2:
        output2.write('USER,PERM\n')
        for uperm in ul:
            p1 = '{},{}\n'.format(uperm['USER'], uperm['PERM1'])
            p2 = '{},{}\n'.format(uperm['USER'], uperm['PERM2'])
            p3 = '{},{}\n'.format(uperm['USER'], uperm['PERM3'])
            p4 = '{},{}\n'.format(uperm['USER'], uperm['PERM4'])
            p5 = '{},{}\n'.format(uperm['USER'], uperm['PERM5'])
            p6 = '{},{}\n'.format(uperm['USER'], uperm['PERM6'])
            p7 = '{},{}\n'.format(uperm['USER'], uperm['PERM7'])
            p8 = '{},{}\n'.format(uperm['USER'], uperm['PERM8'])
            output2.write(p1)
            output2.write(p2)
            output2.write(p3)
            output2.write(p4)
            output2.write(p5)
            output2.write(p6)
            output2.write(p7)
            output2.write(p8)

reformat_ul('user_list.csv', 'output.txt')


texts:
This is a Python script for counting the lines of a compressed file:

#!/usr/bin/env python3

import gzip, bz2, zipfile, os, sys

def openZip(zfile):
    f = zipfile.ZipFile(zfile)
    firstFile = f.filelist[0].filename
    if firstFile.endswith("/"):
        raise Exception("This zip file contains a directory.")
    return f.open(firstFile)

class compressedFile:
    fileOpenerDict = {".gz":gzip.open, ".bz2":bz2.open, ".zip":openZip}

    def __init__(self, pFilePath):
        self.filePath = os.path.abspath(pFilePath)
        self.fileStem, self.ext = os.path.splitext(self.filePath)
        self.ext = self.ext.lower()
        try:
            self.fileOpener = self.fileOpenerDict[self.ext]
        except KeyError:
            print("Only gz, zip, and bz2 files allowed.")
            exit(1)

    def countLines(self):
        nLines = 0
        with self.fileOpener(self.filePath) as fh:
            for line in fh:
                nLines = nLines + 1
        return nLines

if __name__ == "__main__":
    c = compressedFile(sys.argv[1])
    n = c.countLines()
    print("N lines: %d" % n)


texts:
I was given a this problem at a technical interview and failed miserably in the time given. Afterwards, I sat down and worked out what I think is a good solution. The task was actually to build an AngularJS app to do this, which I did, but the guts of my solution is in JavaScript. I wanted to ask if there is a better way to do this:

// convert strings to LC for case insensitivity
// split strings into arrays
// sort the arrays (spaces will sort first and be trimmed later)
// join the arrays back into strings
// we're only concerned about the printable characters in the anagram so,
// trim() to remove any spaces and then compare the resulting strings
var str1 = this.word1.toLowerCase().split('').sort().join('').trim();
var str2 = this.word2.toLowerCase().split('').sort().join('').trim();

if (str1 === str2) {
    this.isAnagram = true;
} else {
    this.isAnagram = false;
}


texts: Validity of macro for printf() call in a corporate environment

texts:
I wrote this program:

#include <stdio.h>
#define printS for(i=0;s[i];i++){printf("%c",s[i]);}

int i;
char s[] = "Hello World!\n";

void main()
{
  printS;
}

It outputs exactly what I want it to but I have no clue if this would be acceptable to use if I were working for a company.

Would this be considered a poorly written piece of code in a corporate environment?


texts: Runtime compiler for getting/setting runtime property values

texts:
I've been playing about with runtime compilation to allow me to get/set runtime property values in C#, and so far I have come up with a class.

This allows me to write code like the following which works well and is much faster than standard reflection:

TypeWrapper wrapper = new TypeWrapper(target);
wrapper.Set("Value", "abc");
return (string)wrapper.Get("Value");

What I'm wondering is whether there is a way to make this even faster. I could go into metaprogramming and use Reflection.Emit,  but that adds a vastly increased order of complexity for other developers to follow.

Is there something obvious you can see?

Here's the current benchmarks using Benchmark.NET:

Total time: 00:01:47 (107.64 sec)

// * Summary *

BenchmarkDotNet=v0.9.4.0
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Xeon(R) CPU E5-1650 0 @ 3.20GHz, ProcessorCount=12
Frequency=3117484 ticks, Resolution=320.7715 ns, Timer=TSC
HostCLR=MS.NET 4.0.30319.42000, Arch=32-bit RELEASE
JitModules=clrjit-v4.6.1063.1

                     Method |      Median |     StdDev | Scaled |
--------------------------- |------------ |----------- |------- |
               1. Static C# |   2.5401 ns |  0.6457 ns |   1.00 |
              2. Dynamic C# |  35.1664 ns |  0.4643 ns |  13.84 |
            3. PropertyInfo | 430.8785 ns |  6.4399 ns | 169.63 |
      4. PropertyDescriptor | 920.3483 ns | 59.1531 ns | 362.32 |
             5. TypeWrapper | 117.0505 ns |  1.6790 ns |  46.08 |

// ***** BenchmarkRunner: End *****

1. Static C#: 2.54 ns
2. Dynamic C#: 35.17 ns
3. PropertyInfo: 430.88 ns
4. PropertyDescriptor: 920.35 ns
5. TypeWrapper: 117.05 ns

And the class itself:

public class TypeWrapper
{
    private readonly dynamic dyn;
    private readonly Dictionary<string, CallSite<Action<CallSite, object, object>>> setters
        = new Dictionary<string, CallSite<Action<CallSite, object, object>>>();

    private readonly Dictionary<string, CallSite<Func<CallSite, object, object>>> getters
        = new Dictionary<string, CallSite<Func<CallSite, object, object>>>();

    public TypeWrapper(object d)
    {
        this.dyn = d;
        Type type = d.GetType();
        foreach (var p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            string name = p.Name;
            CallSite<Action<CallSite, object, object>> set = CallSite<Action<CallSite, object, object>>.Create(
            Microsoft.CSharp.RuntimeBinder.Binder.SetMember(
                CSharpBinderFlags.None,
                name,
                type,
                new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) ,
                        CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));

            this.setters.Add(name, set);

            CallSite<Func<CallSite, object, object>> get = CallSite<Func<CallSite, object, object>>.Create(
            Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
                CSharpBinderFlags.None,
                name,
                type,
                new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));

            this.getters.Add(name, get);
        }
    }

    public void Set(string name, object value)
    {
        var set = this.setters[name];
        set.Target(set, this.dyn, value);
    }

    public object Get(string name)
    {
        var get = this.getters[name];
        return get.Target(get, this.dyn);
    }
}


texts: Role-Playing Game CMS, how can I make this better?

texts:
I am pretty new to Laravel and I have been coding a CMS for a roleplay game, and I have ran in to some code which I see as messy / bad practice, I was just wondering is this really the easiest and best way to do it? What I am mainly looking for is the best practice for doing this in the best possible way without changing too much of my code.

So what I need to do is I need to pass the users business and the users business position to the business overview view/page. I have modals for each of the tables for Business and BusinessPositions which I will post below.

Businesses:

<?php
namespace App\Database\Website\Roleplay\Business;

use Eloquent;

class Businesses extends Eloquent
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_businesses';
    public $timestamps      = false;
    protected $fillable     = [];

    public function positions()
    {
      return $this->hasMany('App\Database\Roleplay\Business\BusinessPositions', 'business_id');
    }

    public function founder()
    {
      return $this->belongsTo('App\Database\Website\User\Player');
    }
}

BusinessPositions:

<?php
namespace App\Database\Website\Roleplay\Business;

use Eloquent;

class BusinessPositions extends Eloquent
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_business_positions';
    public $timestamps      = false;
    protected $fillable     = [];
}

And here is the controller function for sending my view

$businesses = Cache::remember('overview.businesses', 1, function() {
    return Businesses::get();
});

$businessPositions = Cache::remember('overview.business.positions', 1, function() {
    return BusinessPositions::get();
});

$acceptedCount = $businesses->where('business_owner_id', '=', Auth::user()->id)
    ->where('business_status', '=', 'accepted')
    ->count();
$pendingCount = $businesses->where('business_owner_id', '=', Auth::user()->id)
    ->where('business_status', '=', 'pending')
    ->count();
$myBusiness = Businesses::find(Auth::user()
    ->roleplay->business_id);
$myBusinessPosition = $businessPositions->where('business_id', '=', $myBusiness->business_id)
    ->where('position_id', '=', Auth::user()->roleplay->business_position)
    ->first();

return view('frontend.business.overview', compact('acceptedCount', 'pendingCount', 'myBusiness', 'myBusinessPosition'));

The part I see as messy is the way I get the business position, and maybe there is a way to get the business better?

How I get the business position (breakdown of code)

$myBusinessPosition = $businessPositions->where('business_id', '=', $myBusiness->business_id)
    ->where('position_id', '=', Auth::user()
        ->roleplay->business_position)
    ->first();

I am using Laravel 5.3, Thanks.


texts: Java-Helper library for compressing (zipping) files

texts:
I'm writing a Java-Helper library. I want to include a method to zip files together, and this is what I've come up with. I'm using the java.util.zip.* library (ZipOutputStream and ZipEntry specifically).

/**
* This uses the java.util.zip library to zip the given files to the given destination.
*
* @param destination
* @param files
* @throws FileNotFoundException
* @throws IOException
*/
public static void zipFiles(File destination, File... files) throws FileNotFoundException, IOException {
  try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destination))) {
    byte[] buffer = new byte[1024];
    for (int i = 0; i < files.length; i++) {
      try (FileInputStream in = new FileInputStream(files[i])) {
        out.putNextEntry(new ZipEntry(files[i].getName()));

        // Transfer bytes from the file to the ZIP file
        int length;
        while ((length = in.read(buffer)) > 0) {
          out.write(buffer, 0, length);
        }

        // Complete the entry
        out.closeEntry();
      }
    }
  }
}

Any pointers?

Also, from the code, is this a good buffer size?

byte[] buffer = new byte[1024];

I've seen a lot of disks with a blocksize of 512 KB. Would that be a more "optimal" size?


texts:
I have Winform application and I want to separate the button click event from the main form.

My application has Add button which adds files into my Listbox and until now all my code was inside this button click event and caused my code to look complicated.
So I created this class:

public class ListboxFile
{
    public delegate void OnFileAdd(string file);
    public event OnFileAdd OnFileAddEvent;
    private static List<string> _files;

    public ListboxFile()
    {
        _files = new List<string>();
    }

    public void add(string file)
    {
        _files.Add(file);
        OnFileAddEvent(file);
    }

    public void remove(string file)
    {
        if (_files.Contains(file))
        {
            _files.Remove(file);
        }
    }

    public void clear()
    {
        _files.Clear();
    }

    public List<string> list
    {
        get { return _files; }
    }
}

in the constructor I am initiate my List and each file that comes and add to my List raise an event and from the main form this file also add to my Listbox

this is the event from the main form that responsible to add the file into the Listbox:

private void lbf_OnFileAddEvent(string file)
{
    if (InvokeRequired)
    {
        this.Invoke((MethodInvoker)delegate
        {
            listBoxFiles.Items.Add(file);
        });
    }
    else
    {
        listBoxFiles.Items.Add(file);
    }
}

and this is the Add button click that takes the files that the user chooses to add:

    private void btnAddfiles_Click(object sender, EventArgs e)
    {
        string fileToAdd = string.Empty;
        System.IO.Stream stream;
        OpenFileDialog thisDialog = new OpenFileDialog();
        thisDialog.InitialDirectory = (lastPath.Length > 0 ? lastPath : "c:\\");
        thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net, *.pcapng, *.5vw, *.bfr, *.erf, *.tr1)" +
            "|*.snoop; *.pcap; *.cap; *.net; *.pcapng; *.5vw; *.bfr; *.erf; *.tr1|" + "All files (*.*)|*.*";
        thisDialog.FilterIndex = 1;
        thisDialog.RestoreDirectory = false;
        thisDialog.Multiselect = true;
        thisDialog.Title = "Please Select Source File";

        if (thisDialog.ShowDialog() == DialogResult.OK)
        {
            if (thisDialog.FileNames.Length > 0)
            {
                lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
            }

            ListboxFile lbf = new ListboxFile();
            lbf.OnFileAddEvent += lbf_OnFileAddEvent;
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.DoWork +=
            (s3, e3) =>
            {
                foreach (String file in thisDialog.FileNames)
                {
                    try
                    {
                        if ((stream = thisDialog.OpenFile()) != null)
                        {
                            int numberOfFiles = thisDialog.SafeFileNames.Length;
                            using (stream)
                            {
                                lbf.add(file); //add the file
                                lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
                            }
                        }
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    }
                }
            };

            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                (s3, e3) =>
                {
                    updateUi("bla bla"); //update the gui
                });

            backgroundWorker.RunWorkerAsync();
        }
    }

Would love to hear comments about this design since I am new developer.


texts: How to write efficient javascript/jQuery code involving loops and string concat?

texts:
I am using kendo grid's onDataBound event to do something.  Here's my jQuery code:

console.time('withoutnot');
jQuery(e.sender.dataSource._data).each(function (i, v) {
     if (v.IsReadonly) {
         e.sender.wrapper.find("tr[data-uid='" + v.uid + "'] .k-button")
                .each(function (i, j) {
                    if (!jQuery(this).hasClass('k-grid-edit') && !jQuery(this).hasClass('k-grid-Desc')) {
                        jQuery(this).addClass('k-state-disabled').prop('disabled', true)
                                .prop('title', 'Readonly.');
                    }
                });
    }
});
console.timeEnd('withoutnot');

onDataBound event gets raised once the grid has completed data-load from serverside.

My problem is that, because of 400 rows in the grid (without paging), it takes around 355ms to 378ms, which is still slower for me, because it causes visible performance lag in the grids load(readonly button effect).

How can I improve this code snippet even more? or is it the best I can go for?

NOTE: using native for or jQuerys :not (instead of those if conditions), proved disaster to me, load time scaled to 460ms to 550ms.

I am using jQuery 1.7.1


texts: A value set data structure for rapid statistics queries in Java - follow-up

texts:
(See the previous iteration.)

Now all operations of the data structure work in exact constant time, yet it came with the price: the state of this set maybe non-sensical. A user may end up with the set with negative number of elements in it. Basically, the client programmer must keep track of how he/she work with this set.

StatisticsNumberSet.java

package net.coderodde.stat;

/**
 * This class provides the means for rapid statistics queries.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.618 (Mar 28, 2017)
 */
public class StatisticsNumberSet {

    /**
     * Holds the sum of all elements in this set.
     */
    private double sum;

    /**
     * Holds the sum of square of each element in this set.
     */
    private double squareSum;

    /**
     * Holds the number of elements currently in this set.
     */
    private int size;

    /**
     * Adds the given number to this set.
     *
     * @param number the number to add.
     */
    public void add(double number) {
        checkNumberIsFinite(number);
        sum += number;
        squareSum += number * number;
        size++;
    }

    /**
     * Converts and adds the given number to this set.
     *
     * @param number the number to add.
     */
    public void add(Number number) {
        add(number.doubleValue());
    }

    /**
     * Removes the given number from this set.
     *
     * @param number the number to remove.
     */
    public void remove(double number) {
        checkNumberIsFinite(number);
        sum -= number;
        squareSum -= number * number;
        size--;
    }

    /**
     * Converts and removes the given number from this set.
     *
     * @param number the number to remove.
     */
    public void remove(Number number) {
        remove(number.doubleValue());
    }

    /**
     * Resets the state of this set to an empty set.
     */
    public void clear() {
        sum = 0.0;
        squareSum = 0.0;
        size = 0;
    }

    /**
     * Returns the number of elements in this set.
     *
     * @return the size of this set.
     */
    public int size() {
        return size;
    }

    /**
     * Computes the average of this set.
     *
     * @return the average.
     */
    public double getAverage() {
        return sum / size;
    }

    /**
     * Computes the variance of this set.
     *
     * @return the variance.
     */
    public double getVariance() {
        double step1 = squareSum - sum * sum / size;
        return step1 / (size - 1);
    }

    /**
     * Computes the standard deviation of this set.
     *
     * @return the standard deviation.
     */
    public strictfp double getStandardDeviation() {
        return Math.sqrt(getVariance());
    }

    /**
     * Returns the textual representation of the state of this set.
     *
     * @return the textual representation.
     */
    @Override
    public String toString() {
        return "[Size = " + size + ", average = " + getAverage() +
               ", s.d. = " + getStandardDeviation() + ", variance = " +
                getVariance() + "]";
    }

    public static void main(String[] args) {
        StatisticsNumberSet set = new StatisticsNumberSet();

        set.add(1);
        set.add(1.0f);
        set.add((byte) 3);

        System.out.println(set);

        set.remove(1.0f);

        System.out.println(set);

        set.clear();

        System.out.println(set);
    }

    private void checkNumberIsFinite(double number) {
        if (Double.isNaN(number)) {
            throw new IllegalArgumentException("number is NaN");
        }

        if (Double.isInfinite(number)) {
            throw new IllegalArgumentException("number is +Inf or -Inf");
        }
    }
}

As always, any critique is much appreciated.


texts:
https://leetcode.com/problems/house-robber-ii/

  You are a professional robber planning to rob houses along a street.
  Each house has a certain amount of money stashed. All houses at this
  place are arranged in a circle. That means the first house is the
  neighbor of the last one. Meanwhile, adjacent houses have security
  system connected and it will automatically contact the police if two
  adjacent houses were broken into on the same night.

  Given a list of non-negative integers representing the amount of money
  of each house, determine the maximum amount of money you can rob
  tonight without alerting the police.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.
Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CirucularArray
{
    /// <summary>
    /// google interview
    /// https://www.geeksforgeeks.org/maximum-sum-in-circular-array-such-that-no-two-elements-are-adjacent/
    /// https://leetcode.com/problems/house-robber-ii/
    /// </summary>
    [TestClass]
    public class MaximumSumCircularArrayNo2ElementsAreAdjacent
    {
        [TestMethod]
        public void RobberTestEvenArray()
        {
            int[] arr = {1, 2, 3, 4, 5, 1};
            int result = Rob(arr);
            Assert.AreEqual(9, result);

        }
        [TestMethod]
        public void RobberTestOddArray()
        {
            int[] arr = { 5, 1, 2, 10 ,5 };
            int result = Rob(arr);
            Assert.AreEqual(15, result);

        }

        [TestMethod]
        public void TestMethodOneItem()
        {
            int[] arr = {1 };
            int result = Rob(arr);
            Assert.AreEqual(1, result);
        }

        public int Rob(int[] nums)
        {
            if (nums == null || nums.Length == 0)
            {
                return 0;
            }

            if (nums.Length == 1)
            {
                return nums[0];
            }

            return Math.Max(Helper(0, nums.Length - 2,nums), Helper(1, nums.Length - 1,nums));
        }

        private int Helper(int start, int end, int[] nums)
        {
            int prevMax = 0;
            int currMax = 0;
            for (int i = start; i <= end; i++)
            {
                int temp = currMax;
                currMax = Math.Max(prevMax + nums[i], currMax);
                prevMax = temp;
            }

            return currMax;
        }
    }
}


texts: Converts a user inputed string into a Integer

texts:
Just a little exercise to make me more affluent with strings and error handling, any improvements welcome!

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <math.h>

#define MAXSIZE 1024

void retreiveStringInput(char *str, size_t buffersize)
{
    for (;;) {
        if (fgets(str, buffersize, stdin) != NULL) {
            str[strcspn(str, "\n")] = 0;
            return;
        }
        else
            printf("Touble allocating memory, Please try again...\n");
    }
}

bool strHasAllDigits(char *str)
{
    size_t strsize = strlen(str);
    if (str[0] != 0) {
        for (size_t strIndex = 0; strIndex < strsize; ++strIndex) {
            if (isdigit(str[strIndex]))
                continue;
            else
                return false;
        }
        return true;
    }
    else {
        printf("String is empty...\n");
        return false;
    }
}

int strToInt(char str[])
{
    size_t len = strlen(str);
    size_t power = len - 1;
    int convertedString = 0;
    for (size_t strIndex = 0; strIndex < len; ++strIndex, --power) {
        convertedString += ((int)(str[strIndex] - '0') * pow(10,power));
    }
    return convertedString;
}

int main()
{
    char number[MAXSIZE];
    int intNumber = 0;
    for (;;) {
        printf("ENTER A WHOLE NUMBER: ");
        retreiveStringInput(number, MAXSIZE);
        if (strHasAllDigits(number))
            intNumber = strToInt(number);
        else {
            printf("Number must be a whole number containing no characters, please try again...\n\n");
            continue;
        }
        printf("Your number is: %d\n", intNumber);
        break;
    }

    printf("Press any key to continue...");
    getchar();
}


texts:
Description

  You are most likely familiar with the game 2048.

  2048 is played on a gray 4 × 4 grid with numbered tiles that slide smoothly when a player moves them using one of the four arrow keys -  Up ,  Down ,  Left  or  Right . On every turn, a new tile with a value of either 2 or 4 randomly appears on an empty spot of the board. After one of the keys is pressed, the tiles slide as far as possible in the chosen direction until they are stopped either by another tile or by the edge of the grid. If two tiles with the same number collide while moving, they merge into a tile with this number doubled. You can't merge an already merged tile in the same turn. If there are more than 2 tiles in the same row (column) that can merge, the farthest (closest to an edge) pair will be merged first (see the second example).

  In this problem you are not going to solve the 2048 puzzle, but you are going to find the final state of the board from the given one after a defined set of n arrow key presses, assuming that no new random tiles will appear on the empty spots.

  The following example shows the next state of the board after pressing Right.

  You are given a matrix 4 × 4 which corresponds to the 2048 game grid. grid[0][0] corresponds to the upper left tile of the grid. Each element of the grid is equal to some power of 2 if there is a tile with that value in the corresponding position, and 0 if it corresponds to the empty spot.
  You are also given a sequence of key presses as a string path. Each character of the string equals L, R, U, or D corresponding to  Left ,  Right ,  Up  or  Down  respectively.

  Please note that in some cases after pressing an arrow key nothing will be changed.

Example

For

grid = [[0, 0, 0, 0],
        [0, 0, 2, 2],
        [0, 0, 2, 4],
        [2, 2, 4, 8]]

and path = "RR"

the output should be

game2048(grid, path) = [[0, 0, 0, 0],
                        [0, 0, 0, 4],
                        [0, 0, 2, 4],
                        [0, 0, 8, 8]]

Code

def merge(row, left_or_down):
    i, new_row = 0, []
    transposed = [e for e in row if e]

    if not left_or_down:
        transposed = transposed[::-1]

    while i < len(transposed):
        if i == len(transposed) - 1:
            new_row += [transposed[i]]
            break
        if transposed[i] == transposed[i + 1]:
            new_row += [2 * transposed[i]]
            i += 2
        else:
            new_row += [transposed[i]]
            i += 1

    if not left_or_down:
        new_row = [0]*(4 - len(new_row)) + new_row[::-1]

    return  new_row + [0]*(4 - len(new_row))

def game2048(grid, path):
    for direc in path:

        if direc in 'LR':
            grid = [merge(row, direc == 'L') for row in grid]

        if direc in 'UD':
            grid = [merge(row[::-1], direc == 'D') for row in zip(*grid)]
            grid = [row for row in zip(*grid)][::-1]

    return grid


texts: Breadth-first search on a tree in Python

texts:
The following code performs breadth first search on a mockup tree

# some tree
#             A            - LAYER 0
#         B       C        - LAYER 1
#      D     E             - LAYER 2
#   F                      - LAYER 3

def get_something(x):
    if x == 'a':
        return ['b', 'c']
    if x == 'b':
        return ['d', 'e']
    if x == 'c':
        return []
    if x == 'd':
        return ['f']
    if x == 'e':
        return []
    if x == 'f':
        return []

and it is traversed by the following not so beautiful code

# I mean it works, but looking at it makes me feel sick

def recursive_get(x, loop_limit, count_limit):

    # stop condition 1: loop limit exceeded and nonzero
    # stop condition 2: count limit exceeded and nonzero
    # stop condition 3: we have reached the bottom

    current = 0
    seen_list = []
    todo_list = [x]

    while ((current < loop_limit or loop_limit == 0) and
           (len(seen_list) < count_limit or count_limit == 0) and
           todo_list):

        result = get_something(todo_list.pop(0))
        seen_list.extend(result)
        todo_list.extend(result)
        current += 1

    return seen_list

Is there any syntactic sugar to get the second part to look more sexy? (less lines, syntactically nicer looking)?


texts: string.To2DCharArray extension method implementation

texts:
I would like to ask a code review for the class below.

I am asking this because VS showed a quite low Maintainability Index of 54 and I am wondering if it is good code.

I know I could have extracted some parts of the long method to smaller private methods (or local methods but that would not help a lot I think), but I think in case of extension method classes it is better to stick with the one method - one extension concept.

What do you think? (Any feedback is highly appreciated!)

using System;

namespace GridPathFinder.Utilities
{
    public static class StringExtensions
    {
        /// <summary>
        ///     Converts the string to a 2 dimensional char array (<see cref="char[,]"/>),
        ///     finding new lines based on the <see cref="Environment.NewLine"/> value.
        /// </summary>
        /// <param name="input">The input string to convert.</param>
        /// <returns>
        ///     A <see cref="char[,]"/> where dimension 0 indicates rows, dimension 1 indicates columns.
        /// </returns>
        public static char[,] To2DCharArray(
            this string input,
            StringSplitOptions stringSplitOptions = StringSplitOptions.RemoveEmptyEntries)
        {
            return To2DCharArray(input, new string[] { Environment.NewLine }, stringSplitOptions);
        }

        /// <summary>
        ///     Converts the string to a 2 dimensional char array (<see cref="char[,]"/>),
        ///     finding new lines based on the <paramref name="separators"/> given.
        /// </summary>
        /// <param name="input">The input string to convert.</param>
        /// <param name="separators">Array of separator strings</param>
        /// <returns>
        ///     A <see cref="char[,]"/> where dimension 0 indicates rows, dimension 1 indicates columns.
        /// </returns>
        public static char[,] To2DCharArray(
            this string input,
            string[] separators,
            StringSplitOptions stringSplitOptions = StringSplitOptions.RemoveEmptyEntries)
        {
            if (input == null)
                throw new ArgumentNullException(nameof(input));
            if (input == string.Empty)
                throw new ArgumentException($"{nameof(input)} cannot be empty.");
            if (separators == null)
                throw new ArgumentNullException(nameof(separators));
            if (separators.Length == 0)
                throw new ArgumentException($"{nameof(separators)} array has to contain at least one separator string.");

            string[] inputLines = input.Split(separators, stringSplitOptions);

            int widthOfFirstLine = inputLines[0].Length;
            char[,] array = new char[inputLines.Length, widthOfFirstLine];

            for (int row = 0; row < inputLines.Length; row++)
            {
                if (inputLines[row].Length != widthOfFirstLine)
                {
                    throw new ArgumentException($"{nameof(input)}'s all rows has to be equal in width," +
                        $"but the width of row with index {row} differs from the width of first row.");
                }

                for (int col = 0; col < inputLines[row].Length; col++)
                {
                    array[row, col] = inputLines[row][col];
                }
            }

            return array;
        }
    }
}
```


texts: Evaluating an expression with integers, +, and *, as well as -, / - revision 3

texts:
The original question came from this web site.

Revision 1

Revision 2

And this is the third revision. I delete spaces and validate an equation before computing.

public class Main {

    private static final String EQUATION_REGEX = "^-?\\d+((\\/|\\*|\\+|-)\\d+)*$";

    // http://www.careercup.com/question?id=4911380140392448
    public static void main(String[] args) {
        String equationWithAllSigns = "-1 * 5 * 4/2 - 8*9 - 16+1";

        // Delete spaces
        equationWithAllSigns = equationWithAllSigns.replaceAll("\\s+", "");

        // Compute the equation if it's valid
        if (equationWithAllSigns.matches(EQUATION_REGEX)) {
            double allSignsResult = computeWithAllOperations(equationWithAllSigns);
            System.out.println(allSignsResult);
        } else {
            System.out.println("Invalid equation");
        }
    }

    private static double computeWithAllOperations(String input) {
        double result = 0.0;
        /*
         * 1. Replace - with +- except the minus which is the first symbol of
         * the input.
         * 2. Split the input string by +
         * 3. Calculate the products and quotients
         * 4. Sum up the results
         */

        // (\\d)- is used instead of - to support strings starting with -
        String parts[] = input.replaceAll("(\\d)-", "$1+-").split("\\+");
        for (String part : parts) {
            result += computeMultAndDivision(part);
        }
        return result;
    }

    private static double computeMultAndDivision(String part) {
        String[] parts = part.split("(?=[/*])|(?<=[/*])");
        double result = Double.parseDouble(parts[0]);
        for (int i = 1; i < parts.length; i += 2) {
            String op = parts[i];
            double val = Double.parseDouble(parts[i + 1]);
            switch (op) {
            case "*":
                result *= val;
                break;
            case "/":
                result /= val;
                break;
            }
        }
        return result;
    }
}


texts: Base converting with strings from bases 1 to 36 to bases 1 to 36

texts:
I'm writing a fastest-code challenge over at PPCG relating to base conversion of bases 1 to 36, and as a part of the process for writing the competition, I decided to write my own program for it. This is the code I wish to be reviewed:

public class BaseConv {

    // Disallow instantiation
    private BaseConv() {
    }

    // Base setup
    private static final String BASEINFO = "0123456789abcdefghijklmnopqrstuvwxyz";

    /**
     * Converts a string as though it was an integer in base "fromBase" to base
     * "toBase".
     *
     * @param toConvert
     *            The string to convert bases from.
     * @param startbase
     *            The base to convert from. Must be less than 37 and greater
     *            than 1.
     * @param endbase
     *            The base to convert to. Must be less than 37 and greater than
     *            1.
     * @return converted The converted integer as type String.
     */
    public static String convBase(String toConvert, int fromBase, int toBase) throws NumberFormatException {
        if (toBase > 36 | fromBase > 36 | toBase < 2 | fromBase < 2) {
            throw new NumberFormatException("Bases specified must be less than 36 and greater than 2.");
        }
        String converted = "", thisBase = BASEINFO.substring(0, fromBase);
        char[] argument = toConvert.toCharArray(), baseinfochar = BASEINFO.toCharArray();
        int sum = 0, i = argument.length, multi = 1, baseind;
        for (; i > 0; multi *= fromBase) {
            baseind = thisBase.indexOf(argument[--i]);
                    if (baseind == -1)
                        throw new NumberFormatException("Character " + argument[i] + " is not a valid number in base " + toBase);
                    else
                        sum += multi * baseind;
        }
        multi = (int) (Math.log(sum) / Math.log(toBase));
        for (i = multi, multi = 1; i > 0; i--)
            multi *= toBase;
        for (; multi >= 1; sum %= multi, multi /= toBase) {
            converted += baseinfochar[sum / multi];
        }
        return converted;
    }
}

I wish to make sure that this code, with its current algorithm, is in the fastest setup possible, as well as being "proper" code (I plan on using this for more formal stuff later).

The current algorithm goes something like this:

The code checks to make sure that it's not attempting to exceed the bounds for possible base conversions.
The code creates its own String and char[] variables from the first Base String, limiting the string to what the input fromBase base is (needn't change the char array size, since we use that specifically for output and it will never go over the specified output base).
The code generates a sum of the numbers by multiplying according to their respective powers of the base.
Calculates the log base toBase of the sum in order to find the largest power that it will be finding (to get rid of fluff).
It then divides the sum by the respective power of the sought base, finding the indexes of the 'BASEINFO' (as a char array for the slightest speed increase) that align with them, and enacting a modulo on the sum to reduce its size.

Note:  The PPCG challenge explicitly forbids the use of built-in base conversion methods.


texts:
I have a string, where I am only interested in getting the numbers encapsulated in single quotes.

For instance if I have the string "hsa456456 ['1', '2', ...]

I only want the 1 and the 2 and whatever numbers follow

To do this, I have the following code:

import re

#pattern = re.compile("dog")
#l = re.findall(pattern, "dog dog dog")

#valuepattern=re.compile('\'\d{1,6}\'')
valuepattern = re.compile('\'\d+\'')
li = []
s = "hsa04012 [[['7039', '1956', '1398', '25'], ['7039', '1956', '1399', '25']], [['1839', '1956', '1398', '25'], ['1839', '1956', '1399', '25']], [['1399', '25']], [['1398', '25']], [['727738', '1956', '1398', '25'], ['727738', '1956', '1399', '25']], [['1956', '1398', '25'], ['1956', '1399', '25']], [['1950', '1956', '1398', '25'], ['1950', '1956', '1399', '25']], [['374', '1956', '1398', '25'], ['374', '1956', '1399', '25']], [['2069', '1956', '1398', '25'], ['2069', '1956', '1399', '25']], [['685', '1956', '1398', '25'], ['685', '1956', '1399', '25']]]"

#if match:
#    print match.group()
#else:
#    print "no match"

l = re.findall(valuepattern, s)
#print l

for item in l:
    li.append(item.strip("'"))
    #print item

for item in li:
    print item

My areas of interest is to minimize the number of lists. Right now, I use two l and li. I take the item from l and append it to li after stripping. I was curious if there was a way to accomplish this operation all within one list... without the need for li and then appending.


texts: Copying a Dictionary and Replace its Values

texts:
I have a custom dictionary where the values are numpy arrays. I would like to have a convenience function that creates a copy of its content except that the values are changed. If no value is passed, then the default None is assigned to the keys, else a value is set. The function can also work with a callable function, and then the resulting value is obtained by passing the length of the numpy arrays.

Inspired by what I found here, this is what I have so far:

import sys
import numpy as np

class CustomDict(dict):

    def strip(self, value=None):

        if callable(value):
            tmp = dict.fromkeys(self.keys())
            for k,v in self.items():
                tmp[k] = value(len(v))
            return tmp

        return dict.fromkeys(self.keys(), value)

def main(argv=()):

    tmp1 = CustomDict()

    tmp1['n1'] = np.array([[3]])
    tmp1['l2'] = np.array([[ 0,  4],
                            [ 4,  5],
                            [57,  3]])
    tmp1['t3x'] = np.array([[188, 401, 400],
                           [188, 187, 401],
                           [187, 205, 401],
                           [324, 306, 417],
                           [306, 305, 417],
                           [305, 416, 417]])

    # replace values
    print(tmp1.strip(1))

    # replace values with a callable function that gets the size of the array
    print(tmp1.strip(lambda x: [None]*x))

    return 0

if __name__ == "__main__":
    sys.exit(main())

This code outputs:

{'l2': 1, 'n1': 1, 't3x': 1}
{'l2': [None, None, None], 'n1': [None], 't3x': [None, None, None, None, None, None]}

It's all good, it works. But I'm not sure the part that tackles the callable function is the most efficient one, as I am creating the copy of the dictionary first, and then I'm replacing the values with another loop. Can this be done in a single pass?


texts:
I find myself using this bit of code very often when I am retrieving the results from a Cursor

SearchItem searchItem = new SearchItem();
searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));

Specifically this could be when I am using a CursorAdapter for a ListView and in a DAO object.

What would be a useful design pattern to use in this case?

My first instinct is to have a singleton class which does this. Are there any problems in taking this route?


texts:
I have a working code (below) to convert a number to Excel-like (A...Z AA...AZ BA...BZ ...ZA-ZZ) column codes (headers).

For simplicity I limited it to 1 or 2 character codes.

Can the algorithm be streamlined by using a bit more of elementary math or using it differently?

Please note that I just happened to need it in JavaScript (so I wrote it in JS) and am not looking for pure code improvements.

function numberToLetters(nNum) {
    var result;
    if (nNum <= 26) {
        result = letter(nNum);
    } else {
        var modulo = nNum % 26;
        var quotient = Math.floor(nNum / 26);
        if (modulo === 0) {
            result = letter(quotient - 1) + letter(26);
        } else {
            result = letter(quotient) + letter(modulo);
        }
    }

    return result;
}

function letter(nNum) {
    var a = "A".charCodeAt(0);
    return String.fromCharCode(a + nNum - 1);
}


texts:
Problem

Adapted from this HackerRank problem.

Instead of printing YES or NO, I just want to return the Set of all possible weights for an input String.

I found this example to be illustrative

Implementation

Some of my thoughts are in the implementation as comments

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class WeightedUniformStrings {
  public static Set<Long> getWeights(String s) {
    // I thought about using streams here, but I'm not using java 8
    Set<Long> weights = new HashSet<>();
    Map<Character, Long> consecutiveCharacterCounts = WeightedUniformStrings.getConsecutiveCharactersCounts(s);
    for (Map.Entry<Character, Long> entry : consecutiveCharacterCounts.entrySet()) {
      if (entry.getValue() != null && entry.getKey() != null) {
        long weight = WeightedUniformStrings.calculateWeight(entry.getKey());
        for (long i = 0; i < entry.getValue() + 1; i++) {
          weights.add(weight * i);
        }
      }
    }
    return weights;
  }

  private static long calculateWeight(char c) {
    // Could add a check to see if character is alphabetical
    return Character.toLowerCase(c) - 'a' + 1;
  }

  private static Map<Character, Long> getConsecutiveCharactersCounts(String s) {
    if (s.isEmpty()) {
      return new HashMap<>();
    }

    Map<Character, Long> consecutiveCharacterCounts = new HashMap<>();
    char[] chars = s.toCharArray();

    // I'm not a big fan of this initialization + for loop - but I haven't thought of a better alternative implementation
    char startingCharacter = chars[0];
    long consecutiveCharacterCount = 1;
    consecutiveCharacterCounts.put(startingCharacter, consecutiveCharacterCount);

    for (int i = 1; i < chars.length; i++) {
      char currentCharacter = chars[i];

      if (currentCharacter == startingCharacter) {
        consecutiveCharacterCount++;
      }

      if (currentCharacter != startingCharacter || i == chars.length - 1) {
        Long characterCount = consecutiveCharacterCounts.get(startingCharacter);
        if (characterCount == null || consecutiveCharacterCount > characterCount) {
          consecutiveCharacterCounts.put(startingCharacter, consecutiveCharacterCount);
        }
      }

      // Doing this logical check twice feels weird
      if (currentCharacter != startingCharacter) {
        startingCharacter = currentCharacter;
        consecutiveCharacterCount = 1;
        Long characterCount = consecutiveCharacterCounts.get(startingCharacter);
        if (characterCount == null || consecutiveCharacterCount > characterCount) {
          consecutiveCharacterCounts.put(startingCharacter, consecutiveCharacterCount);
        }
      }
    }

    return consecutiveCharacterCounts;
  }
}


texts:
I'm wondering how/if I can improve the regex I'm using in a query. I have a set of identifiers for certain user groups. They can be in two main format:

X123 or XY12, and
Any two letter combo

A user can belong to multiple groups, in which case different groups are separated by a pound symbol (#). Here's an example:

groups     user     age
X124       john     23
XY22#AB    mike     33
AB         peter    21
X122#XY01  francis  43

I want to count rows in which at least one group in second format appears, i.e. where a user is not exclusively a member of groups in first the format. I'm currently doing it like this:

select
  count(*)
from
  users
where
  groups not rlike '^(X[Y1-9][0-9]{2,2})(#X[Y1-9][0-9]{2,2})*$'

Is this bad performance-wise? And how should I approach fixing it?


texts:
ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is a special case of the Caesar cipher, developed in ancient Rome.

  ROT47 is a derivative of ROT13 which, in addition to scrambling the basic letters, also treats numbers and common symbols. Instead of using the sequence A–Z as the alphabet, ROT47 uses a larger set of characters from the common character encoding known as ASCII. Specifically, the 7-bit printable characters, excluding space, from decimal 33 '!' through 126 '~', 94 in total, taken in the order of the numerical values of their ASCII codes, are rotated by 47 positions, without special consideration of case. For example, the character A is mapped to p, while a is mapped to 2.

Below is my implementation of ROT47 algorithm:

#include <cstring>
#include <cstdio>
#include <iostream>

std::string rot47(std::string s)
{
    std::string s1 = "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
    std::string s2 = "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO";

    std::string ret = "";
    for (unsigned int i = 0; i < s.size(); i++)
    {
        std::size_t pos = s1.find(s[i]);
        ret += s2[pos];
    }

    return ret;
}

int main()
{
    std::string str = "HelloWorld!";

    std::string retFct = rot47(str);
    std::cout << retFct << std::endl;

    std::string retFct2 = rot47(retFct);
    std::cout << retFct2 << std::endl;
}

It works as expected but my question is : Is there something I can improve in my implementation? I don't know if there is a more direct way to get the result.


texts:
I have two threads, called Fun and Boring.  Each thread takes the same read-only data and runs some calculations over it and returns a [0.0, 1.0] result.

In the current setup, Fun acts as the main thread.  It gathers, prepares, and stores the data in a global variable; a memory barrier is used.  It then signals (via an event) the Boring thread that there is data to work on.  Fun and Boring now both operate on the data.

Here is code which illustrates the set up:

struct Data
{
    void*   someData;
} g_data;

struct Results
{
    float fun;
    float boring;
} g_results;

Fun::Run()
{
    g_data = somePointer;   // Prepare data
    // *memory barrier*

    SetEvent(dataIsPrepared);
        g_results.fun = FunCalculate(g_data);
    WaitForSingleObject(boringComplete);

    // Do something with g_results
}

Boring::Run()
{
    WaitForSingleObject(dataIsPrepared);
        g_results.boring = BoringCalculate(g_data);
        // *memory barrier*
    SetEvent(boringComplete);
}

Is there a "better" way to share data and results?  Are there any red flags that stand out?

Thanks for any feedback.


texts:
I created a combobox of which the list of options updates whenever you type in the box. Just a bit like entering a search in google works with suggestions.
I followed this tutorial to do so: https://trumpexcel.com/excel-drop-down-list-with-search-suggestions/

There are 4 columns of data in the sheet that make this work, combined with a named range, and a short piece of VBA to update the combobox. The combobox is in linked to cell B3. And data is in E:H starting at row 3.

First column includes the options for the combobox. There are 5619 possible options to choose from.
Second column has the following formula to determine if the entry of the combobox is in the text of the same row in the first column: =--ISNUMBER(IFERROR(SEARCH($B$3,E3,1),""))
Third column has the following formula to establish the amount of matches found: =IF(F3=1,COUNTIF($F$3:F3,1),"")
Fourth column has the following formula to return the list of possible options based on the value typed in the combobox: =IFERROR(INDEX($E$3:$E$22,MATCH(ROWS($G$3:G3),$G$3:$G$22,0)),"")

The code to update the combobox is as follows:

Private Sub ComboBox1_Change()
ComboBox1.ListFillRange = "DropDownList"
Me.ComboBox1.DropDown
End Sub

With DropDownList Being a named range that selects all the names in the fourth column.

The problem I face here is purely performance. It is really slow and unresponsive on a PC. Let alone deployed on a mobile device, which I intend to.

The problem is ofcourse within the fact that there are 5600+ options for the combobox, and therefore 4*5600 formula's to be recalculated at every character entered in the combobox. I was wondering if there is a way to do with less helper columns, and maybe more VBA to reduce the calculation times required?


texts: Optimising Probabilistic Weighted Moving Average (PEWMA) df.iterrows loop in Pandas

texts:
I'm implementing the Probabilistic Exponentially Weighted Mean for real time prediction of sensor data in pandas but have issues with optimising the pandas notebook for quick iterations.

Is there a more optimal way to completely remove the for loop as it currently runs longer than expected. How can I take advantage of apply() ; or vectorized operations etc. here?

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import datetime
import matplotlib.pyplot as plt
#plt.style.use('fivethirtyeight')
#%config InlineBackend.figure_format = 'retina'
#%matplotlib inline
from itertools import islice
from math import sqrt
from scipy.stats import norm

ts = pd.date_range(start ='1-1-2019',
         end ='1-10-2019', freq ='5T')

np.random.seed(seed=1111)
data = np.random.normal(2.012547, 1.557331,size=len(ts))
df = pd.DataFrame({'timestamp': ts, 'speed': data})
df.speed = df.speed.abs()
df = df.set_index('timestamp')
time_col = 'timestamp'
value_col = 'speed'

#pewna parameters
T = 30      # initialization period (in cycles)
beta = 0.5  # lower values make the algorithm behave more like regular EWMA
a = 0.99    # the maximum value of the EWMA a parameter, used for outliers
z = 3

#the PEWNA Model

# create a DataFrame for the run time variables we'll need to calculate
pewm = pd.DataFrame(index=df.index, columns=['Mean', 'Var', 'Std'], dtype=float)
pewm.iloc[0] = [df.iloc[0][value_col], 0, 0]

t = 0

for _, row in islice(df.iterrows(), 1, None):
    diff = row[value_col] - pewm.iloc[t].Mean # difference from moving average
    p = norm.pdf(diff / pewm.iloc[t].Std) if pewm.iloc[t].Std != 0 else 0 # Prob of observing diff
    a_t = a * (1 - beta * p) if t > T else 1 - 1/(t+1) # weight to give to this point
    incr = (1 - a_t) * diff

    # Update Mean, Var, Std
    pewm.iloc[t+1].Mean = pewm.iloc[t].Mean + incr
    pewm.iloc[t+1].Var = a_t * (pewm.iloc[t].Var + diff * incr)
    pewm.iloc[t+1].Std = sqrt(pewm.iloc[t+1].Var)
    t += 1


texts:
Inspired by Mayur Kulkarni's question this morning, I decided to post some code for the classic Towers of Hanoi problem, but this time in C++. Since this is fairly "textbook" kind of task, all suggestions are welcome.

#include <iostream>
#include <vector>
#include <string>
#include <iterator>

class Hanoi {
    typedef std::vector<int> Tower;
    Tower a, b, c;

    void show(std::string const &label, Tower c) {
        std::cout << label;
        std::copy(c.cbegin(), c.cend(), std::ostream_iterator<int>(std::cout, "\t"));
        std::cout << "\n";
    }

    void dump() {
        show("A: ", a);
        show("B: ", b);
        show("C: ", c);
        std::cout << "\n";
    }

    void MoveDisc(Tower &a, Tower &b) {
        b.push_back(a.back());
        a.pop_back();
    }

    void MoveStack(Tower &a, Tower &b, Tower &c, size_t size) {
        if (size == 0)
            return;
        MoveStack(a, c, b, size - 1);
        MoveDisc(a, b);
        dump();
        MoveStack(c, b, a, size - 1);
    }
public:
    Hanoi(std::initializer_list<int> input) : a(input) { dump(); }

    void operator()() { MoveStack(a, c, b, a.size()); }
};

int main() {
    Hanoi h { 30, 25, 20, 15, 10, 5 };
    h();
}


texts: Simple alphabet scrambler --- usage of vectors

texts:
I am currently learning C++, using this book: C++ Primer, 5th Edition. I made this program to help me understand the usage of vectors in C++. I have prior programming experience (mainly Python), and this just seems way too messy to be the right way of doing things. If I'm doing this incorrectly, or inefficiently, then please guide me in the right direction.

The purpose of this program is to take user input, and convert it into random letters (yes, I know that there is a lack of support for #'s and symbols, but that does not matter), somewhat simulating a hashing system.

This isn't homework, and it's not a dire issue. The program runs, but I want to make sure (since I'm new to C++), that I'm doing things in a somewhat correct way.

#include <iostream>
#include <string>
#include <vector>
int main(){
    srand(time(0));
    std::cout << "Welcome, to the scrambler: " << std::endl;
    std::cout << "Enter the string(all lowercase letters) you want to be scrambled: " << std::endl;
    std::string user_password;
    std::cin >> user_password;

    std::cout << "Select the type of encryption you want: " << std::endl;
    std::cout << "1. Standard alphabet scrambler " << std::endl;
              //Add support for other types...
    int choice = 0;
    std::cin >> choice;

    if (choice == 1) {

        std::vector<char> vuser_pass;

        for ( decltype(user_password.size()) i = 0; i <= user_password.size(); ++i ) {
            char letter_hold = user_password[i];
            vuser_pass.push_back(letter_hold);
        }
        //for ( decltype(vuser_pass.size()) i = 0; i <= vuser_pass.size(); ++i) {
            //std::cout << vuser_pass.at(i) << std::endl;
        //}

        std::string alpha = "abcdefghijklmnopqrstuvwxyz";
        std::vector<char> valpha;

        for ( decltype(alpha.size()) cnt = 0; cnt <= alpha.size(); ++cnt) {

            valpha.push_back(alpha[cnt]);
        }

        //for ( decltype(valpha.size()) cnt = 0; cnt <= valpha.size(); ++cnt) {
            //std::cout << valpha[cnt] << std::endl;

        //}

        auto limit = vuser_pass.size();
        limit -= 1;

        for ( decltype(vuser_pass.size()) sindex = 0; sindex < limit; ++sindex ) {
            decltype(valpha.size()) vindex = rand() % 25;
            vuser_pass[sindex] = valpha.at(vindex);
        }

        for ( decltype(vuser_pass.size()) i = 0; i < vuser_pass.size(); ++i) {
            std::cout << vuser_pass.at(i);
        }

    }
return 0;
}


texts: Thumbnail caption in vue.js with possibly missing fields in caption

texts:
I am using the following to output a thumbnail with text. It works fine but I don't like having the use a conditional to check every prop before outputting.

E.g. this.post.user.name would indicate "cannot read property of null".
Some of the values coming from the database would be null.

Whats the standard procedure to do this?

<template>

{{ post.make }}

{{ post.model }}

{{ userName }}

</template>


texts: A prime numbers enumeration optimized for speed

texts:
I know there is this thing called "Eratosthenes" but that requires the allocation of a large array while I want to find (small) prime numbers fast, yet without needing too much memory. So I wrote PrimeTable.cs with this content:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Primes
{
    public static class PrimeTable
    {
        private static readonly List<long> PrimeNumbers = new List<long>();

        public static long MaxValue { get; private set; } = 1;

        public static bool IsPrime(this long value)
        {
            if (value > MaxValue) { var longCount = Primes(true).TakeWhile(p => p <= value).LongCount(); }
            return PrimeNumbers.Contains(value);
        }

        public static long IndexOfPrime(this long value) => IsPrime(value) ? Primes().TakeWhile(p => p < value).LongCount() : -1;
        public static long NextPrime(this long value) => Primes().First(p => p > value);
        public static long PreviousPrime(this long value) => Primes().TakeWhile(p => p < value).LastOrDefault();

        public static IEnumerable<long> Primes(bool skipLast = false)
        {
            if (!skipLast) foreach (var l in PrimeNumbers) { yield return l; }
            while (MaxValue < long.MaxValue)
            {
                var max = (int)Math.Sqrt(++MaxValue);
                if (PrimeNumbers.Where(p => p <= max).All(p => MaxValue % p != 0))
                {
                    PrimeNumbers.Add(MaxValue);
                    yield return MaxValue;
                }
            }
        }
    }
}

The reason for this is because I want to stop looking after a certain value has been found. This is mere practice of my skills in enumerations and extension methods and I'm trying to be a bit creative.

So when I ask 11L.IsPrime() it will be true while 99L.IsPrime() will be false. But it won't calculate prime numbers over 11 until I ask if 99L is a prime. Then it won't go past 99. This keeps the number of calculations to a minimum.

The Primes() method is an enumerator that will basically continue calculating nearly forever and would thus take a while if I wasn't using deferred execution. But because of deferred execution, I can just stop enumerating at any moment and later continue the enumeration as it already knows the values it has had.

The IsPrime() is what I want to use in general, to check if a number is a prime or not. To do so, it needs to make sure it has calculated all primes up to the given number and if not, just calculate the remaining primes. It skips the primes it already knows but I have to find a better way to aggregate the enumeration as without the LongCount() in the end, it won't enumerate. It's deferred execution, after all. So, is there a better way to aggregate here?
I can't just use return Primes().Contains(value); as it would run almost forever when checking 99L.

The IndexOfPrime() will tell me the index of a prime number or -1 if it's not a prime.

The NextPrime() method is interesting, though. It will tell me the first prime number after a given value.
The PreviousPrime() method is trickier as I can't just ask for the last item less than value. It would enumerate nearly forever again.

The MaxValue field is just for debugging purposes so you can asl how far it has goine while enumerating...

The next challenge: can this be improved by using PLinq? If so, how?


texts: Print all path from root to leaves - code review request

texts:
Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple.

public class PrintAllPath {

    private TreeNode root;

    private class TreeNode {
        TreeNode left;
        int item;
        TreeNode right;

        TreeNode (TreeNode left, int item, TreeNode right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    public void create (Integer[] arr) {
        if (arr == null)  {
            throw new NullPointerException("The input array is null.");
        }

        root = new TreeNode(null, null, arr[0]);

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

        final int half = arr.length / 2;

        for (int i = 0; i < half; i++) {
            if (arr[i] != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (arr[left] != null) {
                    current.left = new TreeNode(null, null, arr[left]);
                    queue.add(current.left);
                }
                if (right < arr.length && arr[right] != null) {
                    current.right = new TreeNode(null, null, arr[right]);
                    queue.add(current.right);
                }
            }
        }
    }

    public void printPath () {
        doPrint(root, new ArrayList<TreeNode>());
    }

    private void doPrint(TreeNode node, List<TreeNode> path) {
        if (node == null) return;

        path.add(node);

        if (node.left == null && node.right == null) {
            System.out.println("Path from root: " + root.item + " to leaf: " + node.item + " - ");
            for (TreeNode treeNode : path) {
                System.out.print(treeNode.item + " ");
            }
            System.out.println();
        }
        doPrint(node.left , path);
        doPrint(node.right, path);

        path.remove(path.size() - 1);
    }


texts: git Create Tree from Arbitrary Directory (works in bare repository)

texts:
I made a script for a project I'm working on to create a tree object from a filesystem directory, without any working tree operations (can be run in a bare repository). The tree can be inserted into (a) commit(s) by using an index filter that invokes git read-tree --prefix=</...>.

#!/bin/bash
# createSubtreeRec <path>
# Creates a subtree with all the contents of path
# does not need to be in a work tree.
# Tree and related objects are added to the repository (unreachable)
# recursive.
# Prints the line that should be used to include the built tree in a parent
#   in the form used by git mktree on stdout. This might be a blob or tree.
#   <mode> <type> <hash>    <name>
#         ^space ^space    ^tab
function createSubtreeRec () {
    local path="$1"
    local hash=""
    local type=""
    local mode=""
    local treeData=""
    #echo "" >&2
    if [ -d "$path" ]; then
        for fullpath in $path/*; do
            # edited from my original post to simplify the code
            treeData="$(printf '%s\n%s' "$treeData" "$(createSubtreeRec "$fullpath")")"
        done
        # ignore empty dirs
        if [ "$treeData" ]; then
            # remove leading \n
            treeData="${treeData:1}"
            #echo "$treeData" >&2
            hash="$(echo "$treeData" | git mktree)"
            printf '040000 tree %s\t%s' $hash "$(basename "$path")"
        fi
    elif [ -f "$path" ]; then
        hash=$(git hash-object "$path" -w)
        type=blob
        mode=100644
        if [ -x "$path" ]; then
            mode=100755
        fi
        printf '%s blob %s\t%s' $mode $hash "$(basename "$path")"
    fi
    #echo "" >&2
}

# createSubtree <workdir> <path>
# Creates a subtree starting in <workdir> with the names in <path> as recursive trees,
# Use to get a tree that does not contain <workdir> but contains all of <path>
#   and all contents beneath it.
# Prints the top tree's hash on standard output.
function createSubtree () {
    local workdir="$1"
    local path="$2"
    # Get tree from
    if [ "$path" != "" ]; then
        local entry=$(createSubtreeRec "$workdir/$path")
    else
        local entry=$(createSubtreeRec "$workdir")
    fi
    if [ "$entry" ]; then
        while [ "$path" ] && [ "$path" != "." ] ; do
            local hash=$(echo "$entry" | git mktree)
            path="$(dirname "$path")"
            local entry="$(printf '%s %s %s\t%s' '040000' tree $hash $(basename "$path"))"
        done
        printf '%s\n' $hash
    fi
}

createSubtreeRec outputs the full tree data line because it can sometimes output blobs.

This code is a significant part of my runtime, so any performance improving observations would be appreciated.

Part of me just wants this available online as it would have helped me out, and I can't find any git builtin commands for this.


texts: All upper and lowercase permutations of a string

texts:
A couple of questions:

Is the algorithm wasting CPU time or memory unnecessarily?
If there is something in the code that is not idiomatic Python, how to improve on that?

def permute_first( c ):
    retval = []
    retval.append( c.upper() )
    retval.append( c.lower() )
    return retval

def permute( str ):
    leads = permute_first( str[0] )
    remain = str[1:]
    if not remain:
        return leads
    permutations = permute( remain )
    new_permutations = []
    for perm in permutations :
        for lead in leads:
            new_permutations.append( lead + perm )
    return new_permutations

og = "Question"
print permute( og )


texts: Angular component to render currency or date values

texts:
I have an Angular component and it is just a label which renders a value and if it has an associated pipe, the output of the pipe should be rendered as value of the label. But I don't want to declare all the pipes in the component. Currently I would like to use the currency pipe and the date pipe with their parameters. But maybe I can extend the component to use other pipes.

Would you pass the pipes as input parameter of the component or what would be your approach to achieve that? Any idea?

app.component.ts

<app-custom-label value="10000" title="My Title for a Currency render" datatype="currency" param="EUR"></app-custom-label>

<app-custom-label value="01.10.1980" title="My Title for a Date render" datatype="date" param="dd MMMM"></app-custom-label>

custom.label.component.html

<h1>{{ title }}</h1>
<label> {{ value }} </label>

custom.label.component.ts

import { Component, Input, OnInit  } from '@angular/core';
import { DataType } from './type';
import { CurrencyPipe, DatePipe } from '@angular/common';
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';

registerLocaleData(localeDe, 'de-DE', localeDeExtra);

@Component({
  selector: 'app-custom-label',
  templateUrl: './custom.label.component.html'
})
export class CustomLabelComponent implements OnInit {
  @Input() value: string;
  @Input() title: string;
  @Input() datatype: DataType;
  @Input() param: string;

  constructor() {}

  ngOnInit(){
    if (this.datatype === "currency") {
      this.value = (new CurrencyPipe('de-DE')).transform(this.value, this.param, true);
    } else if (this.datatype === "date") {
      this.value = (new DatePipe('de-DE')).transform(this.value, this.param);
    }
  }
}

Here you have my StackBlitz. If you can see, I pass a type of a pipe and its params as parameters, if I want to use any pipe. The component could also render a label without using a pipe.

https://stackblitz.com/edit/angular-label-render


texts: A simple C++ Trie for working with strings

texts:
Here is a simple C++ 11 trie for insertion and membership testing:

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

class TrieNode{
  //TrieNodes can also be used as tries
public:
  std::map<char, TrieNode> children;
  bool isLeaf;

  bool isContained(char * string){
    if (strlen(string)==0){
      return isLeaf;
     }

    char searchChar = *string; //the next char we are looking at

    if (children.find(searchChar) == children.end()){
      return false;
    }

    /*search for everything but the first char from the string in the trie
      for the first char*/
    return (children[searchChar].isContained(1+string));
  }

  void insertString(char * string){
    if (strlen(string) == 0){
      //If an empty string has been parsed then this node is the end of a string
      isLeaf = true;
      return;
    }

    char searchChar = *string;

    if (children.find(searchChar) == children.end()){
      //Create a new trie for the first character of our string
      TrieNode newNode;
      children[searchChar] = newNode;
    }

    children[searchChar].insertString(string+1);
  }
};

int main(){
  //Sample main function
  TrieNode myTrie;
  printf("hello in trie = %d\n",myTrie.isContained((char *) "hello"));
  myTrie.insertString((char *) "hello");
  printf("hello in trie = %d\n",myTrie.isContained((char *) "hello"));
  return 0;
}

I am relatively new to C++ (I have been muddling around with it for maybe a year now) so am wondering whether I may have either accidentally given my code nasal demons and/or accidentally wasted a lot of memory.


texts:
I am creating a game that contains a Board and Pieces. The Board is basically a 2D array of Pieces. [Think smaller chess board]

One of the things that I want to accomplish is to be able to retrieve the left piece of a given.. (Also want to be able to retrieve the right, up, and down).

The easiest way to achieve this is to simply do something like:

board[i-1][j] //which will give me the piece that's to the left of board[i][j]

The problem with just doing this is that this can get ugly and there is no error checking (array out of range).

I have a feeling that there may be a better data structure to use than a 2D array.

Also, I have two implementations that work, but neither really seem like a good idea

I have the following (untested) Java classes, which is a small scale of my application:

the class Board:

public class Board
{
protected Piece[][] board;

public Board()
{
    board = new Piece[7][7];
    int ctr = 0;
    for(int i = 0; i < 7; i++)
    {
        for(int j = 0; j < 7; j++)
        {
            board[i][j] = new Piece(i, j, ctr++);
        }
    }
}

public Piece PieceAt(int i, int j)
{
    return board[i][j];
}

public Piece LeftOf(Piece p)
{
    return PieceAt(p.verticalIndex, p.horizontalIndex - 1);
}
}

And the Piece class

public class Piece
{
    int verticalIndex;
    int horizontalIndex;
    int value;

    public Piece(int i, int j, int value)
    {
        this.horizontalIndex = i;
        this.verticalIndex = j;
        this.value = value;
    }

    public Piece GetLeftPiece(Board b)
    {
        return (this.horizontalIndex == 0 ? null : b.PieceAt(this.horizontalIndex, this.verticalIndex - 1));
    }
}

The first implementation sits in Board.java. The problem with this is that If I want to call it, it's a big ugly: b.LeftOf(b.PieceAt(3,3)) where b is of  type Board.

The second implementation seems like a better idea, however since the Pieces no nothing about each other, I have to include board in the method signature.


texts:
I've a lot of data whit prices of a product from different firms by week. I've a class named WeekPrice witch contains a list of firms. Here you've my class structure.

Here you've a little part of the data in JSON format:

[
    {
        "ID": 1,
        "NumberOfWeek": 1,
        "Year": 2016,
        "Date": "01/04/2016",
        "Firms": [
            {
                "ID": 1,
                "Name": "Firm ABC",
                "Price": 0.73
            },
            {
                "ID": 2,
                "Name": "DEF Solutions",
                "Price": 0.97
            }
        ]
    },
    {
        "ID": 2,
        "NumberOfWeek": 2,
        "Year": 2016,
        "Date": "08/04/2016",
        "Firms": [
            {
                "ID": 3,
                "Name": "Firm ABC",
                "Price": 0.83
            },
            {
                "ID": 4,
                "Name": "DEF Solutions",
                "Price": 0.94
            }
        ]
    }
]

I'll to make a graph that shows the evolution of the price for one firm by week. to this I need to get the price and the week in a object. In the C# code below DoublePoint is used for do this. The property Data is the week number and Value is the price.

List<DoublePoint> list = (from week in MyListWitData
                          where week.Year == DateTime.Now.Year
                          group week by week.NumberOfWeek into grp
                          select new DoublePoint()
                          {
                              Data = grp.Key,
                              Value = (double)(from price in grp.ToList()
                                               where price.Year == DateTime.Now.Year
                                               select (from firm in prijs.Bedrijf
                                                       where firm.Name == "Firm ABC"
                                                       select firm.Price
                                                      ).FirstOrDefault<decimal>()
                                              ).FirstOrDefault()
                          }).ToList<DoublePoint>();

It works perfectly but the only problem is that the code is a little bit messy. Can you refactor my code so it's better in performance and easier to read it?

Thanks in advance


texts: Counting subnumbers divisible by a given prime

texts:
Assume we are given a number and a prime p. The goal is to count all subnumbers of number that are divisible by p. A subnumber of number is formed of any number of consecutive digits in the decimal representation of number. Here is my solution:
number = input()
p = int(input())
print([int(number[i : j]) % p for i in range(len(number)) for j in range(i + 1, len(number) + 1)].count(0))

Can this solution be made faster?
Here is the original source of the problem.


texts: Effective way to find two string are anagrams

texts:
My approach for checking anagrams is:

step 1: Remove all the space from both input strings.

step 2: Sort both of the strings.

step 3: Return false if the lengths differ.

step 4 : Return true if all char matches.

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

bool anagrams(std::string usr1,std::string usr2)
{
        if(usr1.length()==usr2.length())
        {

                for(std::string::size_type pos = 0 ; pos<= usr1.length()-1 ; ++pos)
                {
                        if(pos==usr1.size()-1)
                        {
                                if(usr1[pos]==usr2[pos])
                                return true;
                        }

                        if(usr1[pos]==usr2[pos])
                        {
                                continue ;
                        }
                }

        }
        return false;
}

int main()
{
        std::string userInput1;
        std::string userInput2;

        std::getline(std::cin,userInput1);
        std::getline(std::cin,userInput2);

        std::string::iterator end_pos1 = std::remove(userInput1.begin(),userInput1.end(),' ');
        userInput2.erase(end_pos1,userInput1.end());

        std::string::iterator end_pos2 = std::remove(userInput2.begin(),userInput2.end(),' ');
        userInput1.erase(end_pos2,userInput2.end());

        std::sort(userInput1.begin(),userInput1.end());
        std::sort(userInput2.begin(),userInput2.end());

        if(userInput1.empty() || userInput2.empty())
                return 0;
        if(anagrams(userInput1,userInput2))
                std::cout<<"String is anagrams"<<"\n";
        else
                std::cout<<"String  not  anagrams"<<"\n";

        return 0;
}


texts: Switch statement in PHP - cleaner way to determine priority?

texts:
I have a function that takes in a controller instance, a method, and parameters (this is for a little MVC experiment I'm working on). The purpose of the function is to execute the controller method with the given parameters.

However, there are a few caveats. First, if the controller has a "router" method, it will call that instead of the method that was passed in. Second, if any of the controller "annotations" return a response, that will also override the method. Then, if those cases fail, we return the response of the actual controller method passed in.

It looks like this:

    switch (true)
    {
        // Router methods get first priority!
        case ($controller->using_router):
            $response = call_user_func_array(array($controller, 'router'));
            break;

        // Annotation responses take precedence over method responses because they are often used for authentication.
        case ( ! is_null($response = Annotation\Runner::run(Annotation\Extractor::extract($controller, $method)))):
            break;

        // No router or annotation responses... we're ready to run the method!
        default:
            $response = call_user_func_array(array($controller, $method), $parameters);
    }

For some reason, this just feels dirty. I don't like the break after checking for an annotation response. But, I'm not sure of any other way to implement a response "priority".

Is there a better way?


texts:
I have a helper class that I am using to return the selected items in a number of IEnumerable POCO collection but I'm not happy with the implementation. One of the reasons for using this method is that the collections area returned by RIA services as ReadOnlyObservableCollections and I don't believe they support LINQ but may be wrong.

Is there a way to refactor these three methods using generics?
Are there any other improvements that I can make?

public class ModelHelper : IModelHelper
{
    public IList<Int32> GetSelectedResults(IEnumerable<FaultAuditScoresDto> scores)
    {
        IList<Int32> selected = new List<Int32>();

        foreach (FaultAuditScoresDto s in scores)
        {
            if (s.IsSelected)
            {
                selected.Add(s.ID);
            }
        }

        return selected;
    }

    public IList<Int32> GetSelectedResults(IEnumerable<ZonesDto> zones)
    {
        IList<Int32> selected = new List<Int32>();

        foreach (ZonesDto s in zones)
        {
            if (s.IsSelected)
            {
                selected.Add(s.ID);
            }
        }

        return selected;
    }

    public IList<Int32> GetSelectedResults(IEnumerable<FaultAreasDto> faultAreas)
    {
        IList<Int32> selected = new List<Int32>();

        foreach (FaultAreasDto s in faultAreas)
        {
            if (s.IsSelected)
            {
                selected.Add(s.ID);
            }
        }

        return selected;
    }
}

I have refactored it to use generics and a dynamic type for the loop but I'm still not happy with it

     public IList<T> GetSelectedResults<T,U>(IEnumerable<U> scores)
    {
        List<T> selected = new List<T>();

        foreach (dynamic s in scores)
        {
            if (s.IsSelected)
            {
                //Need to cast the ID as <T> due to the IList limitation below
                //http://connect.microsoft.com/VisualStudio/feedback/details/534288/ilist-dynamic-cannot-call-a-method-add-without-casting
                selected.Add((T)s.ID);
            }
        }
        return selected;
    }

Any other idea?


texts:
I got this code working with the jQuery Countdown Plugin to take a string input and output a countdown in a div.  Is there a better way of implementing this?

JSFiddler

HTML

Here

Script

function stringToCountdown(element,str){
        /* Parse the String */
        var hh = parseInt(str.substr(0,2),10);
        var mm = parseInt(str.substr(2,2),10);
        var ss = parseInt(str.substr(4,2),10);
        var parity = parseInt(str.substr(4,2),10);

        var austDay = new Date();
        austDay = new Date(    austDay.getFullYear() , austDay.getMonth(),
                            austDay.getDate(),austDay.getHours()+hh,
                            austDay.getMinutes()+mm, austDay.getSeconds()+ss );
        $('#defaultCountdown').countdown({until:austDay , compact: true,format: 'dHMs',expiryText: 'No More Counter for you'});
        }

        $(function () {
          stringToCountdown('#defaultCountdown6','000005');
       });

Should I rewrite this to make it simpler and faster?


texts:
I'm looking for feedback on this live-filter I wrote in JavaScript. You can test it using the included snippet.

(function() {
  var searchField = document.getElementById('filter');

  var handler = function() {
    var text = searchField.value,
      nodes = document.getElementsByClassName('phase'),
      regexp = new RegExp(text, 'i');

    for (var i = 0; i < nodes.length; i++) {
      var node = nodes[i];

      node.text.search(regexp) < 0 ?
        node.parentNode.style.display = 'none' :
        node.parentNode.style.display = 'block';
    }
  };

  searchField.onkeyup = handler;
  searchField.onchange = handler;
})();
<input type="text" id="filter" />

Ruby on Rails

The Rails Way

Pickaxe Guide

jQuery HTML

CSS HTML AJAX

HTML5 Net Set

Node Easy

Listing Bloop