texts:
I came across this coding problem.

  Back in primary school, maybe you were sometimes asked to solve a
  fill-in-the-blank sum - or "mystery sum" - in which certain digits are
  removed and you had to figure out what they originally were.

  Now, it's time for serious business: sums with no digits, where every
  digit is replaced by a letter. Within each seperate sum, a letter
  replaces one digit and it is always the same letter for that one
  digit.

  For example, in the sum below: A+BB=ACC The aim is to figure out which
  digits are hidden behind the letters A, B and C so that the sum turns
  out correct. Here, the solution is that A replaces 1, B replaces 9 and
  C replaces 0; resulting in: 1+99=100

  Finally, there is the constraint that the length of the given word is
  equal to the length of the hidden number. Thus, in the sum
  CHEVAL+VACHE=OISEAU, CHEVAL is indeed a 6 digit number: the C (more
  precisely the first letter of any word) cannot correspond to a zero.

  For each given sum, there is only one possible solution to the
  problem. You are asked to write the result value of the sum to the
  standard output.

  INPUT: One line : a sum in the form WORD1+WORD2=RESULT, in which each
  word is a sequence of capital letters.

  OUTPUT: The result of the solved sum.

  CONSTRAINTS: Each sum has 2 to 20 words, each made up of 1 to 20
  capital letters

I solved it using brute force checking against each permutation of assigned integers to the unique characters. Can anybody suggest a better strategy or algorithm?

public static void mysterySum(String equation) {
String[] breakUp = equation.split("=");
String[] lhs = breakUp[0].split("\\+");
String rhs = breakUp[1];

HashSet<Character> charSet = new HashSet<Character>();
for (char charVal : equation.toCharArray()) {
    if (!(charVal == '+' || charVal == '=')) {
        charSet.add(new Character(charVal));
    }
}

char[] refCharVals = new char[10];

int i = 0;
for (Character charVal : charSet) {
    refCharVals[i++] = charVal;
}
while (i < 10)
    refCharVals[i++] = '=';

String refString = new String(refCharVals);
StringBuilder currRef = new StringBuilder();
checkAllPermutations(refString, currRef, lhs, rhs);

}

private static void checkAllPermutations(String string, StringBuilder outstr,   String[] lhs, String rhs) {

if (resultMatched)
    return;

HashSet<Character> current = new HashSet<>();
if (string.length() == 0) {
    HashMap<Character, Integer> refChars = getRefMap(outstr);

    int sumLhs = 0;
    for (String strNumber : lhs) {
        int number = getnumber(strNumber, refChars);
        sumLhs += number;
    }

    int rhsNumber = getnumber(rhs, refChars);
    if(rhsNumber == sumLhs) {
        resultMatched = true;
    System.out.println(rhsNumber);}
    return;
}

char[] chars = string.toCharArray();

for (int i = 0; i < chars.length; i++) {
    if (current.add(chars[i])) {
        outstr.append(chars[i]);
        checkAllPermutations(string.substring(0, i) + string.substring(i + 1, string.length()), outstr, lhs, rhs);
        outstr.setLength(outstr.length() - 1);
        if(resultMatched) break;
    }

}

}

private static int getnumber(String strNumber,  HashMap<Character, Integer> refChars) {
int number = 0;
for (int i = 0; i < strNumber.length(); i++) {
    number = number * 10 + refChars.get(strNumber.charAt(i));
}
return number;

}

private static HashMap<Character, Integer> getRefMap(StringBuilder outstr) {
HashMap<Character, Integer> refChars = new HashMap<>();

for (int i = 0; i < outstr.length(); i++) {
    if (outstr.charAt(i) != '=')
        refChars.put(outstr.charAt(i), i);
}

return refChars;
}


texts: Shortest possible way of printing a specific board

texts:
I am trying to print a board exactly like this with the multidimensional array.

char score[10][10] = {' '};

   a b c d e f g h i j
  +-------------------+
 0|                   |
 1|                   |
 2|                   |
 3|                   |
 4|                   |
 5|                   |
 6|                   |
 7|                   |
 8|                   |
 9|                   |
  +-------------------+

This is my code:

#include <iostream>
using namespace std;
#include <vector>
#include <string.h>

int main(){

char score[10][10] = {' '};

cout<< "   a b c d e f g h i j"<< endl;
cout <<"  +-------------------+"<< endl;
    for (int i = 0; i < 10; i++) {
        cout<<" "<< i <<"|" ;
        for (int j = 0; j < 10; j++) {
           cout << score[i][j];
        }
            if(i == 0){
                cout << "                  |";

            }
            else{
                cout << "                   |";
                }
        cout<< endl;

    }
    cout <<"  +-------------------+"<< endl;

}

As you can see my code is inefficient and lengthy.

What would be the shortest possible way (or a shorter way) of printing the board as exactly shown above with the multidimensional score array?


texts: Am I overlooking anything with this asynchronous read/write loop?

texts:
Here's my code:

public static void CopyStream(Stream input, Stream output)
{
    var size = 8192;

    var inBuffer = new byte[size];
    var outBuffer = new byte[size];

    IAsyncResult writeAsync = null;

    int count;
    while (true)
    {
        var readAsync = input.BeginRead(inBuffer, 0, size, null, null);

        if (writeAsync != null)
        {
            output.EndWrite(writeAsync);
            writeAsync = null;
        }

        count = input.EndRead(readAsync);
        inBuffer.CopyTo(outBuffer, 0);

        if (count > 0)
        {
            writeAsync = output.BeginWrite(outBuffer, 0, count, null, null);
        }
        else
        {
            break;
        }
    }
}

This really is my first piece of code using the Begin/End asynchronous model.  I'm just wondering if I have any glaring issues.

Or, are there any improvements that you can see to make this even better?


texts: Merge all files in a directory with a specific extension

texts:
I come from Python, with a bit a FORTRAN and Matlab some years ago.
I'm trying to learn C. My first attempt at a program is one to merge all the files in a directory with a specified extension

/*
MERGE: Merges text files. Gives the ability to all files in a
directory with specified extension.
*/
#include <stdio.h>
#include <dirent.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

/* Function prototypes */
int append_to_file(const char *filename, const char *outfilename); // Appends the contents of filename to outfilename
int scandir(char dirname[], char const *ext, char outfile[]); // Scans a directory for files of a specific extension and merges them
bool has_extension(char const *name, char const *ext);
void usage(); // Prints out usage information (help) to the console
void path_combine(char *dest, const char *path1, const char *path2); // Combines a directory name and filename to a single filepath

int main(int argc, char *argv[])
{
    int nfiles; // Number of files merged

    if (argc == 4)
    {
        nfiles = scandir(argv[1], argv[2], argv[3]);
        printf("Merged %d files\n", nfiles);

        return 0;
    }
    else
    {
        printf("Wrong input, quitting");
        return 1;
    }

}

int append_to_file(const char *filename, const char *outfilename)
{
    FILE *infile, *outfile;
    char ch;
    infile = fopen(filename, "r");
    outfile = fopen(outfilename, "a");

    if (infile == NULL)
    {
        printf("Input file is empty, skipping...\n");
        return 1;
    }

    while ((ch = fgetc(infile)) != EOF)
        fputc(ch, outfile);

    printf("Appended file\n");

    fclose(infile);
    fclose(outfile);

    return 0;

}

int scandir(char dirname[], char const *ext, char outfile[])
/* Scans a directory and merges all files of given extension */
{
    DIR *d = NULL;
    struct dirent *dir = NULL;
    char filepath[strlen(dirname) + 255];
    int i = 0;

    d = opendir(dirname);

    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            if (has_extension(dir->d_name, ext))
            {

                path_combine(filepath, dirname, dir->d_name);
                printf("%s\n", filepath);
                append_to_file(filepath, outfile);
                i++;
            }

        }
        closedir(d);
    }
    return i;
}

bool has_extension(char const *name, char const *ext)
{
    size_t len = strlen(name);
    return len > 4 && strcmp(name+len-4, ext) == 0;
}

void path_combine(char *dest, const char *path1, const char *path2)
{
    const char *last_char = path1;
    int append_sep = 0;
    char sep[] = "/";

#ifdef WIN32
    sep[0] = '\\';
#endif

    /* Find the last character in the first path*/
    while(*last_char != '\0')
        last_char++;

    /* If the last character is not a seperator, we must add it*/
    if (strcmp(last_char, sep) !=0)
    {
        append_sep = 1;
    }

    strcpy(dest, path1);
    if (append_sep)
        strcat(dest, sep);
    strcat(dest, path2);

}

void usage()
{
    printf("\t=================\n");
    printf("\t      MERGE\n");
    printf("\t=================\n");
    printf("Merge two or more text files\n");
    printf("Usage:\n");
    printf("\tCall merge with a directory name and desired extension:\n");
    printf("\tmerge DIRNAME .csv OUTPUTFILE\n\n");

};

I realise there are many things I haven't done here (such as any real error handling), but bear in mind this is a first attempt as part of the learning process.
Rather than being told to 'go look up xx' where xx is a whole area of learning, I'm more interested in specifics if possible.

Are there any obvious code smells?
Is there anything that could obviously be implemented better?
Particularly usage of pointers, which I am still getting to grips with.


texts:
I've implemented my own insertion sort algorithm, and here's the code.
def insertion(lst):
    for i in range(1, len(lst)):
        for j in range(i):
            if lst[i] < lst[j]:
                val = lst[i]
                del lst[i]
                lst.insert(j, val)
                break
    return lst

Typical insertion sort algorithms seem to compare values from the immediate left of the current index and make swaps as you continue left in the sorted values.
I implemented my algorithm such that it will compare values from left to right (the second for loop). Do you see any issues with my code, or do you have any feedback on this?


texts: dnaof() - inheritance made easy, my own make inheritance tool

texts:
https://github.com/exebook/dnaof

I created this simple inheritance tool for JavaScript, could any one with deep knowledge in JavaScript prototyped inheritance review it?

Here is the library itself:

kindof = function(K) {
    function X() {}
    if (K != undefined) X.prototype = new K
    X.can = X.prototype
    return X
}
dnaof = function(x, f) {
    var p = x.__proto__
    x.__proto__ = p.__proto__
    var r = p.__proto__[f].apply(x)
    x.__proto__ = p
    return r
}

And here is the example usage to demonstrate what it can do:

require('./dnaof')

// create a kind of idiot without ancestor:

var idiot = kindof()

// tell what it can do:

idiot.can.say = function() { return this.name + ' can chat' }
idiot.can.rest = function() { console.log('bzzzz.z.z.z... (' + this.name + ')') }

// a new kind of smart inherits from a kind of idiot

var smart = kindof(idiot)

// he can also say something:

smart.can.say = function() {
    // he can say something new, and he can say the same thing as an idiot can:
    return dnaof(this, 'say') + ', ' + this.name + ' can talk'
}

// a kind of a genious can do the same things as an idiot and smart can, and even more:

var genious = kindof(smart)
genious.can.say = function() {
    return dnaof(this, 'say') + ', ' + this.name + ' can discuss'
}

