texts: Approximate (250 over 100) permutation best fitting certain criteria

texts:
Given a list of 250 words of 4 letters each, what is the fastest way, in Python, to find a subsample of 100 words (drawn without replacement) so that the distribution of letters across the whole sample is most even?

List of words: http://pastebin.com/2kpiNAcC

Note there are only 18 different characters, and some occur much more frequently than others.

(Currently, "even letter distribution" is operationalized as the smallest difference between max and min letter counts and the smallest standard deviation of letter counts, although I'm open to suggestions.)

I've tried brute forcing it by drawing random samples, and after various refinements have arrived at the code below. But 1. I assume my brute forcing isn't optimal and 2. there probably is a smarter way, but I can't think of any smart approach.

I am interested in finding a better subsample, so either making the brute-forcing more efficient, or using a smarter algorithm could help.
Not sure if this is better suited for Code Review (optimizing the brute forcing) or a site more suited for discussing a smarter algorithm.

import random

import numpy as np
import pandas as pd

# currently unused, as iterating over all combinations seems impossible
from itertools import combinations

from collections import Counter
from joblib import Parallel, delayed

#this just reads the file so "words" is a list of strings
#corresponding to the 250 words
fname = "file.txt"
df = pd.DataFrame.from_csv(fname, sep="\t")
words = list(df.index)

# define function to randomly sample words and rate them
def sampl(r):
    s, mm = 1000000, 1000000  # arbitrary constants
    for w in range(r):
        w = random.sample(words, 100)
        counts = [v for k, v in Counter("".join(w)).items()]
        s_new = np.std(counts)
        mm_new = np.max(counts) - np.min(counts)
        # compare current subsample to benchmark within this run
        if s_new < s:
            w_candidate_1 = w
            s = s_new
        if mm_new < mm:
            w_candidate_2 = w
            mm = mm_new
        if s_new <= s and mm_new <= mm:
            w_candidate_3 = w
    return (w_candidate_1, w_candidate_2, w_candidate_3)

# run the function a bunch (evaluating the results is fairly easy)
runs = 100
n_per_run = 999999
outs = Parallel(n_jobs=-10)(delayed(sampl)(r)
                for r in [n_per_run] * runs)

# to find the best candidate within the output of the parallel job ...
s, mm = 1000000, 1000000
for w in outs[0]:
    counts = [v for k, v in Counter("".join(w)).items()]
    s_new = np.std(counts)
    mm_new = np.max(counts) - np.min(counts)
    if s_new < s:
        w_candidate_1 = w
        s = s_new
    if mm_new < mm:
        w_candidate_2 = w
        mm = mm_new
    if s_new <= s and mm_new <= mm:
        w_candidate_3 = w

for ws in [w_candidate_1, w_candidate_2, w_candidate_3]:
    print([v for k, v in Counter("".join(ws)).items()])

Note: we have 10+ cores and 200+ GB RAM available to burn on this, so embarrassingly parallel approaches are useful.


texts: Same method to export different txt files C#

texts:
I have a basic method to export files, however I have several arrays to export and I need the files to have these names, I'm trying to make it by the enum list, however when I do it, the file isn't created and I'm wondering is there a way to combine the directory+name of array+.txt? Here's method that doesn't export nothing at all. Thank you for looking at the code.

enum exportByName { Client, Appointment, Address,Location,Historic }

        static string askPath()
        {
            var dir = "";

            do
            {
                Console.Clear();
                Console.Write("Insert path to export the txt file: ");
                dir = Console.ReadLine();
            } while (String.IsNullOrEmpty(dir));

            var userPath = Path.Combine(dir,Enum.GetName(typeof(exportByName),0),".txt");
            return userPath;
        }


texts: Make Project Euler 27 solution idiomatic Ruby

texts:
I learned to program in Java and C# and in my free time I am using Ruby because it is fun. Unfortunately I have the feeling that I write Ruby code like I am making Java or C# code. I have learned to use regex instead of strings for comparison, using each instead of for-loops, keeping method names lowercase, and how to use code blocks (which are quite similar to lambda expressions in C#).

I would love to improve the Rubiness of my code and I hope you would be willing to give me one or more pointers on a piece of code I made. It answers Project Euler problem 27.

class Integer
  def prime?
    return false if self < 1
    2.upto(Math.sqrt(self)) do |i|
      return false if self % i == 0
    end
    true
  end
end

def get_amount_of_primes_from_quadratic_formula(a,b)
  primes = []
  still_all_primes = true
  n = 0
  while still_all_primes
    result = n**2 + a*n + b
    if result.prime? then
      primes << result
    else
      still_all_primes = false
    end
    n += 1
  end
  primes.size
end

def get_product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values()
  max_product = 0
  max_primes = 0
  -999.upto(1000) do |a|
    -999.upto(1000) do |b|
      primes = get_amount_of_primes_from_quadratic_formula(a,b)
      if primes > max_primes then
        max_primes = primes
        max_product = a*b
      end
    end
  end
  max_product
end

start = Time.now
answer = get_product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values()

puts "The answer is #{answer} and it took #{Time.now-start} seconds."

I think I can improve on the if-then statement and write it more concise, and also the two "upto-loops" where I first declare the variables max_primes and max_product can be written in a more Ruby-way I am sure.

I would be very grateful if you could let me know how to write more like Ruby!

Links that ask similar questions which I am reading in the meantime:

Advice on making ruby code more ruby-like
Ruby method return values - how to be more Ruby-like?
How to make my script nicer / more Ruby?


texts:
After about half an hour of fooling around with Processing.js/JavaScript, I got this fairly decent particle system set up:

// main particle constructor class
var Particle = function(position) {
    this.velocity = new PVector(random(-0.1, 0.1), random(-0.1, 0.1));
    this.acceleration = new PVector(random(-0.01, 0.01), random(-0.01, 0.01));
    this.lifeTime = 300;
    this.position = position.get();
};

// update the particle
Particle.prototype.update = function() {
    this.velocity.add(this.acceleration);
    this.position.add(this.velocity);
    this.lifeTime--;
};

// render the particle
Particle.prototype.render = function() {
    strokeWeight(2);
    stroke(161, 153, 153, this.lifeTime);
    fill(140, 135, 140, this.lifeTime);
    ellipse(this.position.x, this.position.y, 15, 15);
};

// check the bounds of a particle
Particle.prototype.checkBounds = function() {
    if(this.position.x >= 385) {
        this.acceleration = new PVector(random(-0.02, -0.01), random(-0.01, 0.01));
    }
    if(this.position.x <= 15) {
        this.acceleration = new PVector(random(0.01, 0.02), random(-0.01, 0.01));
    }
    if(this.position.y >= 385) {
        this.acceleration = new PVector(random(-0.01, 0.01), random(-0.02, -0.01));
    }
    if(this.position.y <= 15) {
        this.acceleration = new PVector(random(-0.01, 0.01), random(0.01, 0.02));
    }
};

// check if the particle is dead
Particle.prototype.particleDead = function() {
    if(this.lifeTime > 0) {
        return false;
    } else {
        return true;
    }
};

// array containing particles
var particles = [];

// main draw loop
var draw = function() {

    // draw the background and push a new particle
    background(11, 100, 209);
    particles.push(new Particle(new PVector(mouseX, mouseY)));

    // iterate through particles and run their methods
    for(var p = particles.length-1; p >= 0; p--) {
        var particle = particles[p];
        particle.checkBounds();
        particle.update();
        particle.render();
        if(particle.particleDead()) {
            particles.splice(p, 1);
        }
    }
};

Now, I think that this could definitely be improved, as the Particle.prototype.checkBounds method seems to not work all the time. Anyways, what can I improve here?


texts:
import math

def generate_primes(limit):
    """Generates and prints a list of primes up to a given limit"""
    prime_list = [2, 3]
    num = 5
    increment_2 = True  # When True increment by 2. When False increment by 4

    while num <= limit:
        is_prime = True
        sqr_lim = math.sqrt(num)
        for x in prime_list:
            # Loop through list of prime numbers and check divisibility
            if x > sqr_lim:
                break
            if num % x == 0:
                is_prime = False
                break

        if is_prime:
            # Add primes to list to only check prime numbers
            prime_list.append(num)

        # Alternate step size between 2 and 4 to skip multiples of 2 and 3
        if increment_2:
            num += 2
            increment_2 = False
        else:
            num += 4
            increment_2 = True

    print(prime_list)
    return prime_list

def main():
    generate_primes(200)

if __name__ == "__main__":
    main()

I'm writing a program to generate a list of prime numbers to a given limit through the use of trial division. I was wondering if there is a way to further optimize this code. Currently it: skips multiples of 2 and 3; stores primes in a list and the list is used to check for primality; and checks divisibility up until the square root of the number it's analyzing.

I would also appreciate it if someone could critique me on my coding style such as comments, white space, and organization because I know its pretty rough around the edges. Thanks for the help.


texts: Find the cheapest shipping option based on item weight

texts:
I've been taking the Computer Science course on Codecademy. The course includes this project where we have to create a python script to find the cheapest shipping method based on the weight of an item and I'm just wondering if this is the best way to code the solution?

def ground_shipping_cost(weight):
    flat_cost = 20
    premium_cost = 125
    if weight <= 2:
        flat_cost += weight * 1.50
    elif weight > 2 and weight <= 6:
        flat_cost += weight * 3.00
    elif weight > 6 and weight <= 10:
        flat_cost += weight * 4.00
    elif weight > 10:
        flat_cost += weight * 4.75
    return flat_cost, premium_cost

def drone_shipping_cost(weight):
    cost = 0
    if weight <= 2:
        cost = weight * 4.50
    elif weight > 2 and weight <= 6:
        cost = weight * 9.00
    elif weight > 6 and weight <= 10:
        cost = weight * 12.00
    elif weight > 10:
        cost = weight * 14.25
    return cost

def cheapest_shipping(weight):
    ground_cost, premium_cost = ground_shipping_cost(weight)
    drone_cost = drone_shipping_cost(weight)
    if drone_cost < ground_cost and drone_cost < premium_cost:
        return "You should use drone shipping as it will only cost " + str(drone_cost)
    if ground_cost < drone_cost and ground_cost < premium_cost:
        return "You should use standard ground shipping as it will only cost " + str(ground_cost)
    if premium_cost < ground_cost and premium_cost < drone_cost:
        return "You should use premium shipping as it will only cost " + str(premium_cost)

print(cheapest_shipping(4.8)) # You should use standard ground shipping as it will only cost 34.4
print(cheapest_shipping(41.5)) # You should use premium shipping as it will only cost 125
print(cheapest_shipping(1.5)) # You should use drone shipping as it will only cost 6.75
print(cheapest_shipping(4.0)) # You should use standard ground shipping as it will only cost 32.0

The issue I see is maybe there's too many if, elif statements and maybe there is a way to simplify the code


texts: Django models: different methods on each instance?

texts:
Imagine I have code like this in (it's about the concept; this is example code):

# models.py
from django.db import models

class Monster(models.Model):
    x = models.FloatField()
    y = models.FloatField()
    def use_unique_ability(self, target):
        ''' different monsters types will implement this differently '''
    def check_attack(self, player): # should I attack this player?
        ''' different monsters types will implement this differently '''
    class Meta:
        abstract = True

class SlimyMonster(Monster):
    def __init__(self):
        self.attack = 3
        self.hit_points = 10
    def use_unique_ability(self, target):
        target.hit_points -= 2 * target.attack
    def check_attack(self, player): # should I attack this player?
        return player.hit_points < self.hit_points

class CaerbannogRabbit(Monster):
    ''' well, you get the idea '''

# many more monsters

Each monster has the same attributes and method names, but different values and implementation. Monster would probably be an interface in Java. Each monster type will override only some of the many methods.

This technically works, but it has some significant downsides:

Each monster is a new database table with the same columns
Because of that, I need a lot of queries to check for all monsters
I need GenericForeignKey to reference individual monsters (instances of any of the model classes)

The other extreme isn't exactly pretty either. This is based on dynamically mixin a base class to an instance (+this) and how to import a module given the full path?:

# models.py
from django.db import models
from os.path import join
from inspect import isclass
from imp import load_source
from settings import PATH_TO_MONSTER_FILES

class InconsistentMonsterError(Exception): pass

class MonsterClass(models.Model):
    name = models.CharField(max_length = 32)
    attack = models.PositiveIntegerField(default = 1)
    defense = models.PositiveIntegerField(default = 10)
    method_file = models.CharField(max_length = 128) # it's a source file, not media file, so I'm using CharField
    def __init__(self, *args, **kwargs):
        super(MonsterClass, self).__init__(*args, **kwargs)
        try:
            modul = load_source(self.method_file, join(PATH_TO_MONSTER_FILES, self.method_file))
        except IOError:
            raise InconsistentMonsterError('no file named %s' % join(PATH_TO_MONSTER_FILES, self.method_file))
        classes = [cls for cls in [getattr(modul, x) for x in dir(modul)] if isclass(cls)]
        if not len(classes):
            raise InconsistentMonsterError('file %s doesn\'t contain classes' % join(PATH_TO_MONSTER_FILES, self.method_file))
        bases = self.__class__.__bases__ + (classes[-1], )
        self.__class__ = type('NewClassName', bases, {
            '__module__': MonsterClass.__module__,
        })

class MonsterInstance(models.Model):
    cls = models.ForeignKey(MonsterClass)
    x = models.FloatField()
    y = models.FloatField()

and for each monster a file like this:

# slimy_monster.py
class SlimyMonster(): # not a Model
    def use_unique_ability(self, target):
        ''' different monsters types will implement this differently '''
    def check_attack(self, player): # should I attack this player?
        ''' different monsters types will implement this differently '''

The code seems... inellegant. It's complex, and it's like using eval (execute code based on an 'external' string)
Every monster must be changed in two places: the database and a file (although I suppose I could define database values in the file)

Given these two options, should I use one of them, or something in between? I tend towards the second option, but I'm not quite satisfied.


texts:
I'm new to C++ programming. I'm experienced in Java and its OOP paradigm.
This code works well. I just need to make sure whether it's correct in terms of C++ programming standard.

main.cpp

#include <iostream>
#include "ListNode.h"
#include "LinkedList.h"

using namespace std;

int main(void) {

    LinkedList l;
    ListNode a(10);
    ListNode b(5);
    ListNode c(3);
    l.addFirst(a);
    l.addFirst(b);
    l.addLast(c);

    bool empty = l.isEmpty();

    cout << l.listSize() << endl;

    cout << empty << endl;

    system("PAUSE");
    return 0;
}

LinkedList.h

#pragma once
#include "ListNode.h"

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();
    void addFirst(ListNode &node);
    void addLast(ListNode &node);
    bool isEmpty();
    int listSize();

private:
    ListNode *head;
    ListNode *tail;
    int size;
};

LinkedList.cpp

#include "LinkedList.h"

LinkedList::LinkedList()
{
    head = new ListNode();
    tail = new ListNode();
}

LinkedList::~LinkedList()
{
}

void LinkedList::addFirst(ListNode & node)
{
    if (isEmpty())
    {
        *head = node;
        *tail = node;
        size = 1;
    }
    else {
        node.setNext(*head);
        head->setPrev(node);
        *head = node;
        size++;
    }
}

void LinkedList::addLast(ListNode & node)
{
    if (isEmpty())
    {
        *tail = node;
        *head = node;
        size = 1;
    }
    else
    {
        tail->setNext(node);
        node.setPrev(*tail);
        *tail = node;
        size++;
    }
}

bool LinkedList::isEmpty()
{
    return size == 0;
}

int LinkedList::listSize()
{
    return size;
}

ListNode.h

#pragma once
class ListNode
{
public:
    ListNode();
    ListNode(int val);
    ~ListNode();

    inline void setPrev(ListNode &node) { *prev = node; }
    inline ListNode *getPrev() { return prev; }
    inline void setNext(ListNode &node) { *next = node; }
    inline ListNode *getNext() { return next; }
    inline void setValue(int val) { value = val; }
    inline int getValue() { return value; }

private:
    ListNode *prev;
    ListNode *next;
    int value;
};

ListNode.cpp

#include "ListNode.h"

ListNode::ListNode()
{
}

ListNode::ListNode(int val)
{
    prev = new ListNode;
    next = new ListNode;
    value = val;
}

ListNode::~ListNode()
{
}

Am I do it correctly as usually done by C++ programmer? Or there is something I need to fix.
I heavily put my focus on pointer/reference usage.


texts: Format multiple dates to look good in text, using functional approach

texts:
I had a piece of code that solved really simple problem  - it formated two dates to look better on a webpage. It looked like this:
function formatDateRange(
  days: { firstDay: string, lastDay: string }
): string {

  let first, last;
  first = dayjs(days.firstDay); //dayjs parses string that formatted like this "YYYY-MM-DD"
  last = dayjs(days.lastDay);   //and returns a wrapper for Date object
  if (first.isSame(last, "date")) {
    first = first.format("DD MMMM, YYYY")
    last = ""

  } else if (first.isSame(last, "month")) {
    first = first.format("DD") + " ... "
    last = last.format("DD, MMMM YYYY")

  } else if (first.isSame(last, "year")) {
    first = first.format("DD MMM") + " ... "
    last = last.format("DD MMM, YYYY")

  } else {
    first = first.format("DD MMM, YYYY") + " ... "
    last = last.format("DD MMM, YYYY")
  }
  return first + last
}

Than I decided to refactor it, and I got this:
//adapter that allows to use objects and arrays in function-composition
//EDIT: was called "callable"
function pluckFrom<T extends {}>(obj: T) {
  return (key: keyof T) => obj[key]
}

// a function for function-composition
// (same as compose from redux but order is reversed)
function pipe(...funcs: Function[]) {
  return funcs.reduce((f1, f2) => (...args: any) => f2(f1(...args)))
}

//provides an interface to apply array of functions to array of data
function apply<A>(maps: Array<(a: A) => any>) {
  return {to: (arr: A[]) => arr.map((item, index) => maps[index](item))}
}

//takes array of dates, wrapped in Dayjs object and returns
//true if they're all the same in terms of unit of time
function isSame([day1, ...rest]: Dayjs[]) {
  return (unit: UnitType) => rest.every(day => day.isSame(day1, unit))
}

interface DateRange {
  firstDay: string;
  lastDay: string;
}
//EDIT: removed redundant "same_" prefix
const case_to_format_map = {
  "date": ["DD MMMM, YYYY", " "],
  "month": ["DD ...", "DD, MMMM YYYY"],
  "year": ["DD MMM ... ", "DD MMM, YYYY"],
  " ": ["DD MMM, YYYY ... ", "DD MMM, YYYY"]
}

type Case = keyof typeof case_to_format_map

//EDIT: slightly refactored
function formatDateRange({firstDay, lastDay}: DateRange): string {

  const
    getCase = (days: Dayjs[]) => (
      (["date", "month", "year", " "] as UnitType[])
        .filter(isSame(days))[0]
    ) as Case
    ,
    makeFormatter = (f: string) => (d: Dayjs) => d.format(f)
    ,
    getFormatters = pipe(
      getCase,
      pluckFrom(case_to_format_map),
      formats => formats.map(makeFormatter)
    )
    ,
    days = [firstDay, lastDay].map(dayjs)

  return apply(getFormatters(days)).to(days).join(" ")
}

It's more code, but I like it because now I have 4 additional utility functions, it's more readable for me. Other than that, I'm not sure if I made better or worse.
And so I have these questions:
Is it readable to you?
Is it aligned with functional style and best practices?
I'm not sure if I will ever need to extend this code but how can I make it more extendable?


texts:
I am trying to implement the Jagged Diagonal Storage code in Cuda for Sparse Matrix - Vector multiplication. The code I wrote is as follows but I'm not sure about it:

__global__ jds_kernel(JDSMatrix jds, float * invector, float * outvector){
   int i = blockIdx.x * blockDime.x + threadIdx.x;
   int row = jds.rows[i];

   if (row < jds.numRows){
     float sum = 0.0f;
     for (nnz=0; nnz < jds.nnzperrow[row]; ++nnz){
        int idx = i + jds.iterPtr[nnz];
        int col = jds.colIdxs[idx];
        int val = jds.values[idx];
        sum += invector[col] * val;
     }

     output[row] = sum;
  }
}

Assuming that:

jds is the jds matrix
invector is the input vector
outvector is the output vector
jds.numRows is the number of rows in the jds matrix
jds.nnzperrow is the number of non-zero entries in per row
jds.rows are the rows
jds.iterPtr is the iteration pointer
jds.colIdxs is the column indexes
jds.values are the values


texts: Loop through array of files and rsync to Dropbox

texts:
The goal is pretty straightforward. There’s a list of dotfiles from my home directory. It loops through them and rsyncs all file to a Dropbox folder for backup purposes. A cron job runs this nightly. Code has worked well so far.

#!/usr/bin/python

import os
from os.path import expanduser
import sys
import subprocess

dotfiles = [
  '.ackrc',
  '.tmux.conf',
  '.vimrc',
  '.zshrc',
  '.gitconfig',
  '.ssh/config',
  '.zsh/MyAntigen.hs',
  '.vim/colors/dracula.vim'
]

home = expanduser("~")
src = home + '/'
dest = home + '/Dropbox/Dotfiles'
rsync = 'rsync --times'

if sys.stdout.isatty():
    rsync = rsync + ' --progress'

for item in dotfiles:
    src_file = os.path.join(src + item)
    cmd = rsync + ' ' + src_file + ' ' + dest
    process = subprocess.Popen(cmd, shell=True)
    process.wait()

This is my very first Python script (first time using rsync too) and I just started very recently. I’ve put this together based on trial and error and a lot of Stack Overflow. So I’m here for some genuine feedback.


texts: Number to word converter (1 to 99 inclusive)

texts:
Program

It takes a numerical input in range [1, 99] and outputs its word equivalent.

Concerns

Procedural approach
General code style

Code

#include <iostream>

void print1to20(int num)
    {
           switch(num)
           {
           case 1: std::cout << "one"; break;
           case 2: std::cout << "two"; break;
           case 3: std::cout << "three"; break;
           case 4: std::cout << "four"; break;
           case 5: std::cout << "five"; break;
           case 6: std::cout << "six"; break;
           case 7: std::cout << "seven"; break;
           case 8: std::cout << "eight"; break;
           case 9: std::cout << "nine"; break;
           case 10: std::cout << "ten"; break;
           case 11: std::cout << "eleven"; break;
           case 12: std::cout << "twelve"; break;
           case 13: std::cout << "thirteen"; break;
           case 14: std::cout << "fourteen"; break;
           case 15: std::cout << "fifteen"; break;
           case 16: std::cout << "sixteen"; break;
           case 17: std::cout << "seventeen"; break;
           case 18: std::cout << "eighteen"; break;
           case 19: std::cout << "nineteen"; break;
           case 20: std::cout << "twenty"; break;
           default: std::cout << "1 to 20 switch error";
           }
    }

void printTens(int num)
    {
           switch(num)
           {
           case 20: std::cout << "twenty"; break;
           case 30: std::cout << "thirty"; break;
           case 40: std::cout << "fourty"; break;
           case 50: std::cout << "fifty"; break;
           case 60: std::cout << "sixty"; break;
           case 70: std::cout << "seventy"; break;
           case 80: std::cout << "eighty"; break;
           case 90: std::cout << "ninety"; break;
           default: std::cout << "tens switch error";
           }
    }

int main()
{
    int num;
    do
    {
    std::cout << "Insert a number 1-99: ";
    std::cin >> num;
    } while(num < 1 || num > 99);

    int num_a, num_b; // num = (a)(b);
    num_a = num - num%10;
    num_b = num%10;

    std::cout << "Your number is ";

    if(num <= 20)
        print1to20(num);
    else
    {
        printTens(num_a);
        std::cout << ' ';
        print1to20(num_b);
    }

    return 0;
}


texts:
I have spent a decent amount of (waaay too much) time trying to write the below function and get my head around recursion. The aim was to return all permutations of an int vector (assuming no duplications of input). I would like to know people's thoughts on my code. One downfall that I can identify is that it is pretty demanding of space since I am copying choice and out vectors many times.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void uni_permutes(std::vector<int> in, std::vector<int> out, std::vector<int> choice)
{
    int size = choice.size();
    //complete when all ints in choice have already been used
    if(size == 0) {
        for(int i : out) {
        std::cout << i << std::endl;
    }
        std::cout << '\n' << std::endl;
        return;

    }
    std::vector<int> newo = out;
    std::vector<int> newc = choice;
    for (int i : choice) {
        newo.push_back(i);
        //remove i from choice      newc.erase(std::remove(newc.begin(), newc.end(), i), newc.end());
        uni_permutes(in,newo, newc);
        newc = choice;
        newo = out;
}
    return;
}

int main()
{
    std::vector<int> v1 = {0, 1,2,3};
    std::vector<int > out;
    uni_permutes(v1,out,v1);

    return 0;
}


texts: Pausing script while waiting for Docker container and printing updates

texts:
I'm looking to improve it in brevity, readability, and simplicity. Basically, I'm just looking for a more elegant solution. What improvements can I make?

i=0
while true; do
    OUTPUT="$(docker inspect --format='{{json .State.Health.Status}}' su-apache)"
    if [ $OUTPUT = '"healthy"' ]; then
      echo
      break
    fi
    echo -en "\r\033[KWaiting $i seconds for su-apache to finish starting... Current health: $OUTPUT"
    let "i++"
    sleep 1
done

echo 'Environment started successfully.'


texts: Handling signals in Python inside a function

texts:
I have code that needs to exit gracefully. To simplify things, I am presenting an example based on the answer given here.

Since I need to handle a few signals, I thought of putting this logic in a function:

def set_signals():
   original_sigint = signal.getsignal(signal.SIGINT)
   signal.signal(signal.SIGINT, exit_gracefully)
   signal.signal(signal.SIGTERM, exit_gracefully)
   signal.signal(signal.SIGINT, exit_gracefully)
   signal.signal(signal.SIGALRM, exit_gracefully)
   signal.signal(signal.SIGHUP, signal.SIG_IGN)

Thus, the main block of the python code should be:

if __name__ == '__main__':
    # store the original SIGINT handler
    set_signals()
    run_program()

This will fail however, since the exit_gracefully does not know the variable original_init.

Therefore, my solution was to create original_sigint as a global variable.

import signal
import time
import sys

original_sigint = None

def run_program():
    while True:
        time.sleep(1)
        print("a")

def exit_gracefully(signum, frame):
    # restore the original signal handler as otherwise evil things will happen
    # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant
    global original_sigint
    signal.signal(signal.SIGINT, original_sigint)

    try:
        if raw_input("\nReally quit? (y/n)> ").lower().startswith('y'):
            sys.exit(1)

    except KeyboardInterrupt:
        print("Ok ok, quitting")
        sys.exit(1)

    # restore the exit gracefully handler here
    signal.signal(signal.SIGINT, exit_gracefully)

def set_signals():
    global original_sigint
    original_sigint = signal.getsignal(signal.SIGINT)
    signal.signal(signal.SIGINT, exit_gracefully)
    signal.signal(signal.SIGTERM, exit_gracefully)
    signal.signal(signal.SIGINT, exit_gracefully)
    signal.signal(signal.SIGALRM, exit_gracefully)
    signal.signal(signal.SIGHUP, signal.SIG_IGN)

if __name__ == '__main__':
    # store the original SIGINT handler
    set_signals()
    run_program()

This approach works, but I am not happy with the use of another global variable (the code I working on is quite and is already littered with those). So the question is, how would you do it differently?


texts: Controller for handling user registration

texts:
I spent a lot of time doing Go Horse Extreme programming, but now I want to be a better person.

How can I make this method smaller, better, more OOP?

/**
 * @return \Illuminate\Http\RedirectResponse
 */
public function store()
{
    if (!User::is_valid(Input::all()))
    {
        Flash::error(User::$errors->first());

        return Redirect::back()->withInput();
    }

    $existing_user = User::where('email', Input::get('email'))->first();

    if (is_null($existing_user)) // The user does not exists.
    {
        // Prepare user data
        $user_input = Input::only(
            'firstName',
            'lastName',
            'email',
            'password');

        $confirmation_token = str_random(60);
        $user_data = array_merge($user_input, ['confirmation_token' => $confirmation_token]);

        // Store user
        $new_user = User::create($user_data);

        // Prepare email
        $data['name'] = Input::get('firstName') . ' ' . Input::get('lastName');
        $data['confirmation_token'] = $confirmation_token;
        $mail_subject = 'Confirmação de e-mail';

        // Send email
        Mail::send('emails.auth.email_confirmation', $data, function ($message) use ($mail_subject)
        {
            $message->to(Input::get('email'))->subject($mail_subject);
        });

        // Log the new user in
        Auth::login($new_user);

        $flash_message = sprintf(
            'Enviamos um email para %s. Confirme sua identidade',
            Input::get('email')
        );

        Flash::warning($flash_message);

        return Redirect::route('admin.dashboard');
    } else
    {
        if ($existing_user->is_active())
        {
            //Try to validate
            $stored = $existing_user->password;
            $typed = Input::get('password');
            $match = Hash::check($typed, $stored);

            if (!$match)
            {
                Flash::warning(
                    'Você já possui uma conta.
                    Faça login para continuar.'
                );

                return Redirect::route('login');
            } else
            {
                Auth::login($existing_user);
                Flash::message(
                    'Você já possui uma conta.
                    Bem vindo de volta!'
                );

                return Redirect::route('admin.dashboard');
            }
        } else
        {
            Auth::login($existing_user);

            $flash_message = sprintf(
                'Enviamos um email para %s. Confirme sua identidade [Reenviar]',
                $existing_user->email
            );

            Flash::warning($flash_message);

            return Redirect::route('admin.dashboard');
        }
    }
}

It just handles user registration. Everything seems to be working when I run my Behat tests, but I feel (deep in my soul) that things could be a lot better.


texts:
I am implementing a BVH (Bounding volume hierarchy) in Cython and thought of using a doubly linked list to hold reference of the volumes that still need to be split and push new volumes at one end while popping others on the other side in a recursive manner.

But I am not sure if I got the code right, it gets confusing to me really fast.

Here AABB stands for Axis Aligned Bounding Box, the kind of bounding volume I want to use in my BVH.

    cdef struct AABB:
        double min_x, max_x
        double min_y, max_y
        double min_z, max_z
        AABB* next
        AABB* children
        int id

    cdef struct AABBListItem:
        AABB* box
        AABBListItem* next
        AABBListItem* prev

    cdef AABBList* aabb_list_create(AABB* start):
        cdef AABBList* lst = <AABBList *> malloc(sizeof(AABBList))
        cdef AABBListItem* item = <AABBListItem *> malloc(sizeof(AABBListItem))
        item.next = NULL
        item.prev = NULL
        item.box = start
        lst.first = item
        lst.last = item
        lst.length = 1
        return lst

    cdef void aabb_list_free(AABBList* lst):
        cdef AABBListItem* item = lst.first
        cdef AABBListItem* next
        while not item == NULL:
            next = item.next
            free(item)
            item = next
        free(lst)

    cdef void aabb_list_push_last(AABBList* lst, AABB* box):
        cdef AABBListItem* item = <AABBListItem *> malloc(sizeof(AABBListItem))
        item.box = box
        item.prev = lst.last
        item.next = NULL
        lst.last.next = item
        lst.last = item
        lst.length += 1

    cdef void aabb_list_push_first(AABBList* lst, AABB* box):
        cdef AABBListItem* item = <AABBListItem *> malloc(sizeof(AABBListItem))
        item.box = box
        item.next = lst.first
        item.prev = NULL
        lst.first.prev = item
        lst.first = item
        lst.length += 1

    cdef AABB* aabb_list_pop_first(AABBList* lst):
        cdef AABBListItem* item = lst.first
        cdef AABB* box = item.box
        lst.first = item.next
        lst.first.prev = NULL
        free(item)
        lst.length -= 1
        return box

    cdef AABB* aabb_list_pop_last(AABBList* lst):
        cdef AABBListItem* item = lst.last
        cdef AABB* box = item.box
        lst.last = item.prev
        lst.last.next = NULL
        free(item)
        lst.length -= 1
        return box

```


texts: Clone Vector in rust except at one index

texts:
Let's consider you want to clone all items of a vector orig except the item of index i should be taken from alternative value alt.

Lets say the items are of the type

struct Bla{
  // Some fields
}

Using for loop

On simple solution would be:

fn clone(orig: &Vec<Bla>, i: usize, alt: Bla) -> Vec<Bla> {
  let cloned = Vec::new();
  for (j, item) in orig.iter().enumerate() {
    let new_item = if i != j {item.clone()} else {alt};
    cloned.push(new_item);
  }

  cloned
}

  Note: Does not compile, because the compiler does not know that i==j is only valid once.

Using functional style

The functional alternative would be the follow:

fn clone(orig: &Vec<Bla>, i: usize, alt: Bla) -> Vec<Bla> {
  orig.iter().enumerate()
    .map(|(j, item)| if i != j {item.clone()} else {alt})
    .collect::<Vec<Bla>>()
}

The last one looks nice, but does not compile :( because the rust compiler does not know that alt gets moved (or consumed) only once (i==j).

Using mem replace

In order to fix the version above one can use a default value for the index which should be replaced.

fn clone(orig: &Vec<Bla>, i: usize, alt: Bla) -> Vec<Bla> {
  let mut result = orig.iter().enumerate()
    .map(|(j, item)| if i != j {item.clone()} else {Bla::default()})
    .collect::<Vec<Bla>>();

  mem::replace(&mut result[i], alt);
  result
}

What is the most concise and fastest implementation to do so?


texts:
Let a,b,c be a boolean value. I need to print all values of expression a && b && c. I'm writing the class

public class BooleanTriple{
    private boolean a,b,c;
    public BooleanTriple(boolean a, boolean b, boolean c){ this.a =a; this.b=b; this.c=c;}

    /**
    *Increments the value of triple with lexicographical ordering
    */
    public void incr(){
        if (!a) a=true;
        else if(!b){
            a= false;
            b= true;
        else if (!c){
            a= false;
            b= false;
            c=true;
        }
    }
    public boolean logProduct(){ return a && b && c;}
}

And Main class:

public class Main{
    BooleanTriple bTriple = new BooleanTriple(false,false,false);
    public static void main(String[] args){
        for (int i=0; i<8; i++){
            System.out.println(bTriple.logProduct());
            bTriple.incr();
        }
    }
}

But i think, that it's bad implementation. Can you correct me?


texts: Return the Euler Cycle for a graph with es6

texts:
My algorithm for finding an Euler tour of a digraph, G⃗,  if such a tour exists, starting from some vertex, v.

'use strict';

var graph = {
    1: [{val: 2}],
    2: [{val: 3}],
    3: [{val: 5}, {val: 4}],
    4: [{val: 1}],
    5: [{val: 6}],
    6: [{val: 3}]
};

var EulerCyle = (function(G, source) {
    var Cycle = function(v) {
        var u;
        for (let i=0; i<G[v].length; i++) {
            u = G[v][i];
            if (!u.visited) {
                u.visited = true;
                return [u.val].concat(Cycle(u.val));
            }
        }
        return [];
    }

    var P = [source].concat(Cycle(source));
    var i = 0;
    for (let u of P) {
        i++;
        for (let v of G[u]) {
            if (!v.visited) {
                P = P.slice(0, i) + Cycle(u) + P.slice(i);
            }
        }
    }
    return P;

})(graph, 1);

console.log(EulerCycle);


texts:
Sometimes I need to repeat an execution of rejected promises several times, for example, to fetch some data over internet.
There is a wrapper, which accepts Promise and tryCount:

function tryPromise(f, tryCount) {
  return f().then(null, function(v) {
    tryCount--;
    if (tryCount > 0) {
      return $q.reject(v);
    }
    return tryPromise(f, tryCount);
  });
}

Is there some hidden troubles?


texts:
This code feels long and clunky to me. How can I make it shorter, if possible?

I am writing for a libGDX game, and I need a skill algorithm.
I want it so once the player picks up something (which I already have checked for) I set a, b or c to a certain SkillType, the enum down below. Then, I want to get the value of the specific SkillType, by using the enum's methods to get cooldown and cost.

public SkillType[] skills;
public SkillType a, b, c;
public int acost, bcost, ccost;
public int acooldown, bcooldown, ccooldown;

skills = new SkillType[3];
skills[0] = a; skills[1] = b; skills[2] = c;
acost = a.getCost(); bcost = b.getCost(); ccost = c.getCost();
acooldown = a.getCooldown(); bcooldown = b.getCooldown(); ccooldown = c.getCooldown();

public SkillType getSkill(int index) { return skills[index]; }
public void setSkill(int index, SkillType skill) { skills[index] = skill; }

This code declares the enum used above.  It has all the skills that I want to use.  It declares, inside the SkillType, its cost and cooldown.  I do not want to change these values, and that's why I don't have setters.

public static enum SkillType {
        ROAR(1,3),
        DUST_CLOAK(2,10),
        THORN_CLOAK(2,10),
        SPARK(2,5),
        FLUTTER(0,0),
        EMBER(2,2),
        GLOW(0,0),
        SCRATCH(0,0),
        BITE(0,0);

        int cost;
        int cooldown;
        SkillType(int cost, int cooldown) {
                this.cost = cost;
                this.cooldown = cooldown;
        }
        public int getCooldown() { return cooldown; }
        public int getCost() { return cost; }
}

EDIT:

I have updated the enum class to include more items.

public class SkillData {

public SkillType[] skills;
public static final int MAX_SKILLS = 3;
public static final int SLOT_PRIMARY = 0;
public static final int SLOT_SECONDARY = 1;
public static final int SLOT_SECONDARY_TWO = 2;

public static enum SkillType {
    ROAR(1,3),
    DUST_CLOAK(2,10),
    THORN_CLOAK(2,10),
    SPARK(2,5),
    FLUTTER(0,0),
    EMBER(2,2),
    GLOW(0,0),
    SCRATCH(0,0),
    BITE(0,0);

    int cost;
    int cooldown;
    SkillType(int cost, int cooldown) {
        this.cost = cost;
        this.cooldown = cooldown;
    }
    public int getCooldown() { return cooldown; }
    public int getCost() { return cost; }
}

public SkillData() {
    skills = new SkillType[MAX_SKILLS];
}

public int getCost(int index) { return skills[index].getCost(); }
public int getCooldown(int index) { return skills[index].getCost(); }
public void setSkill(int index, SkillType skill) { skills[index] = skill; }
public SkillType getSkill(int index) { return skills[index]; }
public SkillType[] getSkills() { return skills; }

}


texts: Checking the sum of pairs to match a target value

texts:
I'm new to Python and curious what looks good and what doesn't. The function I have defined looks for pairs in a list of integers and tells the user whether or not any possible pair equals the target number. How can this code be more efficient or fast?

import datetime
from itertools import combinations

def csop(*params):
    t1 = datetime.datetime.now()
    print params[0], params[1]
    for c in combinations(params[0],2):
        print sum(c)
        if sum(c) == params[1]:
            print 'Target number reached'
            t2 = datetime.datetime.now()
            print t2-t1
            exit()
        else:
            pass

To run:

import csop
csop.csop([1,2,3,4],5)

The output should look something like this:

[1, 2, 3, 4] 5
3
4
5
Target number reached
0:00:00.000071


texts: Inserting users using PDO prepared statements

texts:
I made a small script to update fields in a database. I'm using PDO to connect to MySQL. All the business logic of PHP is in the top half of the file, and the form is at the bottom.

Here is the full code. If it's a POST request, it opens the PDO connection and inserts the values from the form.

<?php

/**
 * Use an HTML form to update the users table
 * with new entries.
 *
 */

if ($_POST)
{

    require_once "config.php";
    require_once "common.php";

    try
    {
        $connection = new PDO($dsn, $username, $password, $options);

        $sql = "INSERT INTO users (firstname, lastname, email, age, location)
                VALUES (:firstname, :lastname, :email, :age, :location)";

        $statement = $connection->prepare($sql);

        $statement->execute(array(
            "firstname" => $_POST['firstname'],
            "lastname"  => $_POST['lastname'],
            "email"     => $_POST['email'],
            "age"       => $_POST['age'],
            "location"  => $_POST['location']
        ));

    }

    catch(PDOException $error)
    {
        echo $sql . "
" . $error->getMessage();
    }
}
?>
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/primitive.css">
    <title>Update Users</title>

Add a user

            <form method="post">
                First Name
                <input type="text" name="firstname" id="firstname">
                Last Name
                <input type="text" name="lastname" id="lastname">
                Email Address
                <input type="text" name="email" id="email">
                Age
                <input type="text" name="age" id="age">
                Location
                <input type="text" name="location" id="location">
                <input type="submit" value="Submit">
            </form>

I know I can sanitize HTML input by doing something like:

function escape($html)
{
    return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}

// example use
escape($_POST['firstname']);

I'm wondering how necessary it is when I'm using a prepared statement. I'm still a bit confused about sanitization and filtering, and when it's necessary. I know it's necessary when printing data out to HTML, but not sure how much when receiving input to PDO.

Please forgive any and all ignorance. I'm writing this from scratch and doing my best to teach myself PHP without frameworks.


texts: Shortening Custom Document Property additions

texts:
Context
I have blocks of if statements that check if a certain cell contains a particular string and to add to the counter of the respective custom property. Originally I was using global variables, but those are zeroed out when excel crashes. I learned of custom document properties and their non-volatility and made the switch. However, adding to the counter is a long, barely readable statement.
With global variables I had a statement like:
If cell = "Heavy Duty" Then numHD = numHD + 4

But now statements look like:
If cell = "Heavy Duty" Then ThisWorkbook.CustomDocumentProperties("numHD").Value = ThisWorkbook.CustomDocumentProperties("numHD").Value + 4

It's immensely longer and with 27 other statements doing the same thing for other strings, the code becomes taxing to read.
What I would like
Is there a way that I can shorten the custom document property edits to look more in line with what I had before with global variables? I had tried setting up a global variable as a properties type and setting to the property, then just using the variable in the actual sub:
Public numHD As Properties
Set numHD = ThisWorkbook.CustomDocumentProperties("numHD")

Sub count()
    If cell = "Heavy Duty" Then numHD = numHD + 4
End Sub

But Set cannot be used outside of a sub or function apparently. Any advice?


texts: I've written remainder(x,y) in OCaml. Is there more efficient than O(n)?

texts:
Here's my code:

let rem x y =
  let rec aux acc i n =
    if i=n then acc else
    if acc+1=y then aux 0 (i+1) n else
    aux (acc+1) (i+1) n in
  aux 0 0 x;;

I'm just learning OCaml and I wonder:

Is this tail recursive?
Is there a more efficient algorithm, i.e., operating in better than linear time?


texts: SQL Server 'Execute As'/Revert pattern in a 'Try/Catch' Block

texts:
I wish to ensure I am using the "best" pattern when using an Execute As/Revert from within a Try/Catch block on SQL Server 2012. The below code "seems" to behave correctly... Am I missing anything or are there any security concerns, "better" approaches, etc.?

Below is my code:

CREATE PROCEDURE [dbo].[TryItOut]
WITH EXECUTE as 'NoTable1Access' --does not have access (select) to Table1!
AS
Begin
  Declare @execErrorNumber int,
           @execErrorMessage nvarchar(2048),
           @xactState smallint

  Begin Try
    Execute as user='HasTable1Access'
    select *, 1/0 as [SimulateError] from [T1].[Table1]; -- This will be a Stored Procedure call, but a select statement was easier to demo...
    Revert --Revert on 'HasTable1Access'
  End Try
  Begin Catch;

        select @execErrorNumber = ERROR_NUMBER(),
               @execErrorMessage = ERROR_MESSAGE(),
               @xactState = XACT_STATE();

        Revert -- Revert on 'HasTable1Access' when in error...
        --Do some error processing in context of 'NoTable1Access'
   End Catch

   select * from [T1].[Table1] --Should NOT have any access now and select should fail...
End


texts:
Exercise 2.37.  Suppose we represent
  vectors v = (vi) as sequences of
  numbers, and matrices m = (mij) as
  sequences of vectors (the rows of the
  matrix). For example, the matrix

  is represented as the sequence ((1 2 3
  4) (4 5 6 6) (6 7 8 9)). With this
  representation, we can use sequence
  operations to concisely express the
  basic matrix and vector operations.
  These operations (which are described
  in any book on matrix algebra) are the
  following:

  We can define the dot product as17

(define (dot-product v w)
(accumulate + 0 (map * v w)))

  Fill in the missing expressions in the
  following procedures for computing the
  other matrix operations. (The
  procedure accumulate-n is defined in
  exercise 2.36.)

(define (matrix-*-vector m v)
  (map <??> m))
(define (transpose mat)
  (accumulate-n <??> <??> mat))
(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map <??> m)))

I wrote the following solutions:

(define (accumulate op initial items)
  (if (null? items)
      initial
      (op (car items) (accumulate op initial (cdr items)))))

(define (accumulate-n op init seqs)
  (if (null? (car seqs))
      null
      (cons (accumulate op init (map (lambda (x) (car x)) seqs))
            (accumulate-n op init (map (lambda (x) (cdr x)) seqs)))))

(define (dot-product v w)
  (accumulate + 0 (map * v w)))

(define (matrix-*-vector m v)
  (accumulate-n +
                0
                (map (lambda (row)
                       (map (lambda (i j) (* i j)) row v)) m)))

(define (transpose mat)
  (accumulate-n (lambda (x y) (cons x y)) null mat))

(define (matrix-*-matrix m n)
  (let ((cols (transpose n)))
    (map (lambda (m-row)
           (accumulate-n +
                         0
                         (map (lambda (col)
                                (map * m-row col))
                              cols))) m)))

(define m1 (list (list 1 2 3 4) (list 4 5 6 6) (list 6 7 8 9)))
(define m2 (list (list 10 20 30) (list 40 50 60) (list 70 80 90) (list 100 110 120)))

(define v1 (list 10 20 30 40))

What do you think?


texts: Submit form data to MYSQL table with PHP execute

texts:
I have written code to send a simple email submission form to a sql table so that I can manage the data. I would like feedback on whether or not the code that I have written is efficient and secure. I have a config file that defines constants for database credentials.

HTML FORM

<form method="post" action="index.php">
    <input class="bt-email" type="email" name="email" placeholder="enter email address">
    <input class="bt-submit" type="submit" value="let's get moving!">
</form>

PHP Database Code File

try {
    $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";port=" . DB_PORT,DB_USER,DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
    echo "Could not connect to the database.";
    exit;
}

PHP/SQL Submission Code

<?php
require_once("inc/config.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];
    require(ROOT_PATH . "inc/database.php");
    try {
        $db->exec("REPLACE INTO launch_email VALUES ('$email')");
    } catch (Exception $e) {
        echo "Data could not be submitted to the database.";
        exit;
    }
    header("Location: index.php?status=thanks");
    exit;
}
?>


texts: Find unique characters and count non unique characters

texts:
We scan the string from left to right finding the unique characters. We also need to find the non unique characters and count them on how many times they appear.
If we can’t find any unique characters, then we return an empty list.

Here’s the code:

def unique_occ(the_str):
    res1 = list(the_str)
    unique_letter = []
    non_unique = []
    for i in res1:
        #there lies the issue
        #as you can see, the loop should take care of the counting.
        #But if is this is the first time that the letters appears
        #, well there is an issue.
        if i not in unique_letter:
            unique_letter.append(i)
        else:
            non_unique.append(i)

    #from that, I need to sort the letters as the for loop is not doing
    #what it is supposed to do

    unique_sort = [elts for elts in unique_letter if elts not in non_unique]
    non_unique1 = [elts for elts in unique_letter if elts in non_unique]

    #the worst part is I need to sort again the letters that have appeared more than once and concatenate them into the list again

    non_unique = non_unique + non_unique1
    non_unique2 = {i:non_unique.count(i) for i in non_unique}

    #finally, the letters have been sorted between the unique and the non unique
    return 'unique letter is {} and non unique letter is {}'.format(unique_sort,non_unique2)

The code works.

There is probably an easier way but I don't see how, at least for now. I'm unsatisfied about the pythonic way of the code.

Any help or insight will be welcomed.


texts:
I've been learning F# for a month or so and I'm wondering how good my "functional" aspect of coding is. When I first started, I did this using an iterative approach with a lot of <- and mutables etc. I tried to rewrite it as functional as possible. Any critique is appreciated.

This code prints out all anagrams in the english dictionary read from a "word.txt" file, the LONGEST anagram, and the anagram with the MOST permutations.

open System

let sortStringAsKey (listOfWords : string array) =
    let getKey (str : string) =
        str.ToCharArray()
        |> Array.sort
        |> String

    listOfWords
    |> Array.groupBy getKey
    |> Array.filter (fun (sortedWord, originalWord) -> originalWord.Length > 1)

[<EntryPoint>]
let main argv =
    let filename = "words.txt"
    let listOfWords = System.IO.File.ReadAllLines(filename)
    let listOfAnagrams = sortStringAsKey listOfWords

    // Prints every single anagram combination
    listOfAnagrams |> Array.iter  (fun (_ , anagramList) ->  anagramList |> Array.iter (fun str -> printfn "%s" str); printfn "")

    // Gets the LONGEST anagram
    let longestAnagrams = listOfAnagrams
                        |> Array.filter (fun (sortedWord, _) -> sortedWord.Length >= (listOfAnagrams
                                                                                |> Array.maxBy (fun (sortedWord, _)-> sortedWord.Length)
                                                                                |> fst
                                                                                |> String.length))

    // Gets the set that has the MOST anagrams
    let mostAnagrams = listOfAnagrams
                        |> Array.filter (fun (_, originalWords) -> originalWords.Length >= (listOfAnagrams
                                                                                |> Array.maxBy (fun (_, originalWords) -> originalWords.Length)
                                                                                |> snd
                                                                                |> Array.length))

    // Prints the longest and most anagrams
    longestAnagrams |> Array.iter  (fun (_ , anagramList) ->  anagramList |> Array.iter (fun str -> printfn "%s" str); printfn "")
    mostAnagrams |> Array.iter  (fun (_ , anagramList) ->  anagramList |> Array.iter (fun str -> printfn "%s" str); printfn "")

    0 // return an integer exit code


texts: K&R C Exercise 1-14: Histogram of the frequency of types of characters

texts:
This is for K&R C Exercise 1-14: basically asking to create a program that prints a histogram of the frequency of types of characters. This is done with very basic C functions/knowledge as covered in the first chapter.

I feel like this code as it stands is pretty clunky with all the for loops to print (though it does function!) Is there a simple way to reduce the number of loops (and also the loop variables) in a more concise way?

#include <stdio.h>

int main()
{
    int c, i, j, k, l, h, nwhite, nother;
    int ndigits[10];

    nwhite = nother = 0;

    for (i = 0; i < 10; ++i)
        ndigits[i] = 0;

    while ((c = getchar()) != EOF)
    {
        if (c >= '0' && c <= '9')
            ++ndigits[c-'0'];
        else if (c == '\n' || c == '\t' || c == ' ')
            ++nwhite;
        else
            ++nother;
    }
    for (j = 0; j <= nwhite; ++j)
    {
        if (nwhite - j > 0)
            putchar('*');
    }
    putchar('\n');
    for (k = 0; k <= nother; ++k)
    {
        if (nother - k > 0)
            putchar('*');
    }
    putchar('\n');
    for (i = 0; i < 10; ++i)
    {
        for (h = 0; h < ndigits[i]; ++h)
        {
            if (ndigits[i] - h > 0)
                putchar('*');
        }
        putchar('\n');
    }
}


texts: Did I overuse / underuse threading locks in my custom list class?

texts:
I am writing a Python module in which two threads access one list. One thread adds 500 items to the list per second, and the other thread reads the list at an irregular interval. I want to make a thread-safe "list" class to avoid having to use locks every time I read or write to the list (suggested by this answer to a previous question on SO).

Here is my first go at a thread-safe list class (with help from these previous SO answers: 1 and 2). Are there any methods that should be locked that are not currently locked, or any methods that do not require a lock that are currently locked?

import collections
import threading

class ThreadSafeList(collections.MutableSequence):
    """Thread-safe list class."""
    def __init__(self, iterable=None):
        if iterable is None:
            self._list = list()
        else:
            self._list = list(iterable)
        self.rlock = threading.RLock()

    def __len__(self): return len(self._list)

    def __str__(self): return self.__repr__()

    def __repr__(self): return "{}".format(self._list)

    def __getitem__(self, i): return self._list[i]

    def __setitem__(self, index, value):
        with self.rlock:
            self._list[index] = value

    def __delitem__(self, i):
        with self.rlock:
            del self._list[i]

    def __iter__(self):
        with self.rlock:
            for elem in self._list:
                yield elem

    def insert(self, index, value):
        with self.rlock:
            self._list.insert(index, value)


texts: Template to determine most frequent entries within a collection

texts:
The problem

Given an arbitrary collection of objects of some kind, count and report the top k most frequent, together with the associated count.  For example, if the input array is {'a', b', 'a', 'c', 'b', 'b'} and for k = 2, the template would return { {b, 3}, {'a', 2} }.  The idea for the template it to allow start and ending iterators for any kind of collection for which ::value_type is defined.

The inspiration

Writing this review reminded me that I had, at one point, written a template to solve exactly this kind of problem. So I searched the hard drive, found this, and thought I'd present it here to see if might be critiqued and improved.

Questions

In particular, I'd be interested in any scenario in which the template fails.  Additionally, are there any checks that could be made to make sure that only suitable iterators are passed?  If so, what might those be?

maxfreq.h

#ifndef MAXFREQ_H
#define MAXFREQ_H
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iterator>

/*
 * This template takes a start and ending iterator of a collection of
 * some kind.  It counts the number of occurences for each instance and
 * returns a vector of the top `k` instances each with their associated
 * count.
 */
template <class InputIt>
auto most_frequent_k(InputIt first, InputIt last, std::size_t k) -> std::vector<std::pair<typename InputIt::value_type, unsigned>> {
    typedef typename InputIt::value_type T;
    typedef typename std::pair<T, unsigned> Tcount;
    std::unordered_map<T, unsigned> count;
    for (; first != last; ++first) {
        ++count[*first];
    }
    std::vector<Tcount> pairs;
    auto m = count.size();
    pairs.reserve(m);
    k = std::min(k, m);
    std::copy(count.begin(), count.end(), std::back_inserter(pairs));
    std::partial_sort(pairs.begin(), pairs.begin()+k, pairs.end(), [](const Tcount &a, const Tcount &b) {
            return a.second > b.second;
            });
    pairs.erase(pairs.begin()+k, pairs.end());
    return pairs;
}

#endif // MAXFREQ_H

test.cpp

#include "maxfreq.h"
#include <iostream>
#include <sstream>

void test1()
{
    std::cout << "Test 1 {\n";
    std::vector<int> input{1,2,3,4,2,3,4,1,1,2,1,2,1,2,1,3,5};
    auto pairs = most_frequent_k(input.begin() , input.end(), 3);
    for (const auto &p : pairs) {
        std::cout << '\t' << p.first << ", " << p.second << '\n';
    }
    std::cout << "}\n";
}

void test2()
{
    std::cout << "Test 2 {\n";
    std::istringstream woodchuck{"how much wood would a woodchuck chuck if a woodchuck could chuck wood"};
    std::vector<std::string> input{};
    std::copy(std::istream_iterator<std::string>(woodchuck), std::istream_iterator<std::string>(), std::back_inserter(input) );
    auto pairs = most_frequent_k(input.begin() , input.end(), 3);
    for (const auto &p : pairs) {
        std::cout << '\t' << p.first << ", " << p.second << '\n';
    }
    std::cout << "}\n";
}

int main()
{
    test1();
    test2();
}

Output

Output from the test driver above looks like this:

Test 1 {
    1, 6
    2, 5
    3, 3
}
Test 2 {
    chuck, 2
    woodchuck, 2
    wood, 2
}


texts:
I have written this piece of JS and CSS loading code and I would like some advice on it. Anything some of the JavaScript gurus could possibly point out would be much appreciated. The code works, but I have not done extensive testing, because I am concerned about replacing functions in this manner.

A single JavaScript file containing JQuery as well as the below code will be included on all the pages. We write all the components in house (which means no Require JS) and keep them very modular separated into their own folder with the corresponding JS and CSS. You can imagine starting to use for instance a dropown, dialog and a datepicker on one page would require us to add 6 includes and this quite frankly is annoying, because I want the dependencies to resolve automatically and using JSP includes could possibly make multiple calls to the same resources.

Below is the source to load a single datepicker lazily:

;(function($){
    //All Lazily loaded components go here
    $.fn.datepicker = function(settings){
        console.log("This should only be displayed once");
        loadCSS("/res/component/datepicker/datepicker.css");
        var elem = this;
        return loadJS("/res/component/datepicker/datepicker.js",
                    function(){return elem.datepicker(settings)});//After Load Completion the $.fn.datepicker is replaced
                                                                  //by the proper working implementation, execute it and return it so we maintain the chain
    };
}(jQuery));

function loadCSS(absoluteUrl){
    if(loadCSS[absoluteUrl])
        return;//Css already loaded

    $('<link>')
      .appendTo('head')
      .attr({type : 'text/css', rel : 'stylesheet'})
      .attr('href', absoluteUrl);//Appending entire element doesn't load in IE, but setting the href in this manner does

    loadCSS[absoluteUrl] = true;//Memoize
}

function loadJS(absoluteUrl, onComplete){
    if(loadJS[absoluteUrl])
        return;//Script already loaded

    loadJS[absoluteUrl] = true;//Memoize

    var result;
    jQuery.ajax({
        async : false,//Synchronized because we need to maintain the JQuery chain
         type :'GET',
          url : absoluteUrl,
     dataType :'script',
      success : function(){
                    result = onComplete();
                }
    });

    return result;
}


texts: Implementing `components(separatedBy:)` method in Swift

texts:
On looking at the components(separatedBy separator: String) -> [String] method from the Swift Standard Library, I tried to come up with an implementation just for practice. Your comments are welcome to improve the same. Thanks.

Input:

func main() {
    let sampleString = "Do not be sorry. Be better."
    print(sampleString.components(separatedBy: "."))
}

Output:

["Do not be sorry", " Be better", ""]

Implementation:

extension StringProtocol {

    func components<T>(separatedBy separatorString: T) -> [String] where T: StringProtocol {

        var currentIndex = 0; var stringBuffer = ""; var separatedStrings:[String] = []

        forEach { (character) in

            if String(character) == separatorString {
                separatedStrings.append(stringBuffer); stringBuffer = ""
            } else {
                stringBuffer += .init(character)
            }

            if currentIndex == lastIndex { separatedStrings.append(stringBuffer) }
            currentIndex += 1
        }
        return separatedStrings
    }
}

extension Collection {
    var lastIndex:Int {
        get {
            return self.count - 1
        }
    }
}


texts: Project Euler#61: Cyclical figurate numbers

texts:
Project Euler Problem 61 asks:

  Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:

  $$\begin{array}{lll}
\textrm{Triangle}  & P_{3,n}=n(n+1)/2  & 1, 3, 6, 10, 15, \ldots\\
\textrm{Square}   & P_{4,n}=n^2  & 1, 4, 9, 16, 25, \ldots\\
\textrm{Pentagonal}  & P_{5,n}=n(3n−1)/2  & 1, 5, 12, 22, 35, \ldots\\
\textrm{Hexagonal}  & P_{6,n}=n(2n−1)  & 1, 6, 15, 28, 45, \ldots\\
\textrm{Heptagonal}  & P_{7,n}=n(5n−3)/2  & 1, 7, 18, 34, 55, \ldots\\
\textrm{Octagonal}  & P_{8,n}=n(3n−2)  & 1, 8, 21, 40, 65, \ldots
\end{array}$$

  The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties.

  The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first).
  Each polygonal type: triangle \$(P_{3,127}=8128)\$, square \$(P_{4,91}=8281)\$, and pentagonal \$(P_{5,44}=2882)\$, is represented by a different number in the set.
  This is the only set of 4-digit numbers with this property.

  Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set.

While revising my previous solutions to bound under 5 seconds (because this is the most logical limit for any project Euler solution, otherwise the algorithm is flawed or not the best) I came to this which runs in around 10-15 seconds (peak at 12).

I have tried to make it better but I can't think of any remarkable improvements yet.

    static Stack<Integer> figurateStack;

    public static int get61() {
    figurateStack = new Stack<Integer>();
    int count = -1;
    int i = 1111;// minimum
    final int n = 6;
    final int low_lim = 3;
    int[] a = new int[n];
    boolean flag = false;// flag to use as a stepback conjugate
    boolean stepback = false;
    do {
        flag = false;
        if (count < n - 2) {
            for (; i < 9999; i++) {
                if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
                    if (count == -1 || (count >= 0 && i / 100 == a[count] % 100) && i > 1000) {
                        ++count;
                        a[count] = i;
                        break;
                    } else {
                        figurateStack.pop();
                    }
                }
            }
        } else {
            i = (i % 100) * 100 + a[0] / 100;
            if (isSpecialFigurate(i, low_lim, low_lim + (n - 1))) {
                ++count;
                a[count] = i;
                break;
            } else {
                stepback = true;
            }
        }
        if (i == 9999) {
            stepback = true;
        }
        if (stepback) {
            figurateStack.pop();
            i = a[count] + 1;
            --count;
            flag = true;
            stepback = false;
        }
        if (count < n - 2 && !flag) {
            i = 100 * (i % 100) + 10;
            flag = false;
        }
    } while (count < 6);
    return a[0] + a[1] + a[2] + a[3] + a[4] + a[5];
}

public static boolean isSpecialFigurate(int x, int lowlim, int upplim) {
    for (int index = lowlim; index <= upplim; index++) {
        if (!figurateStack.contains(index)) {
            long n = (long) Math.floor((Math.sqrt(8 * (index - 2) * x + (index - 4) * (index - 4)) + (index - 4)) / (2 * (index - 2)));
            if (getFigurateNumbers(n, index) == x) {
                figurateStack.push(index);
                return true;
            }
        }
    }
    return false;
}

    public static long getFigurateNumbers(long n, int r) {
    return (n * n * (r - 2) - n * (r - 4)) / 2;
}


texts:
I would like to know an alternative, more elegant way to write the following methods.

I am especially not enthusiastic of the nested if statement or if for validate null values.

Now there are 3 if statement for null validation.

Any method:

   private void LoadAlertas()
        {
            // *** OMITTED ***

            // Nullable object must have a value
            var PortalUser = HttpContext.Current.User.PortalUser();
            if (string.IsNullOrWhiteSpace(PortalUser)) throw new ArgumentNullException("HttpContext.Current.User.PortalUser is null");
            var personalData = PersonalData.getPersonalData(PortalUser);
            if (personalData == null) throw new ArgumentNullException("PersonalData.getPersonalData is null para " + PortalUser);
            if (!personalData.iID_PersonalData.HasValue) throw new ArgumentNullException("personalData.iID_PersonalData is null");

            var userLogado = Bll.PortalUser.getUsarioPortalByIdPersonalData(personalData.iID_PersonalData.Value);

Another method:

 protected void Btn_Accion_Click(object sender, EventArgs e)
        {
            // *** OMITTED ***

            // Nullable object must have a value
            var PortalUser = Page.User.PortalUser();
            if (string.IsNullOrWhiteSpace(PortalUser)) throw new ArgumentNullException("Page.User.PortalUser is null");
            var personalData = MyPortal.AdminManager.Bll.PersonalData.getPersonalData(PortalUser);
            if (personalData == null) throw new ArgumentNullException("PersonalData.getPersonalData is null para " + PortalUser);
            if (!personalData.iID_PersonalData.HasValue) throw new ArgumentNullException("personalData.iID_PersonalData is null");

            var userLogado = MyPortal.AdminManager.Bll.PortalUser.getUsarioPortalByIdPersonalData(personalData.iID_PersonalData.Value);
            var userConsultado = setuserConsultado();


texts: strToHex ( string to its hex representation as string)

texts:
I want to convert strings to their hex representations as strings too (like hex dump programs), for example "abz" to "61627A".

char * strToHex( char * str )
{
    int length = strlen ( str );
    char * newStr = malloc( length  * 2 );
    if ( !newStr ) shutDown ( "can't alloc memory" ) ;

    for ( int x = 0; x < length; x++){
        char y = str[ x ];
        sprintf ( newStr + x * 2, "%02X", y );
    }
    return newStr;
}

ShutDown definition is omitted here, it is a function that calls perror and exit()

I designed strToHex to be used like

char * str = "abcdefghijklmnopqrstuvwxyz";
char * hex = strToHex(str);
printf("%s\n",hex);
//outputs : 6162636465666768696A6B6C6D6E6F707172737475767778797A


texts: LogParser function: kill application and send email

texts:
I've created a new tool, which parses a specified log file, and if an Oracle exception is there, it kills Tomcat and sends an email notification.

I tried to take into account comments from my previous post, but I'm sure there is enough stuff that can be improved.

This utility uses python-tail module to get data from the log.

As the tool is big enough, here are just a few main functions:

# sending notifications
def sendmail(event):
        try:
                # get time
                time = datetime.datetime.now()
                timemes = '\n\nSysevent at %s' % time

                # connect to local SMTP
                smtpconnect = smtplib.SMTP('localhost:25')
                # debug to sys.stdout currently is $OUTPUT_DIR/logparcer_mail.log
                smtpconnect.set_debuglevel(1)
                # sending email
                smtpconnect.sendmail(sender, receivers, message + event + timemes)
                # close conenction
                smtpconnect.quit()
                logging.info('Email sent from %s to %s.' % (sender, receivers))
        # if anything wrong on local SMTP
        except socket.gaierror as s:
                logging.exception('Local SMTP error: %s' % s)
        except smtplib.SMTPException as e:
                logging.exception('ERROR during email sent: %s' % e)

Tail calls:

# running main tail
tail = tail.Tail(catalinalog)
# when new line appears - sent it to 'err' function
tail.register_callback(err)
tail.follow()

Errors to rise KILL:

# list of errors to parce
errors = ('ORA-01017', 'ORA-28000')

And err function, which parses data from Tail:

# main error parces function
def err(data):
        # check both errors
        if any(ora in data for ora in errors):

                # on PROD we don't need kill Tomcat
                if not env == 'PROD':
                        # get Tomcat's PID
                        pid = catapid(tpidf)
                    # kill Tomcat with kill -9
                    try:
                            # killing Tomcat with kill -9
                            os.kill(int(pid), signal.SIGKILL)
                            # save message for email and log
                            event = "Tomcat killed with PID %s.\n\nError data: \n\n%s" % (pid, data)
                            logging.error(event)
                            # sending email
                            sendmail(event)
                            logging.info('Email sent from %s to %s.\n' % (sender, receivers))
                            # as Tomcat killed - LogParcer doesn't need anymore
                            # will be started again when LMSmanager -start
                            sys.exit(0)
                    # if can't find catalina.pid
                    except OSError as e:
                            event = "Got ALARM, but can't kill Tomcat: %s with PID %s" % (e, pid)
                            sendmail(event)
                            logging.critical(event)
                # if PROD - just send email, no kill
                else:
                       event = "Tomcat wasn't killed. Please - check logs manually.\n"
                       sendmail(event)
                       logging.error(event)

And one from my 'main' question is: is it good practice to call one function from inside of another (sendmail() from err())?


texts:
I post the below code as review/answer to a question in codereview.
(Custom Dynamic Array)
however, seems the answer itself having issues looking at the comments that I received.
I would appreciate your valuable review comments:

public class DynamicArray<T> : IEnumerable<T>, ICollection<T>
{
private T[] _items;

public DynamicArray()
{
}

public int Count
{
    get
    {
        if (_items == null)
            return 0;
        return _items.Length;
    }
}

public bool IsReadOnly => false;

public void Add(T item)
{
    if(item==null)
         throw new ArgumentException("item");

    if (_items == null)
    {
        _items = new T[1];
    }
    else
    {
        Array.Resize(ref _items,_items.Length+1);
    }
    _items[_items.Length - 1] = item;
}

public void Clear()
{
    _items = null;
}

public bool Contains(T item)
{
    if (_items == null)
        return false;
    return _items.Contains(item);
}

public void CopyTo(T[] array, int arrayIndex)
{
    _items.CopyTo(array, arrayIndex);
}

public IEnumerator<T> GetEnumerator()
{
    if (_items == null)
        return Enumerable.Empty<T>().GetEnumerator();
    return _items.AsEnumerable().GetEnumerator();
   }

public bool Remove(T item)
{
    if (item == null)
        return false;

    if(_items==null)
        return false;

    var temp = _items.Where(i => !i.Equals(item));
    _items = temp.ToArray();

    return true;
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}
}


texts: C++ console based - "Word Guessing" game

texts:
I have made a console game in C++ which is called "Word Guessing", and according to the compiler, it is using about 542 KB of memory.

I am mainly wondering if it's possible to decrease the memory usage some more, and if possible, how it can be improved.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

// Function Declaration
string getRandWord();
void checkLetter(char&, string&, int&, string&);

// main function
int main() {

    // str Variables
    string RandomWord = getRandWord();
    string hiddenWord = "";

    // int Variables
    unsigned long int _length_ = RandomWord.length();
    int chances = int(_length_)+1;
    char newLetter;

    // fill varialbe with characters
    hiddenWord.append((_length_),'_');

    cout << "The Word is "<< _length_ <<" letters long." << endl;

    // game loop
    while(chances > 0){
        // request (char) input
        cin >> newLetter;
        checkLetter(newLetter, RandomWord, chances, hiddenWord);

        // check if player won
        if(hiddenWord == RandomWord){
            cout << "Congratulations! You won the game." << endl;
            break;
        }
        // decrease try chances
        chances--;
    }

    return 0;
}

// Functions

void checkLetter(char &newLetter, string &randstr, int &strlen, string &hiddenWord){
    // initiate iterator it
    string::iterator it;

    // iterate trough string
    for(auto it = randstr.begin(); it != randstr.end();++it){
        // validate letter mach
        if(*it == newLetter){
            // replace letter
            hiddenWord.at(it - randstr.begin()) = newLetter;
        }
    }
    cout << hiddenWord << endl;
}

string getRandWord(){
    string filePath = "/Users/nedimkanat/XCODE/testcpp/testcpp/";

    // constants
    enum sizes {
        COUNTER = 0,
        ARRAY_SIZE = 5
    };

    // set seed
    srand((unsigned)time(NULL));

    // get random int between 0 and 5
    int randint = rand() % ARRAY_SIZE;

    // str to store each line from file
    string str;

    // array to store 5 (random) words
    vector<string> arr;

    // initialize file object & open file
    ifstream file(filePath+"words.txt");
    int counter = COUNTER;

    // loop trough file
    if (file.is_open()){
        while (getline(file,str) && counter < ARRAY_SIZE){
            arr.push_back(str);
            counter++;
        }
        file.close();
    } else {
        cout << "File is not open" << endl;
    }

    // send away random word
    if(arr.empty()){
        cout << "CANCER" << endl;
    }
    return arr.at(randint);
}


texts:
I need to calculate checksum using 16-bit ones' complement addition:

while(byte>0)  //len = Total num of bytes
{
    Word = ((Buf[i]<<8) + Buf[i+1]) + Checksum; //get two bytes at a time and  add previous calculated checsum value

    Checksum = Word & 0x0FFFF; //Discard the carry if any

    Word = (Word>>16);     //Keep the carryout for value exceeding 16 Bit

    Checksum = Word + Checksum; //Add the carryout if any

    len -= 2; //decrease by 2 for 2 byte boundaries
    i += 2;
}

 Checksum = (unsigned int)~Checksum;

The above code works fine, and if I understood the concept well (to add 16 bits), add the carry if any and then take the compliment.

Are there any improvements or corrections?


texts: extending Exception to allow for auto appending class name on exception message

texts:
Got this idea from the php.net website on extending exceptions. The main thing I wanted with this was to have the exception name auto imprinted on the exception message, so I wouldn't have to write it in each message. So far its working, just wondering if this is efficient or not?

Thanks

class DataException extends Exception
{
   protected $solved;
   protected $howSolved;

   public function __construct($message, $solved = false, $howSolved = null,
                               $code = 0, Exception $previous = null)
   {
      $this->solved = $solved;
      $this->howSolved = $howSolved;

      // make sure everything is assigned properly
      parent::__construct($message, $code, $previous);
   }

   public function setSolved($isSolved)
   {
      $this->solved = $isSolved;
   }

   public function setHowSolved($howSolved)
   {
      $this->howSolved = $howSolved;
   }

}

class GeoCoordinateOutOfBoundsException extends DataException
{
   public function __construct($message, $solved = false, $howSolved = null,
                               $code = 0, Exception $previous = null)
   {
      $message = get_class($this) . "::" . $message;

      // make sure everything is assigned properly
      parent::__construct($message, $solved, $howSolved, $code, $previous);
   }
}


texts:
My definition of monkey testing is basically playing with a program in as if I was a monkey (press every button, unplug things, go in the wrong order..etc etc)

So I made a rather simple SmartCard library that when I "enable" it it just polls the smart card reader for a card, and reports back information. see code

private void CardStatusChange()
{
    readerState[0].dwCurrentState = SCardState.SCARD_STATE_UNAWARE;
    while (run)
    {
        System.Threading.Thread.Sleep(100);
        if (SCWrapper.SCardGetStatusChange(scHandle, UInt32.MaxValue, readerState, 1) == SCardFunctionReturnCodes.SCARD_S_SUCCESS)
        {
            readerState[0].dwCurrentState = readerState[0].dwEventState;
            SendCardStatus(readerState[0].dwEventState);
        }
    }
}

private void SendCardStatus(SCardState sCardState)
{
        //case SCardState.SCARD_STATE_UNAWARE:
        //case SCardState.SCARD_STATE_IGNORE:
        //case SCardState.SCARD_STATE_CHANGED:
        //case SCardState.SCARD_STATE_UNKNOWN:
        //case SCardState.SCARD_STATE_UNAVAILABLE:
        //case SCardState.SCARD_STATE_EMPTY:
    if (HasStateMask(sCardState, SCardState.SCARD_STATE_EMPTY))
        OnCardUnplugged(); //fire event
        //case SCardState.SCARD_STATE_PRESENT:
    if (HasStateMask(sCardState, SCardState.SCARD_STATE_PRESENT))
    {
        OnCardPluggedIn(); //fire event
        SendCardATR(readerState[0].rgbAtr); //fire event
    }
        //case SCardState.SCARD_STATE_ATRMATCH:
    OnATRMatch(HasStateMask(sCardState, SCardState.SCARD_STATE_ATRMATCH));
        //case SCardState.SCARD_STATE_EXCLUSIVE:
        //case SCardState.SCARD_STATE_INUSE:
    OnCardInUse(HasStateMask(sCardState, SCardState.SCARD_STATE_INUSE));
        //case SCardState.SCARD_STATE_MUTE:
        //case SCardState.SCARD_STATE_UNPOWERED:
}

private bool HasStateMask(SCardState theValue, SCardState theMask)
{
    return ((theValue & theMask) == theMask);
}

This part works as expected in that while my thread is running I can plug in and unplug a smartcard as often and as quickly as I want without problem. What I'm struggling with is the Threading portion of it. Visual Studio screams at me for using suspend and I found a bug when using suspend in my thread so I am taking that out (in other words don't comment on that) but this is how I "open" and "enable" my smart card

public override bool Open()
{
    readerThread = new Thread(CardStatusChange);
    //code here to setup the smart card
    return true;
}

public override bool Enable()
{
    run = true;
    //thread start checking for card events
    switch (readerThread.ThreadState)
    {//this is probably a mistake
        case ThreadState.AbortRequested:
            break;
        case ThreadState.Aborted:
            break;
        case ThreadState.Background:
            break;
        case ThreadState.Running:
            break;
        case ThreadState.StopRequested:
            break;
        case ThreadState.Stopped:
            break;
        case ThreadState.SuspendRequested:
            break;
        case ThreadState.Suspended:
            readerThread.Resume();//TODO remove

            break;
        case ThreadState.Unstarted:
            readerThread.Start();

            break;
        case ThreadState.WaitSleepJoin:
            break;
        default:
            break;
    }

    return true;
}
public override void Disable()
{
    run = false;
    readerThread.Suspend(); //TODO remove
}

I've never been too good at threading, but I do need this as a thread (I think I do atleast I am open to other ideas). So how should I really Enable and Disable? I used to just set run to true or false, but my monkey testing showed that this doesn't always work and sometimes Windows would cry that it can't start a running thread... SO I dunno what to do. Any thoughts?


texts: Displaying a scheduled job under a scheduled time

texts:
I use at to schedule jobs and atq to display the scheduled jobs. But it mildly irritates me in that I have to look up each job individually.  I wrote a Python script to display the scheduled job under the scheduled time.

(In my world all the commands will begin 'task')

So instead of

stafflinux$atq
8   Mon Aug 18 09:00:00 2014 a joseph
10  Tue Aug 19 09:00:00 2014 a joseph
15  Thu Aug 21 09:00:00 2014 a joseph
12  Fri Aug 22 09:00:00 2014 a joseph
9   Thu Aug 21 09:00:00 2014 a joseph
14  Sat Aug 30 09:00:00 2014 a joseph
7   Sun Aug 17 09:00:00 2014 a joseph
6   Mon Aug 18 09:00:00 2014 a joseph
11  Sat Aug 30 09:00:00 2014 a joseph
stafflinux$

My script produces

stafflinux$./atscript.py
8  Mon Aug 18 09:00:00 2014 a joseph
task "buy a four-way plug adapter"
task "see guy about meeting"
-----------------------------------------
10  Tue Aug 19 09:00:00 2014 a joseph
task "bring back personal effects from office"
-----------------------------------------
15  Thu Aug 21 09:00:00 2014 a joseph
task "book tickets for next week"
-----------------------------------------

I'm looking for any feedback - particularly in terms of 'pythonic' style and any and all tricks I may have missed:

#!/usr/bin/python
import os
os.system("atq > attemp.txt")
file = open("attemp.txt")
line = file.readline()
while line:
    number =line[:2]
    print line.strip()
    os.system("at -c "+ number+ "| grep task")
    line=file.readline()
    print '-----------------------------------------'
print line
os.system("rm attemp.txt")


texts: Find redundant braces in an input string

texts:
I am solving interview questions from here.

  Problem : Write a program to validate if the input string has redundant braces

  Return 0/1 :

  0 --> NO

  1 --> YES

  Input will be always a valid expression and operators allowed are only + , * , - , /

  Example:

  ((a + b)) has redundant braces so answer will be 1

(a + (a + b)) doesn't have have any redundant braces so answer will be 0

How can I improve my solution?

def redundant_braces(exp):
    """returns 1 if any redundant bracket is present else returns 0"""
    cnt = 0  ## counter for elements popped from stack
    if '(' not in exp:
        return 0
    stack = []
    ## add elements in stack until closing bracket encountered
    for i in exp:
        stack.append(i)
        if i == ')' :
            stack.pop()  ## remove the last closing bracket
            while stack.pop() != '(':  ## check for last opening bracket
                cnt += 1
            if cnt  == 0 or cnt == 1:
                return 1

        cnt = 0  ## reset counter to zero
    return 0

assert redundant_braces("(a)") == 1
assert redundant_braces("(a+(a+b))") == 0
assert redundant_braces("(a+b)")   == 0
assert redundant_braces("(a*b)+(b*c)") == 0
assert redundant_braces("(a+((a+b)))") == 1
assert redundant_braces("((a+(a+b)))") == 1


texts:
There is a large list of email addresses and there is a limitation of max 100 email addresses to process once. This is the code I have written.

        //Create a list of email addresses to test
        List<string> emails = new List<string>();
        for (int i = 0; i < 10000; i++)
        {
            emails.Add(string.Format("email{0}@domain.com", i));
        }

        //buffered read
        int remainingCount = emails.Count;
        int maxToReadOnce = 100;
        int startIndex = 0;
        while(remainingCount > 0)
        {
            int countToRead = (remainingCount > maxToReadOnce) ? maxToReadOnce : remainingCount;
            List<string> myemails = emails.GetRange(startIndex, countToRead);
            startIndex = startIndex + countToRead;
            remainingCount = remainingCount - countToRead;
            Process(myemails); // Method that process the email addresses
        }


texts: Parsing data from big json field and geocode services then store to PostgreSQL using psycopg2 instead django-orm

texts:
This code works, but my boss told me that it's very bad code, and don't want to deploy it. It is my first time working as a programmer and I have at least 3 months of experience.

# -*- coding: utf-8 -*-

import psycopg2.extras
import time
import json
from psycopg2.extensions import AsIs
from methods_grabber import get_district, get_city,\
                            get_street, get_house, get_postcode
time_start = time.time()

conn = psycopg2.connect("dbname=gym user=gyms")

def get_data():

    global conn

    dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    dict_cur.execute("""
                    SELECT *
                    FROM dblgis_grabber_firm;
                    """
                    )

    res = dict_cur.fetchall()
    dict_cur.close()
    return res

def update_data(id_row, row, data):
    global conn

    cur = conn.cursor()

    query = "UPDATE dblgis_grabber_firm SET %s=%s WHERE id=%s;"

    cur.execute(query, (AsIs(row), data, id_row))

    conn.commit()
    cur.close()
    return cur.rowcount

data = get_data()

def get_from_contacts(contact_group, row_name, representation, id_row):
    result = []
    for contacts in contact_group:
        for contact in contacts.get('contacts'):
            if contact.get('type') == representation:
                result.append(unicode(contact.get('text')))
    result = '; '.join(result)
    update_data(id_row, row_name, result)

def fill_data(instance):

    longitude = instance.get('longitude')
    latitude = instance.get('latitude')

    id_row = instance.get('id')

    contact_group = json.loads(instance.get('all_data', {})).get('contact_groups', {})

    if not instance.get('street'):
        street = get_street(longitude, latitude)
        if street:
            update_data(id_row, 'street', street)

    if not instance.get('street_number'):
        street_number = get_house(longitude, latitude)
        if street_number:
            update_data(id_row, 'street_number', street_number)

    if not instance.get('postcode'):
        postcode = get_postcode(longitude, latitude)
        if postcode:
            update_data(id_row, 'postcode', postcode)

    get_from_contacts(contact_group, 'phone_number', 'phone', id_row)
    get_from_contacts(contact_group, 'site', 'website', id_row)
    get_from_contacts(contact_group, 'email', 'email', id_row)

for d in data:
    fill_data(d)

conn.close()

print 'Timeit %s' % (time.time() - time_start)

It use my methods from methods, which resolves data from yandex and geopy lib.

After parsing big JSON data, it writes changes to the DB. It's tested for 4k elements and works for 230sec. I think it's normal, but why is it so bad?


texts: Generating a sequence number based on last item of a list

texts:
I wrote this method in order to generate a sequence number based on a specific pattern:

public string LatestNumber(Guid id = default(Guid))
{
    var number = "";
    if (id == Guid.Empty)
    {
        var items = myList.ToList();
        var lastNumber = items.Any() ? items[items.Count - 1].Number : "";

        var intitialNumber = "Number#000001";
        if (!items.Any())
            number = intitialNumber;
        else
        {
            var nextNumber = int.Parse(lastNumber.Split('#')[1]) + 1;
            number = $"Number#{nextNumber:D6}";
        }
    }
    else
    {
        number = myList.FirstOrDefault(p => p.Id == id).Number;
    }

    return number;
}

This code works as expected in production but I wonder if there's a better way to make this code clean or more testable. What do you think?


texts: Two CSS grids side by side, one is scrollable, the other isn't

texts:
I've made a section of my site to have two grids side by side. On the left-hand side is one big static (sticky in my case) image, on the right-hand side is a (grid) long column of several other images, that is scrollable. So as the user scrolls the grid on the right-hand side of the page, the grid on the left remains 'stuck' until the user has reached the end of the grid on the right.

My code below works, but I was wondering if there a more elegant way of doing this?

html,
body,
p,
ol,
ul,
li {
  background-color: #1A1A1A;
  margin: 0;
  padding: 0;
}

.container {
  height: 100vh;
  width: 95%;
  margin: auto;
  position: relative;
}

#tattoos {
  width: 95%;
  display: flex;
  justify-content: space-between;
  height: 2000px;
  position: relative;
}

#sectionOne {
  display: grid;
  height: 100vh;
  grid-template-rows: repeat(1, 1fr);
  grid-template-columns: repeat(1, 1fr);
  grid-gap: 15px;
  width: 60%;
  position: sticky;
  top: 0;
}

.gallery-item {
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 1;
  text-transform: uppercase;
  font-family: 'Lora';
  font-weight: 700;
  color: white;
  font-size: 9vw;
}

#image-one {
  background-image: url("https://i.ibb.co/HXfG735/tattoo.jpg");
  background-size: cover;
  background-position: 0% 80%;
  box-shadow: inset 0 0 0 2000px rgba(0, 0, 0, 0.8);
  margin: 4% 0;
}

.sectionTwo {
  width: 37%;
  display: grid;
  height: 1940px;
  grid-template-rows: repeat(7, 1fr);
  grid-template-columns: repeat(1, 1fr);
  grid-gap: 30px;
  margin: 2.5% 0;
}

#image-two {
  background-image: url("https://i.ibb.co/kBJrryt/7ab34470-9318-4fc1-a6da-656ca31399c5.jpg");
  background-size: cover;
  background-position: 0% 80%;
}

#image-three {
  background-image: url("https://i.ibb.co/SKCnT4d/b19aaf2a-84cf-42b4-9ccd-6205ca1be395.jpg");
  background-size: cover;
  background-position: 0% 50%;
}

#image-four {
  background-image: url("https://i.ibb.co/xF4Qv50/b5d6695b-2142-42cc-8eef-2963311edfd6.jpg");
  background-size: cover;
  background-position: 0% 60%;
}

#image-eight {
  background-image: url("https://i.ibb.co/0nY3VDG/d1ecf205-6b1b-4a1a-b94b-7d75aa177464.jpg");
  background-size: cover;
  background-position: 0% 60%;
}

#image-nine {
  background-image: url("https://i.ibb.co/QYf6vDY/48a63fe2-066b-42d1-9211-040c6977ceff.jpg");
  background-size: cover;
  background-position: 0% 40%;
}

#image-ten {
  background-image: url("https://i.ibb.co/7RdJqgP/ce30fff2-1679-403f-8431-c6be4f8b1466.jpg");
  background-size: cover;
  background-position: 0% 80%;
}

#image-twelve {
  background-image: url("https://i.ibb.co/BtJxDc7/24b54530-710f-4173-a32a-36bd24a496e0.jpg");
  background-size: cover;
  background-position: 0% 50%;
}

      tatujes


texts: What improvements can I make to this table filtering jQuery Plugin?

texts:
This plugin is meant to filter through a table based on column header text that matches options given to it.
check it out here: Filter Table Plugin

Plugin code below for reference:

//framework from http://jqueryboilerplate.com/
; (function ($, window, document, undefined) {

    var pluginName = "filterTable",
        defaults = {
        };
    function Plugin(element, options) {
        this.element = element;

        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype = {

        init: function () {

            $el = $(this.element);
            $table = $('#' + $el.data('filtertable'));
            var filterColumnNames = ($el.attr('data-filtercolumns')).split(',');
            var filterColumns = new Array();
            var altRowCSS = $el.data('filteralternatingcss');

            //get the column index of the column we'll be filtering on
            $table.find('th').each(function (i) {
                for (j in filterColumnNames) {
                    if ($(this).text().trim() == filterColumnNames[j]) {
                        filterColumns.push(i + 1);
                    }
                }
            });

            $el.keyup(function () {
                var query = $(this).val();
                var numDisplayed = 0;
                //remove any no result warnings
                $table.find('#noResultsRow').remove();
                //hide all rows
                $table.find('tr').removeClass(altRowCSS).hide();
                //show the header row
                $table.find('tr:first').show();
                for (i in filterColumns) {
                    $table.find('tr td:nth-child(' + filterColumns[i] + ')').each(function () {
                        if ($(this).text().toLowerCase().indexOf(query.toLowerCase()) >= 0) {
                            $(this).parent().show();
                            numDisplayed++;
                        }
                    });
                }
                if (numDisplayed == 0) {
                    $tr = $('<tr>');
                    $tr.attr('id', 'noResultsRow');
                    $td = $('<td>').attr('colspan', $table.children('tbody').children('tr').children('td').length);
                    $td.html('No results for filter "' + query + '."');
                    $td.css({ textAlign: 'center' });
                    $tr.append($td);
                    $table.children('tbody').append($tr);
                }
                $table.find('tr:visible :odd').addClass(altRowCSS);
            });
            $el.keyup();
        },
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);

Any improvements I can make?