// instantiate three persons:

var bob = new idiot
var alice = new smart
var candy = new genious

// assign properties, because to make life simpler we do not initialize anything during creation:

bob.name = 'bob'
alice.name = 'alice'
candy.name = 'candy'

// let them talk:

console.log(bob.say())
console.log(alice.say())
console.log(candy.say())

// let them take some rest:

alice.rest(), bob.rest(), candy.rest()


texts: Remove all duplicated elements in a single list

texts:
I am learning algorithms. And my current algorithm is create a single list, and try to remove all duplicated elements in a sorted list.
Ex:
   given Input: 1 -> 1 -> 1 -> 2 -> 2 -> 3 -> 5 -> 5 -> 7
   Expected Output: 3 -> 7

My bellow solution worked well:

//Definition for singly-linked list.
public class ListNode
{
    public int val;
    public ListNode next;
    public ListNode(int x)
    {
         val = x;
         next = null;
    }
}

public ListNode deleteAllDuplicates(ListNode list)
{
    if (list == null)
    {
        return null;
    }

    var start = list;
    var isStart = true;
    var pre = start;
    var tmp = list.val;

    while (list?.next != null)
    {

        if (tmp == list.next.val)
        {
            while (list?.val == tmp)
            {
                list = list.next;
            }

            if (isStart)
            {
                start = list;
                pre = start;
            }
            else
            {
                pre.next = list;
            }

            if (list == null)
            {
                return start;
            }

            tmp = list.val;
        }
        else
        {
            pre = list;
            list = list.next;
            tmp = list.val;
            isStart = false;
        }
    }

    return start;
}

My question is: What should I do to improve the solution?
Any help are appriciate!


texts: Finding the minimum number of required deletions to have a non-repeating string

texts:
I wrote code for the following problem:

  Given a string, print out the number of deletions required so that the adjacent alphabets are distinct.

Please suggest different methods by which I can increase the speed of execution.

tst = int(input())
for i in range(0,tst):
    str = input()
    length = len(str)
    str = list(str)
    j=0;
    count = 0
    while(j<length):
       if(j+1<length):
            if((str[j] == str[j+1])):
                del str[j+1]
                count+=1
                length-=1
            else:
                j+=1
       else:
            j+=1
    print(count)


texts:
I have an instance method which calculates the position of an element, depending on the tariff of its seller.

If the seller is of a level3 tariff, it gets to top 100, the probability of 40%. If the tariff is level2, then 30%, etc.

TARIFFS = {level3: 0...40,
           level2: 40...70,
           level1: 70...90,
           level0: 90..100}

def update_priority
  top = 100
  priority = 0
  random = rand(0..top)
  all_count = collection.find.count
  if TARIFFS[seller.tariff] === random
    priority = rand((all_count - top).to_f..all_count.to_f)
  else
    priority = rand(1..all_count)
  end

  collection.find(_id: self._id).update('$set' => {priority: priority})
end

And I have class method which runs every 2 hours:

def recalculate_priorities
  unscoped.each(&:update_priority)
end

It does not work fast. How can I optimize it to work faster?


texts:
Coming from a C/C++ background, this was my first python code I wrote to grasp a few basic concepts. The game involves giving random arithmetic operations to the users and scoring their responses. Player has 3 lives i.e he can mark 3 wrong answers at most. I've tried to time the game i.e the player gets 60 seconds to solve as many questions as possible.

Any suggestions and improvements are welcome.

import random
import time

# Function to generate expressions
from typing import List

def generate_expression(no_of_operators):
    operands = []
    operators = []
    operations = ['+', '-', '*', '/']
    expression = []
    operands_count = 0
    operators_count = 0
    for i in range(0, no_of_operators):
        operands.append(random.randint(0, 20))
    for i in range(0, no_of_operators - 1):
        operators.append((random.choice(operations)))
    for i in range(0, len(operators) + len(operands)):
        if i % 2 == 0:
            expression.append(operands[operands_count])
            operands_count += 1
        else:
            expression.append(operators[operators_count])
            operators_count += 1
    expression = ''.join(str(x) for x in expression)
    return expression

# Function to calculate the solution
def result(expression):
    return (int(eval(expression)))

# Function to evaluate if the answer is right
def evaluate(solution, user_solution):
    if solution == user_solution:
        return True
    else:
        return False

# Display Message

print("""Welcome to the maths game !!!
-----------------------------
Test your basic arithematic skills by playing this simple game. With every 5 correct answers, the level increase
increasing the difficulty of the questions.
Remember :
----------
        1. Write only the integral part of the answer
        2. Operator precedence applies
        3. You have 3 lives.
        4. Total of 60 seconds will be provided.
        5. The timer starts after the first answer is entered """)
input("Are you ready ?? Press any key to begin ! ")

# Variables on which the game operates
score = 0
level = 1
lives = 3
start = time.time()
finish_time = time.time() + 60  # for the timed mode, 60 seconds are needed

# While loop to drive the game
while lives != 0 and time.time() < finish_time:
    # Increase the level of difficulty every 5 questions.
    if score != 0 and score % 5 == 0:
        level = level + 1
    print("LEVEL : ", level)
    no_of_operands = level + 1
    question_expression = generate_expression(no_of_operands)
    print(question_expression, end='')
    # Checking for any divide by zero or numerical errors that may show up
    correct_answer = 0
    try:
        correct_answer = result(question_expression)
    except:
        print("OOPS ! I messed up ! Lets do it again !")
        continue
    answer = int(input(" = "))

    if evaluate(correct_answer, answer):
        print("CORRECT ! ", end='')
        score = score + 1
        print("SCORE = ", score, "LIVES = ", lives)
    else:
        print("WRONG ! ", end='')
        lives = lives - 1
        print("SCORE = ", score, "LIVES = ", lives)
print("GAME OVER !!!")
print("Maximum Level = ", level, "SCORE = ", score)


texts: Plain-text file encryption and decryption

texts:
I have created an Encryption and Decryption Algorithm that encrypts plain text using a given cipher and also decrypts it back to the original notation. It works great.

This was my code for a coding test and the reviewer told me that the class structure is inverse of what is the right way of doing it and that it is sloppy at some places.

I want to know what is wrong with my structuring of classes, if anything. Does it look sloppy? Can someone please help me identify places where it is lacking Best Practices for Java?

I have a MyBuilder class which creates an instance of MyAlgorithm.
MyAlgorithm has the methods to encrypt and decrypt text, and it extends another class called EncryptionAndDecryption where the actual logic of the algorithm resides.

public class MyAlgorithm extends EncryptionAndDecryption {

    public enum Action {
        ENCRYPT,
        DECRYPT
    }

    protected MyAlgorithm(final String cipherCharSet) {
        super(cipherCharSet);
    }

    public String encryptText(final String cipher, final String plainText) {
        return encryptOrDecryptText(cipher, plainText, Action.ENCRYPT);
    }

    public String decryptText(String cipher, String encryptedText) {
        return encryptOrDecryptText(cipher, encryptedText, Action.DECRYPT);
    }

    public boolean encryptDirectory(String cipher, String baseDirectory) {
        // for each files and sub files in each sub directories, call the following method;
    // encryptOrDecryptFile(cipher, file, baseDirectory, Action.ENCRYPT));
    }

    public boolean decryptDirectory(String cipher, String baseDirectory) {
        // for each files and sub files in each sub directories, call the following method;
    // encryptOrDecryptFile(cipher, file, baseDirectory, Action.DECRYPT));
    }
}

public class EncryptionAndDecryption {

    private final String CIPHER_CHAR_SET;

    protected EncryptionAndDecryption(final String cipherCharSet) {
        this.CIPHER_CHAR_SET = cipherCharSet;
    }

    protected final String encryptOrDecryptText(final String cipher, final String inputText, final MyAlgorithm.Action action) {
         // method logic here
    }

    protected final void encryptOrDecryptFile(final String cipher, final Path filePath, final String baseDirectory, final MyAlgorithm.Action action) {
        // method logic here
    }
}

public class MyBuilder {

    private String CIPHER_CHAR_SET;

    private MyBuilder() {}

    public static MyBuilder builder() {
        return new MyBuilder();
    }

    public MyBuilder withCipherSet(String cipherSet) {
        this.CIPHER_CHAR_SET = cipherSet;
        return this;
    }

    public MyAlgorithm build() {
        return new MyAlgorithm(CIPHER_CHAR_SET);
    }
}

public class MyEncryptionApp {

    public static final String CIPHER_CHAR_SET = "abcdefghijklmnopqrstuvwxyz";

    public static void main(String args[]) {
        if (args.length != 3) {
            System.out.println("Exact 3 parameters required - [action] [key] [target]");
            System.exit(1);
        }

        String action, key, target;
        action = args[0];
        key = args[1];
        target = args[2];

        MyAlgorithm myAlgorithm = MyBuilder.builder()
                .withCipherSet(CIPHER_CHAR_SET)
                .build();

        if ("encrypt".equalsIgnoreCase(action)) {
            System.out.println(myAlgorithm.encryptText(key, target));

        } else if ("decrypt".equalsIgnoreCase(action)) {
            System.out.println(myAlgorithm.decryptText(key, target));

        } else if ("encryptDir".equalsIgnoreCase(action)) {

            if(myAlgorithm.encryptDirectory(key, target)) {
                System.out.println("Directory encryption Successful");
            }

        } else if ("decryptDir".equalsIgnoreCase(action)) {

            if(myAlgorithm.decryptDirectory(key, target)) {
                System.out.println("Directory decryption Successful");
            }

        } else {
            System.out.println("action [" + action + "] not implemented");
        }

    }
}


texts:
Please keep in mind that I am very new to data science and completely new to NLP! I am trying to create a model to classify customer reviews as either negative or positive. However, my main problem is that most of them are in Norwegian, which seems not to be very well supported. I have found this repo https://github.com/ltgoslo/norsentlex/tree/master/Fullform containing both negative and positive lexicons and have decided to use it.

with open("Fullform_Positive_lexicon.txt") as f:
    reader = csv.reader(f)
    positive_lexicon = []
    for row in reader:
        print(str(row))
        positive_lexicon.append(row[0])

with open("Fullform_Negative_lexicon.txt") as f:
    reader = csv.reader(f)
    negative_lexicon = []
    for row in reader:
        negative_lexicon.append(row[0])

#adjusted to use it with NaiveBayesClassifier
def get_tokens_for_model(cleaned_tokens_list):
    final_token_list = []
    for token in cleaned_tokens_list:
        token_dict = {}
        token_dict.update({token : True})
        final_token_list.append(token_dict)
    return final_token_list

positive_tokens_for_model = get_tokens_for_model(positive_lexicon)
negative_tokens_for_model = get_tokens_for_model(negative_lexicon)

positive_dataset = [(token, "Positive")
                     for token in positive_tokens_for_model]

negative_dataset = [(token, "Negative")
                     for token in negative_tokens_for_model]

dataset = positive_dataset + negative_dataset
#shuffle dataset
for i in range(len(dataset)-1, 0, -1):
    j = random.randint(0, i + 1)
    dataset[i], dataset[j] = dataset[j], dataset[i]

train_data = dataset[:20000]
test_data = dataset[7742:]

classifier = NaiveBayesClassifier.train(train_data)

print("Accuracy is:", classify.accuracy(classifier, test_data))

So I am just training my model based on this lexicon and then I am trying to apply it to my comments. I am getting here 87%, which is not so bad. However, it looks worse when used with whole sentences.

with open("stopwords.csv") as f:
    reader = csv.reader(f)
    norwegian_stopwords = []
    for row in reader:
        norwegian_stopwords.append(row[0])

customer_feedback = pd.read_excel("classification_sample.xlsx")
customer_feedback = customer_feedback.dropna()
customer_feedback['Kommentar'] = customer_feedback['Kommentar'].apply(remove_punctuation)

list_of_comments = list(customer_feedback['Kommentar'])

for comment in list_of_comments:
    custom_tokens = word_tokenize(comment)
    filtered_tokens = []
    for word in custom_tokens:
        if word not in  norwegian_stopwords:
            filtered_tokens.append(word)

    classification = classifier.classify(dict([token, True] for token in filtered_tokens))
    probdist = classifier.prob_classify(dict([token, True] for token in filtered_tokens))
    pred_sentiment = probdist.max()
    print("Sentence: " + comment)
    print("Classified as: " + str(classification))
    print("Key words: " + str(custom_tokens))
    print("Probability: " + str(round(probdist.prob(pred_sentiment), 2)))
    print("-----------------------------------------------------------")

I know my code is not the highest quality right now(although suggestions regarding this are also appreciated). I am looking mostly for some feedback what more can I do to improve my accuracy. What is currently not very clear to me, is how to properly train the model on words and then achieve the very same accuracy on sentences.


texts:
While reading HackerNews, I learned about a data set of the first 50 million primes.  This would be a lot, but his website has disclaimer:

  n this directory I have the first fifty million primes in blocks of one million.  Usually it is faster to run a program on your own computer than to download them, but by popular demand, here they are!

N = 10000

n = np.arange(N)+2
P = []

for M in range(3):

    n = np.arange(N)+2 + M*N
    for p in P:
        n =  n[np.where(n% p != 0)]

    while(len(n) > np.sqrt(N)):
        P += [n[0]]
        n = n[np.where(n% P[-1] != 0)]
        #print len(n),

print len(P), M*N/np.log(M*N), M

When I posted this on HackerNews, someone mentioned this was sub-optimal.

  I like this way of using NumPy. This resembles the sieve of Eratosthenes, so you'd think it was fast.
  However n%p[-1] isn't fast to do, your inner loop ends up taking nearly linear time. At least linear in the final number of primes, which is larger than \$N \log N\$. Hence your algorithm runs in \$N^{3/2}\$ whereas Eratosthenes is \$N \log \log N\$.

How do I fix it? For large values, say N=10**6 it's a bit slow.  What is wrong with n%p[-1]?


texts:
I have a "GetPersonsPerDepartment()" method returning a IQueryable<IEnumerable<Person>> while I'm trying to get a simple List<Person> or IEnumerable<Person> with all the persons from every department. I wrote a simple method GetAllPersons() that solves this with a loop but I feel I must be missing a simple command to get the same result:

private List<Person> GetAllPersons()
{
    List<Person> allPersons = new List<Person>();

    foreach(var Persons in GetPersonsPerDepartment())
    {
        allPersons.AddRange(Persons);
    }

    return allPersons;
}

private IQueryable<IEnumerable<Person>> GetPersonsPerDepartment()
{
    IQueryable<IEnumerable<Person>> Persons;

    using (var context = MySource.GetPersonsContext())
    {
        var library = "Personlist";
        var PersonFolderList = context.Web.Lists.GetByTitle(library);
        context.Load<List>(PersonFolderList);

        var PersonFolderListItems = PersonFolderList.GetItems(new CamlQuery());
        context.Load<ListItemCollection>(PersonFolderListItems);

        context.ExecuteQuery();

        Persons = PersonFolderListItems.Where(x => x.FileSystemObjectType == FileSystemObjectType.Folder).Select(x => GetPersonsFromFolderListItem(x, context, PersonFolderList));
    }

    return Persons;
}


texts: Creating my own flow control statements in C++. Is that acceptable?

texts:
I always considered switch statement as somehow defective:

works only on integral types and enumerations.
isn't an readability improvement over traditional if/else chain.
forget a break - you have a bug.
variable declaration spills over neighbouring cases.
is essentially a computed goto

Because of said reasons, and also as an exercise on lambdas and variadic templates I created my own flow control function.

#include <functional>
#include <tuple>

template<typename V>
bool switch_on(const V& value)
{
    return false;
}

template<typename V, typename P, typename... Args>
bool switch_on(const V& value, const P& p, Args... args)
{
    if(std::get<0>(p)(value, std::get<1>(p)))
    {
        std::get<2>(p)();
        return true;
    }
    else
    {
        return switch_on(value, args...);
    }
}

template<template <typename> class P, typename F, typename V >
auto case_of(const V& v, const F& p) -> decltype( std::make_tuple(P<V>(), v, p) )
{
    return std::make_tuple(P<V>(), v, p);
}

template<typename P, typename F, typename V >
auto case_of(const V& v, const F& p) -> decltype( std::make_tuple(P(), v, p) )
{
    return std::make_tuple(P(), v, p);
}

template<typename F, typename V >
auto case_of(const V& v, const F& p) -> decltype( std::make_tuple(std::equal_to<V>(), v, p) )
{
    return std::make_tuple(std::equal_to<V>(), v, p);
}

so I can use:

using std::less;
using std::greater;

int main()
{
    int a = 42;
    switch_on(a,
        case_of<less>(0, [&]{
            std::cout << "LESS THAN ZEROOOOOOOOOOOOOO.";
        }),
        case_of(42, [&]{
            std::cout << "Yes";
        }),
        case_of<greater>(9000, [&]{
            std::cout << "IT'S OVER NINE THOUSAAAAAAAAND!!!";
        })
    );
}

While in Lisp, it is encouraged to create new forms of flow control, what about C++? I would also like to see some opinions about template usage, some pointers on how to improve the code and possible corner cases when this code will break.


texts: A Tour of Go, problem #56 - error handling

texts:
New to Go, trying to solve Tour of Go, Exercise 56, which is about error handling.

Can the following error handling method can be further improved?

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(f float64) (float64, error) {
    if f > 0 {
        return math.Sqrt(f), nil
    } else {
        return 0, ErrNegativeSqrt(f)
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}


texts: An "Add" button that clones an item, and a "Remove" button that fades and removes an item

texts:
I was looking into removing multiple inputs and selects at once using jQuery, but I couldn't find a solution, so I ended up with the following code:

$(function() {

  $('a.add').click(function(evt) {
    //clone lists
    //is there any way to simplify this part --begin--
    $('#s0 option').clone().appendTo('#s'+obj);
    $('#i0 option').clone().appendTo('#i'+obj);
    $('#r0 option').clone().appendTo('#r'+obj);
    $('#ieu0 option').clone().appendTo('#ieu'+obj);
    $('#ied0 option').clone().appendTo('#ied'+obj);
    //--end--
    evt.preventDefault(); //prevents scrolling
  });

  //remove inputs/selects
  $('a.remove').click(function(evt) {
    //animation is not necessary. How can I simplify this code? --begin--
    $('#comp'+x).animate({opacity:"hide"}, "slow").remove();
    $('#ppt'+x).animate({opacity:"hide"}, "slow").remove();
    $('#ct'+x).animate({opacity:"hide"}, "slow").remove();
    $('#p'+x).animate({opacity:"hide"}, "slow").remove();
    $('#ipvs'+x).animate({opacity:"hide"}, "slow").remove();
    $('#s'+x).remove();
    $('#i'+x).remove();
    $('#r'+x).remove();
    $('#ipvs'+x).remove();
    $('#other'+x).remove();
    //--end--
  }
  evt.preventDefault();
  });
});

How can the sections marked between --begin-- and --end-- be simplified/improved?


texts: Using closure, alias and namespace extension patterns: How to allow for independent instantiations of plugin?

texts:
Simplified working demo code here.

Relevant JS code:

;(function(exports) {

    //--------------------------------------------------------------------------
    //
    // Private properties:
    //
    //--------------------------------------------------------------------------

    var _msg = '',
    _ol = document.getElementById('debug');

    //--------------------------------------------------------------------------
    //
    // Public methods:
    //
    //--------------------------------------------------------------------------

    exports.init = function(arg) {

        _msg = arg;

        // Add a listener to the `window.resize` event, pass `exports`/`self` as the scope:
        _addEvent(window, 'resize', _listenForChange, exports);

    };

    //--------------------------------------------------------------------------
    //
    // Private methods:
    //
    //--------------------------------------------------------------------------

    function _addEvent(elem, type, handle, context) {

        // Attache event:
        if (elem) {

            if (elem.addEventListener) {

                // If the browser supports event listeners, use them:
                elem.addEventListener(type, function() { handle.call(context); }, false);

            } else if (elem.attachEvent) {

                // IE & Opera:
                elem.attachEvent('on' + type, function() { handle.call(context); });

            } else {

                // Otherwise, replace the current thing bound to `on[whatever]`!
                elem['on' + type] = function() { handle.call(context); };

            }

        }

    }

    function _listenForChange() {

        var li = document.createElement('li');

        li.innerHTML = String(_msg);

        _ol.appendChild(li);

        if (typeof console !== 'undefined') console.log(_msg);

    }

    return exports; // Expose the API.

}(window.FOO = window.FOO || {}));

//--------------------------------------------------------------------

window.onload = function() {

    FOO.init('world');

    FOO.init('universe');

};

Problem with existing code:

When re-sizing the window, I only see "universe".

Goal:

When browser window re-sizes, I want to world "world" and "universe" output as a list item (and to the console).

I want to have the ability to instantiate FOO multiple times and have it work independently from any other running instances.

My questions:

Is there a pattern (or patterns), similar to the one(s) that I'm currently using, that will allow me to run multiple instances of FOO without having the last FOO called trump all previously called FOOs?

The code I posted is obviously not real world; my end goal is to allow/modify a plugin I wrote to be used without the end user having to worry if FOO is already being used by another script.

Please let me know if I can clarify anything and/or provide more specific code.


texts:
I have 9 sheets with 1668 rows and 34 cols. The code collects all data from every sheet into one Summary sheet in the following format:

service 1 supplier 1 price etc..
service 1 supplier 2 price etc..

Unfortunately excel freezes around the 7k row and I receive 'out of memory' error. Any suggestions how to solve improve to code to run on large data?

Sub goEasy()

Dim wsText As Variant
Dim sht As Worksheet
Dim wSum As Worksheet
Dim service As String
Dim supplier As String
Dim priceRange As String
Dim price As String
Dim Lrow As Long, LastRow As Long
Dim a As Long, b As Long

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Set sht = ThisWorkbook.Worksheets(4)
Set wSum = ThisWorkbook.Worksheets("Summary")

wsText = Array("<25K", "25K <100K", "100K <250K", "250K <500K", "500K <1M", "1M <5M", "5M <15M", "15M <30M", "30M <50M")

LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

    For Each element In wsText
        'For i = 5 To LastRow
        a = 4
        b = 12
        Do While a < LastRow
            'For j = 13 To 47

            If a = LastRow Then
            a = 4
            Exit Do
            End If
            a = a + 1

            Do While b <= 47

            If b = 47 Then
            b = 12
            Exit Do
            End If

                b = b + 1
                Lrow = wSum.UsedRange.Rows(wSum.UsedRange.Rows.Count).Row + 1

                service = ThisWorkbook.Worksheets(element).Cells(a, 1).Text
                supplier = ThisWorkbook.Worksheets(element).Cells(4, b).Text
                priceRange = ThisWorkbook.Worksheets(element).Cells(2, 1).Text
                price = ThisWorkbook.Worksheets(element).Cells(a, b).Text

                wSum.Cells(Lrow, 1) = service
                wSum.Cells(Lrow, 2) = supplier
                wSum.Cells(Lrow, 3) = priceRange
                wSum.Cells(Lrow, 4) = price
            'Next j
            Loop
        'Next i
        Loop
    Next element

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True

MsgBox ("Complete")

End Sub


texts: Iterative uniform recombination of integer lists in python with numba

texts:
I have a list of N integers and I iteratively take two integers at random, which are not at the same position in the list and uniformly recombine their binary representation, e.g. in intList = [1,4,1,5] (N=4) the number on the second and third position is chosen, aka 4 & 1, and their binary represenations 4=100 & 1=001 is uniformly recombined. Uniformly recombined means that I chose either the 1 or the 0 of the first position, one of the two 0's of the second position and either the 0 or 1 of the third position. This could result in 000 or 101 or 100 or 001. The result is saved as integer in the list. In each iteration I do this recombination for all N integers. This happens in a function with a numba decorator. My code is:
@nb.njit()
def comb():
    iterations = 100000
    N = 1000
    intList = list(range(N))   # this is just an example of possible integer lists
    l = 10   # length of the largest binary representation.
    intList_temp = [0]*N
    for _ in range(iterations):
        for x3 in range(N):
            intList_temp[x3] = intList[x3]
        for x3 in range(N):
            randint1 = random.randint(0, N - 1)
            randint2 = random.randint(0, N - 1)
            while randint1 == randint2:
                randint1 = random.randint(0, N - 1)
                randint2 = random.randint(0, N - 1)
            a = intList[randint1]
            b = intList[randint2]
            c = a ^ ((a ^ b) & random.randint(0, (1 << l) - 1))
            intList_temp[x3] = c
        for x3 in range(N):
            intList[x3] = intList_temp[x3]
    return intList

print(timeit(lambda: comb(), number=1))
>>>2.59s

My question is, can this be improved?


texts: Out of N number of participants, draw out M winners

texts:
It could be a simple Fisher-Yates, but then if the number of participants is 1,000,000 and the number of winner is only 3, then we really don't need to shuffle the whole 1,000,000 numbers, so the following is to reduce the number of steps, written as a simpler case of drawing 9 winners out of 30 participants:
The following is to consider 30 participants, each numbered from 1 to 30, and take out 9 winners.  One will be Grand Prize, and two will be Second Prizes, and 6 Third Prizes.

const NUM_PARTICIPANTS = 30;
const NUM_DRAWN = 9;

console.log(`run: ${NUM_PARTICIPANTS} draw ${NUM_DRAWN}`);

const arr = Array.from(new Array(NUM_PARTICIPANTS), (e, i) => i + 1);

for (let i = arr.length - 1; i >= NUM_PARTICIPANTS - NUM_DRAWN; --i) {
  const j = Math.floor(Math.random() * (i + 1));
  [arr[i], arr[j]] = [arr[j], arr[i]];
}

const results = arr.slice(NUM_PARTICIPANTS - NUM_DRAWN)

console.log(`Grand prize: ${results[0]}`);
console.log(`Second prize: ${results.slice(1,3).sort((a, b) => a - b).join(" ")}`);
console.log(`Other winners:\n  ${results.slice(3).sort((a, b) => a - b).join("\n  ")}`);


texts: Web crawler that filters out non diseases

texts:
It is very messy and I lack the experience to make it eloquent so I wanted some help with it. The process time is also very slow.

Currently it goes into the first page and goes through the links in the index looking for the word "symptoms." If its not found it will look for a link inside that link named "faqs" and go to that link and look for 'symptoms'.

import requests
import string
from bs4 import BeautifulSoup, Tag
alpha = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'
alpha = alpha.split()
w = []
def disease_spider(maxpages):
    i = 0
    while i <= maxpages:

        url = 'http://www.cdc.gov/DiseasesConditions/az/'+ alpha[i]+'.html'
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)

        for l in soup.findAll('a', {'class':'noLinking'}):
            if l.text != "USA.gov" and l.text != 'Inspector General' and l.text != '':
                href = l.get('href')
                diseasechecker(href)
        i += 1
def diseasechecker(url2):
    source_code = requests.get(url2)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for y in soup.findAll('p'):
        x = str(y)
        txt = y.text
        if 'symptoms' in x and url2 not in w:
            w.append(url2)
        elif 'symptoms' in txt and url2 not in w:
            w.append(url2)
    for y in soup.findAll('li'):
        x = str(y)
        txt = y.text
        if 'symptoms' in x and url2 not in w:
            w.append(url2)
        elif 'symptoms' in txt and url2 not in w:
            w.append(url2)
    for y in soup.findAll('a'):
        href2 = y.get('href')

        try:
            s = str(href2)
            u = "http://www.cdc.gov"+s
        except UnicodeEncodeError:
            pass
        l3 = 0
        if 'faqs' in s:
            l3 = level3(u)
        if l3 == 1 and url2 not in w:
            w.append(url2)
def level3(url3):
    source_code = requests.get(url3)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for y in soup.findAll('p'):
        x = str(y)
        txt = y.text
        if 'symptoms' in x:
            return 1
        elif 'symptoms' in txt:
            return 1

disease_spider(0)
for i in range(len(w)):
    print w[i]


texts: Adjusting all depth data in a file by some elevation

texts:
The code adds up numbers from two different text files. It opens an input file 'DEPTH.dat' and reads the numbers after some headers as follows:

SCALAR
ND    3
ST    0
TS    1000
1.0
1.0
1.0
SCALAR
ND    3
ST    0
TS    2000
3.3
3.4
3.5
SCALAR
ND    3
ST    0
TS    3000
1.7
1.8
1.9

It then adds to them numbers which have been read from a smaller text file 'ELEVATION.dat' which looks as follows:

SCALAR
ND    3
ST    0
TS    0
10.0
10.0
10.0

The result is written in a text file 'output.txt' like this:

SCALAR
ND    3
ST    0
TS    1000
11.0
11.0
11.0
SCALAR
ND    3
ST    0
TS    2000
13.3
13.4
13.5
SCALAR
ND    3
ST    0
TS    3000
11.7
11.8
11.9

Here's the code in question.  As I have learned from 200_success in my last code review that I should write the code using functions, I tried to write this new code using some functions.

For a small example, the code works properly but for bigger input data, it does not work. (For a 350 MB file with 30 million lines, there is no response after two hours.)  How can the code be improved?

from itertools import zip_longest

def grouper(iterable, n, padvalue=None):
    return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)

def writing_ND(f1):
    for line1 in f1:
        if line1.startswith('ND'):
            ND = float(line1.split()[-1])
            return ND

def writing_TS(f):
    with open(f, 'r') as f:
        for line1 in f:
            if line1.startswith('TS'):
                x = float(line1.split()[-1])
                TS.append(x)
        return TS
TS = []
ND = []
n = 0
add_numbers = []
TS = writing_TS('DEPTH.dat')
with open("ELEVATION_LHP.dat") as f, open("DEPTH.dat") as f1,\
     open('output.txt', 'w') as out:
    ND = writing_ND(f)
    n = int(ND)+4
    f.seek(0)
    for lines in grouper(f, int(n)):
        for item in lines[4:]:
            add_numbers.append(float(item))
    i = 0
    for l in grouper(f1, n):
        data_numbers = []
        for line in l[4:]:
            data_numbers.append(float(line.split()[-1].strip()))
            result_numbers = [x + y for x, y in zip(data_numbers, add_numbers)]
        del data_numbers
        out.write('SCALAR\nND    %d\nST  0\nTS      %0.2f\n' % (ND, TS[i]))
        i += 1
        for item in result_numbers:
            out.write('%s\n' % item)


texts:
I am taking a Ruby class and our assignment was to write a class that takes two users inputs (1. the time, 2. the amount of minutes to move forward).  Then based on the two inputs forward the time by that amount.  I am new to Ruby so any feedback on how to improve my code would be great.

class Timeshift
  @time
  @timeshift
  @hours
  @minutes
  @additional_hours
  @am_or_pm
  @newTime

  def initialize (time, timeshift)
    @time = time
    @timeshift = timeshift
    @hours = 0
    @minutes = 0
    @additional_hours = 0
    @am_or_pm
    @newTime

  end

  def check_is_valid_time
    /^(1[0-2]|0?[1-9]):([0-5][0-9])(\s[A|P]M)\)?$/.match(@time)
  end
  private :check_is_valid_time

  def get_hours
    temp_array = @time.split(':')
    @hours = temp_array[0].to_i
  end
  private :get_hours

  def get_minutes
    temp_array = @time.split('')
    temp_minutes = temp_array[3].to_i * 10
    temp_minutes += temp_array[4].to_i
    @minutes = temp_minutes
  end
  private :get_minutes

  def get_additional_minutes
    while @timeshift >= 1440
      @timeshift -= 1440
    end
  end
  private :get_additional_minutes

  def get_am_or_pm
    temp_array = @time.split('')
    @am_or_pm = temp_array[6]
  end
  private :get_am_or_pm

  def add_minutes
    @minutes += @timeshift
    while @minutes >= 60
      @additional_hours += 1
      @minutes -= 60
    end
  end
  private :get_additional_minutes

  def add_hours
    @hours += @additional_hours
    if @hours >= 13 && @hours < 25
      @hours -= 12;
      if  @am_or_pm == 'A'
        @am_or_pm = 'P'
      else
        @am_or_pm = 'A'
      end
    elsif @hours >= 25
      @hours -= 24;
    end
  end
  private :add_hours

  def add_time ()
    if !check_is_valid_time
       @newTime = "Not a valid time entered"
    else
        get_hours
        get_minutes
        get_am_or_pm
     if @timeshift > 0
        get_additional_minutes
        add_minutes
        add_hours
      end
      @newTime = "#{@hours}:#{@minutes} #{@am_or_pm}M"
    end
     @newTime
  end
end

# 2 minutes in future
time  = "11:55 AM"
timeshift = 2
puts Timeshift.new(time, timeshift).add_time


texts:
I have been trying recently to develop a code finding the next palindrome from a certain number. For example, if the input is 800, the output should be 808, as 808 being the next palindrome from 800.

Here's my code. It's fully functional, but on my online judge I get a problem with the time of the execution. My method is not optimal. Any advice on this?

def reverseNumber(a):
   degreMax = findDegree(a)
   result = 0
   while a != 0:
      r = a % 10
      a = a // 10
      result = result + r*10**degreMax
      degreMax = degreMax - 1
   return result

def findDegree(a):
   degre = 0
   while a >= 10:
     a = a/10
     degre = degre + 1
   return degre

def isPalindrome(a):
   test = False
   if reverseNumber(a) == a:
      test = True
   return test

def nextPalindrome(a):
   while isPalindrome(a) == False:
      a = a + 1
   return a

nbTest = int(raw_input())
inputs = []

for i in range(0,nbTest):
   a = int(raw_input())
   inputs.append(a)

for i in range(0,len(inputs)):
   print nextPalindrome(inputs[i])


texts: MVC4 approach to checking authorization after POST

texts:
I have a very simple form that is designed to update account expiration dates. I'm currently creating a View Model and sending that to the form, however, I still have to pass along a GUID so I know what object is being referenced on POST back.

What I'm worried about it is someone altering the guid (via JS, jQuery, etc..) to match an entity that they're not authorized for. After the form is posted, I'm checking to see if the user making the request matches the username of the entity that maps from the ViewModel (I realize at some point administrators and future permissions will need to be added, I'm keeping it simple for design-pattern sake).

Is this the proper way to do this, or is there a more efficient out of the box approach?

Entity:

public class FtpTrack
{
    [Key]
    public int id { get; set; }
    public string domainUserName { get; set; }
    public string ftpAccountName { get; set; }
    public DateTime expirationDate { get; set; }
}

ViewModel

public class FtpTrackViewModel
{
    public int guid { get; set; }
    public DateTime expirationDate { get; set; }
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(FtpTrackViewModel ftptrackVM)
{
    if (ModelState.IsValid)
    {
        FtpTrack ftptrack = db.FtpTracks.Find(ftptrackVM.guid);
        if (ftptrack.domainUserName == User.Identity.Name.Split('\\')[1])
        {
            ftptrack.expirationDate = ftptrackVM.expirationDate;
            db.Entry(ftptrack).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    return View(ftptrackVM);
}


texts: Using the stack algorithm for parenthesis matching

texts:
I have used Stacks to check for brackets mismatch. (Parentheses matching problem using Stack algorithm)

Any suggestions on how to improve the code?

I have tried various examples and it works without error but I feel there is a lack of specificity. How do I work on that?

Side note: I think there's a stack reference type in Java but I am not allowed to use that.

import java.util.Scanner;
class ParensMatching
{
    static  Character Stack[]= new Character[25];
    static int ptr = -1;

    static void push(char ch)
    {
        if(ptr+1 < 25)
        {
            Stack[++ptr]= ch;
        }
        else
        {
            System.out.println("Overflow!! ");
        }

    }

    static int pop()
    {

        if (ptr == -1)
        {
            System.out.println("Underflow!!");
            return 999;
        }
        int value = Stack[ptr];
        ptr = ptr-1;
        return value;
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while(true)
        {
            System.out.println("Enter a string");
            String str = sc.nextLine();
            char temp;
            int i = 0;
            outer:
            for (i = 0; i< str.length(); i++)
            {
                if(str.charAt(i)== '('|| str.charAt(i)== '{' || str.charAt(i)== '[')
                {
                    push(str.charAt(i));
                    temp = str.charAt(i);
                }
                else if(str.charAt(i)== ')')
                {
                    if(pop()!= '(')
                    {
                        System.out.println("Unmathced parens, exitting! ");
                        break outer;
                    }
                }
                else if(str.charAt(i)== '}')
                {
                    if(pop()!= '{')
                    {
                        System.out.println("Unmathced parens, exitting! ");
                        break outer;
                    }
                }
                else if(str.charAt(i)== ']')
                {
                    if(pop()!= '[')
                    {
                        System.out.println("Unmathced parens, exitting! ");
                        break outer;
                    }
                }
            }
            if(ptr != -1)
            {
                System.out.println("Missing closing parens!!");
            }
            else if (i == str.length())
            {
                System.out.println("Success. No unmatched parens");
            }
            System.out.println("Enter 2 to stop testing");
            int n = sc.nextInt();
            if(n == 2)
                break;
            else
                continue;
        }

    }
}


texts:
I am writing simple formatter for valid JSON. Is reads JSON data from stdin and writes formatted output to stdout.

Goals:

given valid input produce valid formatted JSON output
constant memory usage
minimal viable program (smallest program that solves a particular problem)
feature free
easy to read and understand
be C99 compatible

Non-goals:

validating JSON
handling arguments

I am not aiming JSON validation right now (as said "formatter for valid JSON").

I tried adding arguments (like setting placeholder string with -p) but faced several issues:

unclear what arguments must be implemented
I don't feel comfortable yet writing argument parsing code.

So I skipped these for now.

Latest file in GitHub: https://github.com/sineemore/juu/blob/master/juu.c

#include <stdio.h>
#include <stdlib.h> /* EXIT_SUCCESS */

#define BUF_SIZE (1024 * 4)

int main(int argc, char **argv) {

    char buf[BUF_SIZE];
    const char placeholder[] = "  ";
    unsigned int indent = 0;
    unsigned int i = 0;
    unsigned int k = 0;
    char is_string = 0;
    char escaped = 0;
    char ch;
    size_t n;

    while (0 < (n = fread(&buf, sizeof(char), BUF_SIZE, stdin))) {
        for (k = 0; k < n; k++) {
            ch = buf[k];

            if (is_string) {
                /* Inside quoted string */
                putchar(ch);
                if (! escaped) {
                    if (ch == '"') {
                        /* Unescaped quote, string just ended */
                        is_string = 0;
                    } else if (ch == '\\') {
                        escaped = 1;
                    }
                } else {
                    escaped = 0;
                }
                continue;
            }

            switch (ch) {

            case ' ':
            case '\t':
            case '\n':
            case '\r':
                /* Ignoring original formatting */
                break;

            case '{':
            case '[':
                putchar(ch);
                putchar('\n');
                i = ++indent;
                while (i-- > 0) fputs(placeholder, stdout);
                break;

            case '}':
            case ']':
                putchar('\n');
                i = --indent;
                while (i-- > 0) fputs(placeholder, stdout);
                putchar(ch);
                if (indent == 0) putchar('\n');
                break;

            case ',':
                putchar(',');
                putchar('\n');
                i = indent;
                while (i-- > 0) fputs(placeholder, stdout);
                break;

            case ':':
                putchar(':');
                putchar(' ');
                break;

            case '"':
                /* String/property key start, see if clause on top (line 20) */
                putchar('"');
                is_string = 1;
                break;

            default:
                /* Numbers, true, false, null */
                putchar(ch);
                break;
            }
        }
    }

    return EXIT_SUCCESS;
}

Example output:

$ wget -qO- 'https://xkcd.com/info.0.json' | juu
{
  "month": "4",
  "num": 1979,
  "link": "",
  "year": "2018",
  "news": "",
  "safe_title": "History",
  "transcript": "",
  "alt": "HISTORIANS: We've decided to trim the past down to make things more manageable. Using BCE/CE, would you rather we lose the odd-numbered or even-numbered years?",
  "img": "https://imgs.xkcd.com/comics/history.png",
  "title": "History",
  "day": "11"
}

UPDATE:

I missed ALL ferror() calls, fixing this part.
Also program doesn't handle SIGPIPE, therefore it may be killed. Just tested it. I don't see a clear solution, should I set SIG_IGN?


texts:
I'm writing a service for a ORPG and I expect traffic of about 10kb of packets per second from multiple clients. I just want to know if my approach is correct? Are there areas I can improve?

This is a bit basic the full app would have a lot more handlers and packet structs.

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "io"
    "net"
)

var handlers map[uint16]func(conn net.Conn, data []byte)
var currDataVer uint16 = 100

type Packet struct {
    Length, ID uint16
}

// 1000+ more packet types with different fields
type VersionPacket struct {
    Packet
    Client, Upgrade, Data uint16
}

func main() {
    handlers = make(map[uint16]func(conn net.Conn, data []byte))

    listener, err := net.Listen("tcp", "127.0.0.1:2222")
    if err != nil {
        return // or panic?
    }
    defer listener.Close()

    // possibly up to 1000 handlers
    handlers[300] = func(conn net.Conn, data []byte) {
        var pVer VersionPacket

        err := binary.Read(bytes.NewReader(data), binary.LittleEndian, &pVer)
        if err != nil {
            return
        }

        // if version does not match
        if currDataVer != pVer.Data {
            resp := bytes.NewBuffer(make([]byte, 2))
            binary.Write(resp, binary.LittleEndian, uint16(100)) // packet id
            binary.Write(resp, binary.LittleEndian, uint16(13))  // packet data
            binary.Write(resp, binary.LittleEndian, uint16(35))
            binary.Write(resp, binary.LittleEndian, uint16(0))
            resb := resp.Bytes()
            binary.LittleEndian.PutUint16(resb, uint16(len(resb)))
            fmt.Println(resb)
            conn.Write(resb)
        } else {
            resp := bytes.NewBuffer(make([]byte, 2))
            binary.Write(resp, binary.LittleEndian, uint16(1001)) // packet id
            binary.Write(resp, binary.LittleEndian, uint16(60))   // packet data

            for i := 0; i < 2; i++ {
                binary.Write(resp, binary.LittleEndian, uint16(i))
            }

            resb := resp.Bytes()
            binary.LittleEndian.PutUint16(resb, uint16(len(resb)))
            conn.Write(resb)

            resp = bytes.NewBuffer(make([]byte, 2))
            binary.Write(resp, binary.LittleEndian, uint16(1002)) // packet id
            binary.Write(resp, binary.LittleEndian, uint16(61))   // packet data

            for i := 0; i < 3; i++ {
                binary.Write(resp, binary.LittleEndian, uint16(i))
            }

            resb = resp.Bytes()
            binary.LittleEndian.PutUint16(resb, uint16(len(resb)))
            conn.Write(resb)
        }
    }

    for {
        conn, err := listener.Accept()
        if err != nil {
            break
        }

        go process(conn)
    }
}

func process(conn net.Conn) {
    buffer := make([]byte, 2000)

    for {
        _, err := io.ReadFull(conn, buffer[:2])
        if err != nil {
            // error
            break
        }

        length := binary.LittleEndian.Uint16(buffer)

        if length > 2000 {
           // error too long
           // consume ignore continue
           // or disconnect
           conn.Close()
           return
        }

        // length only packet (keepalive)
        if length <= 2 {
            continue
        }

        _, err = io.ReadFull(conn, buffer[2:length-2])
        if err != nil {
            break
        }

        packetID := binary.LittleEndian.Uint16(buffer[2:])

        handler, ok := handlers[packetID]
        if ok {
            handler(conn, buffer[:length])
        } else {
            fmt.Println("packet with no handler:", packetID)
        }
    }
}

Is creating a new goroutine per accepted client worth it? I'm expecting about 500-1000 daily unique clients.
Will using the handler handlers[300] from multiple go routines result in a race condition?
Can the creation of packets be improved (DRY)?
Should I check the length of a []byte every time I try to access with an index to avoid getting a panic?
How about the error handling?


texts: Query the github api and filter the last 1000 commits which include and exclude certain words from the top 3 repositories in a given organization

texts:
This code should query the github api and filter, out of the last 1000 commits, which ones include and exclude certain words from the top 3 repositories in a given organization.
For example, I could query the endpoint /search with parameters such as org:facebook and include:fixed exclude:try. This should then return, out of the 3 most popular facebook repositories, and out of the 1000 most recent commits, the commit messages which include and exclude fixed and try, respectively.
from flask import Flask, request
import requests
import json

app = Flask(__name__)

NUM_REPOS = 3
MAX_PER_PAGE = 100
NUM_PAGES = 10
HEADERS = {"Accept": "application/vnd.github.cloak-preview"}

def get_matches():
    if request.method == 'POST':
        try:
            org = request.get_json()["org"]
            include = request.get_json()["include"]
            word_to_ignore = request.get_json()["ignore"]

        except:
            return {"error": "your request is missing the 'org', 'include' or 'ignore' parameters"}

        repo_data = requests.get( f"https://api.github.com/search/repositories?q=org:{org}&sort=stars&order=desc&per_page={NUM_REPOS}").content
        repo_data_dict = json.loads(repo_data.decode('utf-8'))

        if not "items" in repo_data_dict:
            if "errors" in repo_data_dict:
                return {"invalid_organization": f"{org} does not exist or doesn't have any repositories"}
            else:
                return {"reached_api_limit": True}
        else:
            repo_list = repo_data_dict["items"]

        matches = []

        for repo in repo_list:
            repo_info = {}
            repo_name = repo["name"]

            repo_info["repo"] = repo_name

            page = 1
            items_exist = True
            total_count = 0

            while (items_exist and page <= NUM_PAGES):
                commits = requests.get( f"https://api.github.com/search/commits?q={include} repo:{org}/{repo_name}&per_page={MAX_PER_PAGE}&page={page}", headers=HEADERS).content
                commits = json.loads(commits.decode('utf-8'))

                if "message" in commits:
                    matches.append({"reached_api_limit": True})
                    return {"matches": matches}

                if "items" in commits and len(commits["items"]) > 0 and (page == 1 or commits["total_count"] > page-1 * MAX_PER_PAGE):

                    for commit in commits["items"]:

                        if word_to_ignore in commit["commit"]["message"]:
                            continue

                        repo_info["message"] = commit["commit"]["message"]

                        matches.append(repo_info)

                        if commits["total_count"] < MAX_PER_PAGE:
                            items_exist = False

                else:
                    items_exist = False

                page += 1

        return {"matches": matches}

@ app.route('/search', methods=['POST'])
def example():
    return get_matches()

if __name__ == '__main__':
    app.run()


texts: Print all permutations with repetition of characters

texts:
Given a string of length n, print all permutation of the given string.
  Repetition of characters is allowed. Print these permutations in
  lexicographically sorted order

Examples:

Input: AB

Ouput: All permutations of AB with repetition are:

  AA
  AB
  BA
  BB

Input: ABC

Output: All permutations of ABC with repetition are:

   AAA
   AAB
   AAC
   ABA
   ...
   ...
   CCB
   CCC

The following is my code:

void permutate(const string& s, int* index, int depth, int len, int& count)
{
    if(depth == len)
    {
        ++count;
        for(int i = 0; i < len; ++i)
        {
            cout << s[index[i]];
        }
        cout << endl;
        return;
    }

    for(int i = 0; i < len; ++i)
    {
        index[depth] = i;
        permutate(s, index, depth+1, len, count);
    }
}

int main()
{
    string s("CBA");
    sort(s.begin(), s.end());
    cout << s << endl;
    cout << "**********" << endl;
    int len = s.size();
    int* index = new int[len];
    int count = 0;
    permutate(s, index, 0, len, count);
    cout << count << endl;

    system("pause");
    return 0;
}


texts:
Here's my implementation of sorting a stack in ascending order. The problem statement is as follows :

  Write a program to sort a stack in ascending order (with biggest items on top).
  You may use at most one additional stack to hold items, but you may not copy
  the elements into any other data structure (such as an array). The stack supports
  the following operations: push, pop, peek, and isEmpty.

My Algorithm :
Take two stacks I'll call it myStack and helperStack.

If helper stack is empty, simply pop from myStack and push it to helperStack.
If top of helperStack is less than the top of myStack, then pop it from myStack and push it to helperStack. Recurse on two Stacks.
If top of helperStack is less greater than the top of myStack then, recursively pop from helperStack and push it to myStack until the condition is violated. Finally push it to the right position.
End if myStack isEmpty.

Code

static class Node{
    int data;
    Node next;

    Node(int data){
        this.data = data;
    }
}

static class Stack{
    Node top;
    String name;
    Stack nextStack;

    public boolean isEmpty(){
        return top==null;
    }

    Stack(String name){
        this.name = name;
    }

    public int pushTo(Stack anotherStack){
        int popped = this.pop();
        anotherStack.push(popped);
        return popped;
    }

    public void _push(int data){
        System.out.println("Pushing : " + data + " to " + this.name);
        if(top==null){
            top = new Node(data);
        }else{
            Node temp = new Node(data);
            temp.next = top;
            top = temp;
        }

    }

    public void push(int... data){
        for(int i : data){
            this._push(i);
        }
    }

    public int pop(){
        if(top==null){
            System.out.println("Error : Stack is empty!!");
            return -1;
        }
        System.out.println("Popping " + top.data + " from " + this.name);
        Node toRet = top;
        top = top.next;
        return toRet.data;
    }

    public int peek(){
        return top.data;
    }

    public void printStack(){
        Node temp = top;
        while(temp.next!=null){
            System.out.print(temp.data + "->");
            temp = temp.next;
        }
        System.out.println(temp.data);
    }

}//End of Class Stack

public static void sortStack(Stack myStack, Stack helperStack, int curr){
    if(myStack.isEmpty()){
        return;
    }
    if(curr==-1)
        curr = myStack.pop();
    if(helperStack.isEmpty() || curr > helperStack.peek()){
        helperStack.push(curr);
        sortStack(myStack, helperStack, -1);
    }else{
        helperStack.pushTo(myStack);
        sortStack(myStack, helperStack, curr);
    }
}

public static void main(String[] args) {
    Stack someStack = new Stack("someStack");
    Stack helperStack = new Stack("helperStack");
    someStack.push(1,2,3, 200, 4, 22);
    someStack.printStack();
    sortStack(someStack, helperStack, -1);
    helperStack.printStack();
}

Analysis

In worst case , the number of steps executed : n (for popping it out from helperStack) + 1 (pushing the current element at right place) + n (for popping elements out from myStack).
So,
T(n) = 2n + 1

Solving this recurrence, I get a complexity of \$\theta\$(\$2^n\$)
Hence, the algorithm runs in exponential time. Is there any way I could make it faster without violating the condition?

Feel free to suggest and criticize :)


texts:
I wanted to compare radix_sort to quick_sort for values limited to 0..127 so I implemented this :

void bin_radix_sort(int *a, const size_t size, int digits) {
    assert(digits % 2 == 0);

    int *b = malloc(size * sizeof(int));

    for (int exp = 0; exp < digits; exp++) {
        // Count elements
        size_t count[2] = {0};
        for (size_t i = 0; i < size; i++)
            count[(a[i] >> exp) & 1]++;

        // Cumulative sum
        count[1] += count[0];

        // Build output array
        for (int i = size - 1; i >= 0; i--)
            b[--count[(a[i] >> exp) & 1]] = a[i];

        int *p = a; a = b; b = p;
    };

    free(b);
}

I was able to compare it to qsort with :

struct timespec start;

void tic() {
    timespec_get(&start, TIME_UTC);
}

double toc() {
    struct timespec stop;
    timespec_get(&stop, TIME_UTC);
    return stop.tv_sec - start.tv_sec + (
        stop.tv_nsec - start.tv_nsec
    ) * 1e-9;
}

int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int main(void) {
    const size_t n = 1024 * 1024 * 50;
    printf("Init memory (%ld MB)...\n", n / 1024 / 1024 * sizeof(int));
    int *data = calloc(n, sizeof(int));
    printf("Sorting n = %ld data elements...\n", n);
    size_t O;

    tic();
    O = n * log(n);
    qsort(data, n, sizeof(data[0]), cmpfunc);
    printf("%ld %lf s\n", O, toc());
    int d = 6;

    tic();
    O = d * (n + 2);
    bin_radix_sort(data, n, d);
    printf("%ld %lf s\n", O, toc());
}

This gives me this output:

$ gcc -Os bench.c -lm
$ ./a.out
Init memory (200 MB)...
Sorting n = 52428800 data elements...
931920169 1.600909 s
314572812 0.963436 s

I guess my code needs code-review since I was expecting to be six times better than quick sort.


texts:
I've been into trying to have an as simple as possible dependency container in Python and with your help managed to conceive TinyDIC, many thanks.
Now, I use Flask for my apps, and from by background with other languages I'm used to the idea of injecting dependencies into my controllers with the typical MVC frameworks. Flask advocates for using simple functions to handle the requests, rather than classes (although it supports class based views). Those functions are invoked by Flask dynamically upon receiving web requests and there's not much I could do with them in what regards to passing stuff for them. (Maybe I could use some globals like g or current_app inside the view to get the dependencies I need, but I don't like it, feels like using a Service Locator and taking instead of asking).
Luckily 2 things occurred to me recently:

Python3.5 supports type hints

Python has decorators that allow me to "modify" functions

So, I came with this idea, that:

we just write the view functions taking the dependencies we want to inject first and with type hints.
we put a decorator on the views that will read those type hints and using partial application modify the function to have the dependencies inject and just return a view with just enough params to handle the HTTP request.

POC code is below and I'd really appreciate your feedback.

from functools import partial
import inspect
from flask import Flask

class Container(object):
    def __init__(self):
        self._registry = {}

    def register(self, key, value, constant=False):
        if constant:
            self._registry[key] = lambda container: value
        else:
            self._registry[key] = value

    def inject(self, func):
        func_name = func.__name__
        type_hints = zip(func.__annotations__.keys(), func.__annotations__.values())
        for parameter_name, parameter_type in type_hints:
            if parameter_name == 'return': break
            # NOTE: Assumes we're doing the right thing: depending on the interface and not the implementation
            parameter_instance = self._registry.get(parameter_type.__qualname__)(self)
            func = partial(func, parameter_instance)
        func.__name__ = func_name  # NOTE: required by Flask
        return func

class UpperCaseFormatter:
    def __init__(self):
        pass

    def format(self, string):
        return string.upper()

# Composition root
# ---
container = Container()
container.register(UpperCaseFormatter.__qualname__, UpperCaseFormatter(), True)

# Web app
# ---
app = Flask(__name__)

@app.route('/<name>')
@container.inject # NOTE: must come first so final view version with dependencies already injected is pass to Flask's app.route
def index_action(formatter: UpperCaseFormatter, name):
    return formatter.format(name)

app.run(debug=True)

Initial considerations on advantages:

the required dependencies to handle the request are explicitly declared.
we obey the principle of ask don't take (from g or current_app).


texts: Checking the GridColumnType using a switch statement

texts:
I am trying to refactor a switch statement. I know that you can replace a switch with a Dictionary, or a strategy pattern but it kind of feels like overkill for what I have.

Switch

var filters = new List<ColumnFilter>();
switch (gridColumnDataType)
                {
                    case "System.String":
                        if (filterColumnType != typeof(RuleTextNode))
                            filters.Add(columnFilter);
                        break;
                    case "System.DateTime":
                        if (filterColumnType != typeof(RuleDateNode))
                            filters.Add(columnFilter);
                        break;
                    case "System.Boolean":
                        if (filterColumnType != typeof(RuleBoolNode))
                            filters.Add(columnFilter);
                        break;
                    default:
                        if (gridColumnType.IsNumericType())
                            if (filterColumnType != typeof(RuleNumberNode))
                                filters.Add(columnFilter);
                        break;
                }
            }

Explanation

I have a grid and each grid column has its own datatype column. Like DataType = "String.DateTime" And there is a filter on each column. Now the problem is every now and again the filter an column does not have the same DataType. Thank you Infragistics.

What the switch is doing is checking what the GridColumnType is and if it's, let's say, a System.String, the FilterColumnType should be of type RuleTextNode. If it is not, I am just adding it in the ColumnFilter List.

All the RuleTypes have the same underlying type FilteringNode.

Having said all of that, what would be the best way the rewrite the switch to avoid the code duplication and the switch?


texts: Using Threading.Event to signal main thread

texts:
I was reading on this page about using a thread, catching an exception, and notifying the calling thread.

The answer suggested Queue, but in the comments it states:

  Queue is not the best vehicle to communicate an error back, unless you
  want to have a full queue of them. A much better construct is
  threading.Event()

From the Python documentation:

  This is one of the simplest mechanisms for communication between
  threads: one thread signals an event and other threads wait for it.

I'm new to multi threading and I wanted to give it a try, so I came up with this trivial example. I'm unsure if I'm on the right track.

import threading

def dividebyzero(event,first,second):
    try:
        result = first / second
    except ZeroDivisionError:
        event.set()
        print("Can't divide by 0")
    else:
        print(result)

e = threading.Event()
t1 = threading.Thread(name='DivideByZero',target=dividebyzero, args=(e, 10, 0),)

t1.start()
t1.join()

if e.is_set():
    print("Error occurred in division thread")

Question:

Using threading.Event as shown in my example, is it the correct way to signal the main thread an error as occurred?
I'm not using event.wait() because it seems unnecessary, I call join() on the t1 thread, so when I call is_set() hopefully I'll get an accurate result. Is it mandatory to use event.wait() when using threading.event()
I understand that if I needed to raise more exceptions using an event probably isn't ideal, how would you know which exception was raise? In that situation would a Queue be better?

If I were to use event.wait() there is a chance the main thread could hang forever, because if the exception doesn't occur the event is never set.

I don't have an error or problems with the code, it works, I just want it reviewed to make sure I used event correctly.


texts: Converting models into a list of ViewModels

texts:
I have the following code:

public abstract class BaseViewModel<PrimaryKey, ModelType>
{
    //Some base fields

    public static List<T> Convert<T>(IEnumerable<ModelType> collection)
        where T : BaseViewModel<PrimaryKey, ModelType>, new()
    {
        var list = new List<T>();

        if (collection != null)
        {
            foreach (var item in collection)
            {
                var view = new T();
                view.Value = item;

                list.Add(view);
            }
        }

        return list;
    }
}

Of course, it works because it requires to I set a generic type.

var list = GroupViewModel.Convert<GroupViewModel>(model);

There is GroupViewModel extends from BaseViewModel. But how can I reduce this generic casting to it will get GroupViewModel type automaticaly when I call it so: var list = GroupViewModel.Convert(model);.
Is it possible? Just I learn C# only.


texts: Comparing dates (without the time part) in Java

texts:
In my current project, I have to deal a lot with dates, especially checking if the date entered by user is today, or max one year from today etc. As I find the datetime API of Java7 (which I regrettably still have to use) pretty confusing, in order to keep my code clean and readable, I wrote the following method:

public static int compareDates(Date date1, Date date2) {
    SimpleDateFormat math = new SimpleDateFormat("yyyyMMdd"); // I'm working with servlets, so keeping it thread-safe
    Long date1asLong = new Long(math.format(date1));
    Long date2asLong = new Long(math.format(date2));
    return date1asLong.compareTo(date2asLong);
}

// usage, e.g. to find if the date entered by user is greater than today
if (MyDateUtils.compareDates(dateFromUser, new Date()) > 0) {
    // do the work
} else {
    // scream
}

Anyway, I am not sure whether this approach has any serious drawbacks, so I am throwing it here for review. Looking forward to your comments.


texts:
I have an application using tkinter where different actions are required on mouse click, double click and when the mouse is being moved. The following class works however I wonder if there is no easier- or tkinter builtin way of doing this?

from tkinter import Tk, Canvas

class MouseControl:
    '''  Class for mouse control to establish if there is a 'click',
         'double click' or mouse is being moved '''
    def __init__(self, aw):
        self.double_click_flag = False
        self.button_released_flag = False
        self.aw = aw
        self.aw.bind('<Button-1>', self.clicked)  # bind left mouse click
        self.aw.bind('<Double-1>', self.double_click)  # bind double left clicks
        self.aw.bind('<ButtonRelease-1>', self.button_released)  # bind button release
        self.aw.bind('<B1-Motion>', self.moved)  # bring when mouse is moved

    def clicked(self, event):
        '''  add a little delay before calling action to allow for double click
         and button released to have occurred '''
        self.double_click_flag, self.button_released_flag = False, False
        self.aw.after(300, self.action, event)

    def double_click(self, event):
        '''  set flag when there is a double click '''
        self.double_click_flag = True

    def button_released(self, event):
        '''  set flag when button is released '''
        self.button_released_flag = True

    def moved(self, event):
        '''  define action on when mouse is moved in this case just printing
             the coordinates'''
        print('mouse position is at ({:03}. {:03})'.
              format(event.x, event.y), end='\r')

    def action(self, event):
        '''  define action on click and double click in this case just printing
             the event '''
        if self.button_released_flag:

            if self.double_click_flag:
                print('double mouse click event')

            else:
                print('single mouse click event')

root = Tk()
window = Canvas(root, width=400, height=400, bg='grey')
mouse = MouseControl(window)
window.place(x=0, y=0)
window.mainloop()


texts: Class to unit-test functions, with rudimentary support for testing multi-parameter functions

texts:
Recently I read about test-driven-design and decided to try to create a simple unit testing class to begin using this approach. I have not been programming in Python for very long so forgive my ignorance of the language.

I would like to discuss better approaches to handling multi-parameter test functions. Right now I accept a tuple (of varying length) with one or more function inputs.

I find the tuple input and "length" checks (lines 10-13) to be clunky. Is there a better way to handle this? I tried using a spread operator to distribute the arguments into the test function but this fails for list inputs (it spreads the list input itself rather than inserting it as the argument).

Like I said this is very basic and I'm sure there are modules out there I can import to do a much more thorough job. I learn best when I try something myself so while I appreciate any suggestions for external modules I'd like to focus on improving this class itself.

class Unit_Tester:
  def __init__(self, function, tests):
    self.function_to_test = function
    self.test_list = tests

  def unit_test(self, function_to_test, test_input, expected_output):
      try:
          number_of_inputs = len(test_input)
          if number_of_inputs == 1: function_output = function_to_test(test_input)
          elif number_of_inputs == 2: function_output = function_to_test(test_input[0], test_input[1])
          elif number_of_inputs == 3: function_output = function_to_test(test_input[0], test_input[1], test_input[2])
          elif type(test_input) == list: function_output = function_to_test(test_input)
      except Exception as error:
          print("Error occurred with test input: [{0}] value: {1}\nError Message: {2}\nCorrect the error and try again.\n"
          .format(type(test_input), test_input, error))
      else:
        try:
            assert function_output == expected_output
            print(self.unit_test_response(True, test_input, function_output, expected_output))
        except AssertionError:
            print(self.unit_test_response(False, test_input, function_output, expected_output))

  def unit_test_response(self, correct, test_input, function_output, expected_output):
      score = "Test Passed" if correct else "Test Failed"
      return "{0}\nInput: {1}\nExpected Output: {2}\nFunction Output: {3}\n".format(score, test_input, expected_output, function_output)

  def run_unit_tests(self, function_to_test, test_list):
      for test_tuple in test_list:
          test_input, expected_output = test_tuple
          self.unit_test(function_to_test, test_input, expected_output)

  def run(self):
    self.run_unit_tests(self.function_to_test, self.test_list)


texts: Calculating if vehicle's mileage is in service window

texts:
I'm trying to calculate whether a given vehicle's mileage is within the recommended service windows.

For example, if a fuel filter replacement is every 15,000 miles and the service window is 5,000 miles, then a vehicle is within the service window from 12,500-17,500 miles, 27,500-32,500 miles, etc.

My current logic works (I think), but I'm not sure if it's too convoluted or if there are better ways of figuring this out:

$mileage = 27500;
$service = 15000;
$window = 2500;
$is_due = $mileage < $service
    ? $service - $mileage <= $window
    : $mileage % service <= $window
        || abs($mileage % $service - $service) <= $window;


texts: Is this an efficient way to use one event for multiple controls?

texts:
I've got a NumericUpDown control for each denomination of money and all of the events run the exact same code save for a single line so I'm trying to condense them into 1 event. I was originally going to use a switch but you can't switch on a non-value object so I just did an if tree. Is there a better way to do this?

private void BankInChanged(object sender, EventArgs e)
    {
        var objSender = (NumericUpDown) sender;

        if(objSender == bkI_Ls_Quarters)
        {
            currBoat.inBank.setQuarters(Convert.ToInt32(bkI_Ls_Quarters.Value));
        }
        else if(objSender == bkI_Rl_Quarters)
        {
            currBoat.inBank.setQuarterRolls(Convert.ToInt32(bkI_Rl_Quarters.Value));
        }
        else if(objSender == bkI_Ls_Nickels)
        {
            currBoat.inBank.setNickels(Convert.ToInt32(bkI_Ls_Nickels.Value));
        }
        else if(objSender == bkI_Rl_Nickels)
        {
            currBoat.inBank.setNickelRolls(Convert.ToInt32(bkI_Rl_Nickels.Value));
        }
        else if(objSender == bkI_Ls_Dimes)
        {
            currBoat.inBank.setDimes(Convert.ToInt32(bkI_Ls_Dimes.Value));
        }
        else if(objSender == bkI_Rl_Dimes)
        {
            currBoat.inBank.setDimeRolls(Convert.ToInt32(bkI_Rl_Dimes.Value));
        }
        else if(objSender == bkI_Ls_Pennies)
        {
            currBoat.inBank.setPennies(Convert.ToInt32(bkI_Ls_Pennies.Value));
        }
        else if(objSender == bkI_Rl_Pennies)
        {
            currBoat.inBank.setPennyRolls(Convert.ToInt32(bkI_Rl_Pennies.Value));
        }
        else if(objSender == bkI_Ones)
        {
            currBoat.inBank.setOnes(Convert.ToInt32(bkI_Ones.Value));
        }
        else if(objSender == bkI_Fives)
        {
            currBoat.inBank.setFives(Convert.ToInt32(bkI_Fives.Value));
        }
        else if(objSender == bkI_Tens)
        {
            currBoat.inBank.setTens(Convert.ToInt32(bkI_Tens.Value));
        }
        else if(objSender == bkI_Twenties)
        {
            currBoat.inBank.setTwenties(Convert.ToInt32(bkI_Twenties.Value));
        }
        else if(objSender == bkI_Fifties)
        {
            currBoat.inBank.setFifties(Convert.ToInt32(bkI_Fifties.Value));
        }
        else if(objSender == bkI_Hundreds)
        {
            currBoat.inBank.setHundreds(Convert.ToInt32(bkI_Hundreds.Value));
        }
        currBoat.updateTotals();
        updateStatDisplay();
    }


texts: Automatically checking argument types in commands of a Telegram bot

texts:
I am writing a simple Telegram bot in Python 3 using the python-telegram-bot library. A command is a Telegram message that looks like this: /command_name arg1 arg2 arg3.... The bot should handle the users' messages by changing its internal state and making responses to the users.

I was not very happy with the 'command handling' provided by the library because this code is not beautiful at all and is very noisy:

def caps(update, context):
    text_caps = ' '.join(context.args).upper()
    context.bot.send_message(chat_id=update.message.chat_id, text=text_caps)

caps_handler = CommandHandler('caps', caps)
dispatcher.add_handler(caps_handler)

So I wanted to create a more convenient way, and now a command looks like this:

@cmd('hello')
def cmd_hello(msg, a:int, b:[float], c:str):
    s = ''
    s += 'Number: '+str(a)+'\n'
    s += 'Floats: '+str(b)+'\n'
    s += 'String: '+c
    return s

If i send this command: /hello 1 3.14 5 3.7 world to the bot, the response will be:

Number: 1
Floats: [3.14, 5.0, 3.7]
String: world

I am using the inspect module to read the argument annotations of a function and store them in a dict:

Cmd = namedtuple('Cmd',['func','patterns'])
commands = dict()

def cmd(name):
    def deco(func):
        args = []
        sig = signature(func)

        for arg_name, param in sig.parameters.items():
            ann = param.annotation
            if ann:
                args.append(ann)
            else:
                args.append(str)

        args.pop(0)
        commands[name] = Cmd(func, tuple(args))
        return func
    return deco

The process_args function takes: 1) a list of raw (str) arguments that a bot receives in a message, 2) a list of patterns to match the arguments; and returns a list of processed (converted) arguments or raises CmdError if the arguments are incorrect.

def process_args(args, patterns):
    patterns = list(patterns)

    processed = []
    while patterns:
        if not args:
            raise CmdError("Not enough arguments")

        pattern = patterns.pop(0)

        if pattern in (int, float, str):
            arg = args[0]
            try:
                converted = pattern(arg)
            except Exception:
                raise CmdError(f"Cannot parse argument {arg} as {pattern.__name__}")
            args.pop(0)
            processed.append(converted)

        elif isinstance(pattern, list):
            pat_single = pattern[0]
            collected = []

            match = True
            while match:
                try:
                    x = process_args([args[0]], [pat_single])[0]
                except CmdError: # If the pattern isn't matched anymore
                    match = False
                else:
                    collected.append(x)
                    args.pop(0)
            processed.append(collected)

    return processed

This function looks really bad. Is there a better way of implementing a pattern matching like this?


texts: Process files in a directory and upload them to URL

texts:
I have some code that I wrote for a personal project which takes, as arguments, a directory and a URL. It then processes the files in the named directory, archives them, and uploads the archive to the specified URL.

I have heard that there are many ways to do this(TIMTOWTDI), particularly, with globs. I am hesitant to change working code, but I am interested in possible optimizations that may be possible with "globbing".

What can I do to make my code more idiomatic?

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper qw(Dumper);
use File::Spec qw(catfile rel2abs);
use Digest::SHA qw(sha256_hex);
use Archive::Tar;
use JSON;
use HTTP::Request::Common;
use LWP::UserAgent;

my $dir = $ARGV[0];
my $url = $ARGV[1];
my $fullpath;
my $fullsize;
my $fullid;
my @AoH;
my @checksumfiles;
my $archive = "archive.tar.gz";

opendir DIR, $dir or die "cannot open dir $dir: $!\n";
chdir $dir or die "cannot navigate to dir $dir: $!\n";

while(my $file = readdir DIR) {
    next unless(-f File::Spec->catfile($dir, $file));
    next if($file =~ m/^\./);

    $fullpath = File::Spec->rel2abs($file);
    $fullsize = -s File::Spec->catfile($dir, $file);
    $fullid   = sha256_hex($fullpath);

    my %hash = (
        path    =>  $fullpath,
        size    =>  $fullsize,
        id      =>  $fullid,
    );

    push(@AoH, \%hash);
}
my @array;
for my $i(0..$#AoH) {
    no warnings 'uninitialized';
    my ($ext) = $AoH[$i]{path} =~ (/(\.[^.]+)$/);
    my $idext = $AoH[$i]{id} . $ext;
    push(@checksumfiles, $idext);
    push(@array, $AoH[$i]{path});
}

my $manifest = JSON->new->pretty->encode(\@AoH);

my $filename = "manifest.json";
open my $fh, '>', $filename or die "could not open file $filename: $!\n";
print $fh $manifest;
close $fh;

my $tar = Archive::Tar->new;
$tar->add_files(@array);
$tar->write($archive);
my @file_objs = $tar->read($archive);

for my $i(0..$#file_objs) {
    $file_objs[$i]->rename($checksumfiles[$i]);
}

$tar->add_files($manifest);
$tar->write($archive, COMPRESS_GZIP);

my $browser = LWP::UserAgent->new;
my $useragent = LWP::UserAgent->new(
    env_proxy   => 1,
    keep_alive  => 1,
    timeout     => 120,
    agent       => 'Mozilla/5.0',
);

my $req = POST $url,
    Content_Type    => 'form-data',
    Content         => [ pageAction => 'upload', file => [$archive] ];

$useragent->request($req);

#print Dumper sort \@array;
#print Dumper sort \@checksumfiles;
#print Dumper sort \@AoH;


texts: Creating a specific distribution of random numbers in Powershell

texts:
I originally posted this on StackOverflow but was requested to post it here instead as it relates to optimization/performance of the code rather than a specific problem.
TL;DR: Get-Random produces an even distribution of numbers where every number in the pool has an even chance of appearing. I'm looking for a way to generate random numbers where every individual number appears with a frequency that I myself specify.

If I run
for($i=1;$i -le 1000;$i++){
    Get-Random -Minimum 0 -Maximum 10
}

I get a very evenly distributed count for each number (roughly 100 for each number between 0 and 9). Using Get-Random allows me to get a random number every time but on average, every individual result will appear roughly an equal amount of times. I want to decide the frequency for how often any specific number appears, and then generate random numbers that fit that distribution. As an example:
Number   Probability
0        10
1        11
2        19
3        12
4        3
5        10
6        6
7        7
8        4
9        18

I'm looking for a way to use the above list to randomly generate a number between 0 to 9, but with the probability of each individual number appearing using the Probability column.
My very hard-coded and not so generic solution so far is that I thought of doing something like adding a cumulative percentage column:
Number   Probability   CumulativeProbability
0        10            10
1        11            21
2        19            40
3        12            52
4        3             55
5        10            65
6        6             71
7        7             78
8        4             82
9        18            100

And from here, run the object through a filter. Something like:
$RandomNumber = Get-Random -Minimum 0 -Maximum 100
$MyProbabilityObject | Where-Object {$RandomNumber -ge $_.CumulativeProbability}

This gives me all numbers with a lower Cumulative probability than the random number. Let's say the $RandomNumber was 42, that would result in:
Number   Probability   CumulativeProbability
0        10            10
1        11            21
2        19            40

From here, I could pipe the result to
Select-Object CumulativeProbability | Measure-Object -Property CumulativeProbability -Maximum

Which gives me the highest value, and then use that column as a reference to find the number with
Where-Object {$_.CumulativeProbability -eq $TheNumberIGetAbove}

While this kinda works, it feels like I'm doing several laps around a problem that should be easier and more straightforward to solve. Are there any better ways of generating random numbers that fit a distribution you specify yourself instead of using an even distribution such as Get-Random?


texts: C# 5 Async Await .Task.Factory.StartNew cancellation

texts:
I have the async code that implements cancellation token. It's working but Im not pretty sure if this is the right way to do it so I just want feedback about it.

Here is the actual code:

/// <summary>
///
/// </summary>
private async void SaveData() {

    if (GetActiveServiceRequest() != null)
    {
        var tokenSource = new System.Threading.CancellationTokenSource();

        this.ShowWizardPleaseWait("Saving data...");

        var someTask = System.Threading.Tasks.Task<bool>.Factory.StartNew(() =>
        {

            bool returnVal = false;

            // Set sleep of 7 seconds to test the 5 seconds timeout.
            System.Threading.Thread.Sleep(7000);

            if (!tokenSource.IsCancellationRequested)
            {
                // if not cancelled then save data

                App.Data.EmployeeWCF ws = new App.Data.EmployeeWCF ();
                returnVal = ws.UpdateData(_employee.Data);
                ws.Dispose();
            }

            return returnVal;

        }, tokenSource.Token);

        if (await System.Threading.Tasks.Task.WhenAny(someTask, System.Threading.Tasks.Task.Delay(5000)) == someTask)
        {
            // Completed
            this.HideWizardPleaseWait();
            if (someTask.Result)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                this.DialogResult = System.Windows.Forms.DialogResult.Abort;
            }
            btnOK.Enabled = true;
            this.Close();
        }
        else
        {
            tokenSource.Cancel();

            // Timeout logic
            this.HideWizardPleaseWait();
            MessageBox.Show("Timeout. Please try again.")
        }

    }
}

Does async / await / cancellation code is well implemented?