texts:
I'm currently working on this problem for my own practice. It's a paintball problem where I should determine if everyone can get a unique target. The problem is as follows I get a number of pair like:

1 2
3 4
3 2
4 1

If I get 1 2 it means that 1 can see 2 and therefore 1 can target 2. It goes the other way around to so 2 can see 1 and therefore 2 can target 1.

My assignment is to determine if everyone can get an unique target. If so I should output the numbers in order so first numbers 1 target than who number 2 should target and so on.

My implementation goes as follows:

I read in the number of players and lines.
For each line I create an edge.
Then I create a bool array to keep track if a player has a target and another bool array to see if a player is a target.
Then use a recursive method to find out the path which all player gets a target.
I also have a graph class to keep track of all the edges.

I need advice on what I'm doing wrong or any tips on the implementation.

  class Graph{
      std::list<int> graph[1000];
   public:
     void addEdge(int from, int to){
        graph[from].push_back(to);
    }
    std::list<int> getEdges(int e){
      std::list<int> myList = graph[e];
      return myList;
}

};

int n;
bool res = false;
int cnt = 0;
void checkPlayers(Graph graph,bool hasTarget[],bool isTarget[],int i,std::string myRes){
std::list<int> list = graph.getEdges(i);

std::list<int>::const_iterator iterator;
for(iterator = list.begin(); iterator != list.end(); ++iterator){
     int currentplayer = (*iterator);

     if(hasTarget[i] == false && isTarget[currentplayer] == false && currentplayer <= n){
       hasTarget[i] = true;
       isTarget[currentplayer] = true;
       cnt++;
       myRes += std::to_string(currentplayer);
       checkPlayers(graph, hasTarget, isTarget,++i,myRes);
       hasTarget[i] = false;
       isTarget[currentplayer] = false;
       cnt--;
       //myRes.erase(myRes.begin()+ st)
     }
 }
    if(cnt == n && res == false ){
     res = true;
     std::cout << myRes << std::endl;
  }
}

     int main(){
     int m;
     int playerOne, playerTwo;
     Graph graph;
     for(std::cin >> n >> m; m; --m){
       std::cin >> playerOne >> playerTwo;
       graph.addEdge(playerOne,playerTwo);
       graph.addEdge(playerTwo,playerOne);
     }
     bool isTarget[1000] = {false};
     bool hasTarget[1000] = {false};
     checkPlayers(graph,hasTarget, isTarget,1,"");
  }


texts: calculate tree height (arbitrary tree) - python

texts:
Given an array as input, we have to calculate the tree height. For example, input [4, -1, 4, 1, 1] means that there are 5 nodes with numbers from 0 to 4, node 0 is a child of node 4, node 1
is the root, node 2 is a child of node 4, node 3 is a child of node 1 and node 4 is a child of node 1.
I have a very low performing code that loops over the input more than once:
def height(array):
        di= {array.index(-1):-1}
        while (len(di)<len(array)):
                for i, p in enumerate(array):
                        if p in di.keys():
                                di[i] = di[p] - 1
        max_distance = -1
        for val in di.values():
                if val < max_distance:
                        max_distance = val
        max_distance = abs(max_distance)
        return max_distance

Another method I'm trying is I group the child nodes together like this:
input [9, 7, 5, 5, 2, 9, 9, 9, 2, -1] I group then to {9: [0, 5, 6, 7], 7: [1], 5: [2, 3], 2: [4, 8], -1: [9]} But I'm stuck and have no idea if I'm on the right track or what to do after this. Please let me know what you think. Much appreciated!


texts: Making the Levenshtein distance code cleaner

texts:
I was writing an implementation of Levenshtein distance in Python and I found my code really ugly.
Have you any idea how to make it more elegant?

import unittest
import enum

def seq_dist(first, second):
    Direction = enum.Enum('Direction', 'gap_first gap_second match finish')

    def find_dist():
        dist_table = [(len(second) + 1) * [0] for i in range(len(first) + 1)]
        directions = [(len(second) + 1) * [None] for i in range(len(first) + 1)]
        for i in range(len(first) + 1):
            for j in range(len(second) + 1):
                if (i, j) == (0, 0):
                    dist_table[i][j] = 0
                    directions[i][j] = Direction.finish
                elif i == 0:
                    dist_table[i][j] = j
                    directions[i][j] = Direction.gap_first
                elif j == 0:
                    dist_table[i][j] = i
                    directions[i][j] = Direction.gap_second
                else:
                    gap_first = dist_table[i - 1][j] + 1
                    gap_second = dist_table[i][j - 1] + 1
                    match = dist_table[i - 1][j - 1] + (first[i-1] != second[j-1])
                    if gap_first <= min(gap_first, match):
                        dist_table[i][j] = gap_first
                        directions[i][j] = Direction.gap_second
                    elif gap_second <= min(gap_second, match):
                        dist_table[i][j] = gap_second
                        directions[i][j] = Direction.gap_first
                    else:
                        dist_table[i][j] = match
                        directions[i][j] = Direction.match
        return dist_table, directions

    def backtrack(directions):
        i, j = (len(first), len(second))
        seq = []
        while directions[i][j] != Direction.finish:
            direction = directions[i][j]
            if direction == Direction.gap_first:
                seq.append((None, second[j-1]))
                j -= 1
            elif direction == Direction.gap_second:
                seq.append((first[i-1], None))
                i -= 1
            elif direction == Direction.match:
                seq.append((first[i-1], second[j-1]))
                i -= 1
                j -= 1
        seq.reverse()
        return seq

    dist_table, directions = find_dist()

    dist = dist_table[-1][-1]
    diff = backtrack(directions)

    return (dist, diff)

class MatchSeqsTest(unittest.TestCase):
    def test_seq_dist(self):
        self.assertMatchDist(0, '', '')
        self.assertMatchDist(2, 'something cool', '')
        self.assertMatchDist(0, 'first', 'first')
        self.assertMatchDist(1, 'first', 'first second')
        self.assertMatchDist(1, 'fourth second', 'first second')
        self.assertMatchDist(1, 'first second third', 'second third')

    def assertMatchDist(self, dist, first, second):
        self.assertMatchDistOneWay(dist, first, second)
        self.assertMatchDistOneWay(dist, second, first)

    def assertMatchDistOneWay(self, dist, first, second):
        actualDist, actualDiff = seq_dist(first.split(), second.split())
        self.assertEqual(dist, actualDist)
        self.assertEqual(dist, self.alignment_dist(actualDiff))
        self.assertEqual(self.extract_first(actualDiff), first.split())

    def extract_first(self, diff):
        return [f for f, s in diff if f is not None]

    def alignment_dist(self, diff):
        return sum(1 for f, s in diff if f != s)

if __name__ == '__main__':
    unittest.main()


texts: Thread which executes code after Thread.sleep() and can be cancelled only if it's sleeping

texts:
I use Java8, I have a subclass of Thread called DelayedThread which wraps a Runnable and executes the Runnable after certain amount of time. It has a method called cancelOnlyIfStillSleeping() which interrupts Thread.sleep but I don't want to interrupt it once Runnable has been called because I'm afraid of interrupting Runnable which might react to the interruption in an unexpected way. The code looks like this:
class DelayedThread extends Thread {

    private final long delay;
    private final Runnable task;
    private boolean starting;

    private final Object lock = new Object();

    DelayedThread(long delay, Runnable task) {
        this.delay = delay;
        this.task = task;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }

        synchronized (lock) {
            if (isInterrupted()) {
                return;
            }
            starting = true;
        }

        task.run();
    }

    /**
     * Interrupts this thread only if it's still sleeping. Once it finished sleeping
     * the thread won't get interrupted.
     */
    void cancelOnlyIfStillSleeping() {
        synchronized (lock) {
            if (starting) {
                return;
            }
            interrupt();
        }
    }
}

Does this code look safe? Isn't there any race condition where my code doesn't work as intended? Or is there any way better to achieve this?


texts: Using Symfony forms without a database entity

texts:
I've been developing an application based on Symfony 3, and part of that application involves an import process where a user can upload csv files.  One thing that I've never been too sure about with symfony is using the forms component without a database entity to attach it too.  In the past I've typically just used an array to hold the form data, but this always felt improper.  This time I decided to try building an entity class to base the form on, even though it has no mapping to anything in the database.

This is the entity I created.  In addition to defining the fields for the form I also setup validation to ensure at least one of the fields has been populated.

class StudentImportFiles {
    /** @var File */
    private $studentList;
    /** @var File */
    private $transferList;
    /** @var File */
    private $enrollmentList;

    public static function loadValidatorMetadata(ClassMetadata $metadata){
        $metadata->addConstraint(new Callback(function(self $self, ExecutionContextInterface $context){
            if (!($self->studentList || $self->transferList || $self->enrollmentList)){
                $context->addViolation('At least one import file must be selected');
            }
        }));
    }

    public function getStudentList(){
        return $this->studentList;
    }

    public function setStudentList($studentList){
        $this->studentList = $studentList;

        return $this;
    }

    public function getTransferList(){
        return $this->transferList;
    }

    public function setTransferList($transferList){
        $this->transferList = $transferList;

        return $this;
    }

    public function getEnrollmentList(){
        return $this->enrollmentList;
    }

    public function setEnrollmentList($enrollmentList){
        $this->enrollmentList = $enrollmentList;

        return $this;
    }
}

This is the form type I created.  It simply maps to the above entity and ensures it is valid.

class StudentImportFilesType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder
            ->add('studentList', FileType::class, [
                'required' => false
            ])
            ->add('transferList', FileType::class, [
                'required' => false
            ])
            ->add('enrollmentList', FileType::class, [
                'required' => false
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver){
        $resolver->setDefaults([
            'data_class' => StudentImportFiles::class
            , 'constraints' => [
                new Valid()
            ]
        ]);
    }
}

Is this proper usage of the forms component for such a scenario?  Are there any improvements that could be made?


texts: changing root password with an ansible playbook

texts:
It is with great difficulty that I resolved to solve my problem, so I allow myself to submit here the solution.

I wanted a playbook that could replace on all hosts the root password with a string containing the last 3 digits of the IP address of the remote host.

Example:
suppose the password is my_password and my LAN is 172.1.1.0/24. I wanted to set my_password@111 on the host with IP 172.1.1.111, my_password@112 on IP 172.1.1.112, and so on.

Here is the solution i propose:

- hosts: test

  vars:
    shared_string: my_very_secure_password

  tasks:

   - debug:
       msg: "Remote IP host is {{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"

   - name: Extract last digits of remote host ip
     set_fact:
        last_digits: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] | regex_search(regexp) }}"
     vars:
        regexp: '\d{1,3}$'

   - debug:
        msg: "Last digits are {{ last_digits }}"

   - name: Compose and encrypt the password as shared_string@last_digits
     command: openssl passwd -crypt "{{ shared_string }}@{{ last_digits }}"
     register: crypted_password

   - debug:
       msg: "clear password is {{ shared_string }}@{{ last_digits }}"
   - debug:
       msg: "crypted password is {{ crypted_password.stdout }}"

   - name: Change root password
     user: name=root update_password=always password={{ crypted_password.stdout }}

what do you think, how to improve it?


texts: Backwards stepwise regression code in R (using cross-validation as criteria)

texts:
I want to write code that does backward stepwise selection using cross-validation as a criterion.

I have only started learning R a month ago and I have almost zero programming experience prior to that. Hence, I would appreciate any comments on the code.

(I understand that there are issues with the backward stepwise selection process itself.)

rm(list=ls())
library(forecast)
library(fpp)
set.seed(1)

x1<-c(1:500)*runif(20,min=0,max=200)
x2<-c(1:500)*runif(20,min=0,max=200)

library(caret)
data(credit)
score <- credit$score
log.savings <-log(credit$savings+1)
log.income <-log(credit$income+1)
log.address<- log(credit$time.address+1)
log.employed <- log(credit$time.employed+1)

##################################

#Input
full.model<- score ~ log.savings + log.income + log.address + log.employed + x1 +x2

# 1. Start with the full model
counter=1
full <- lm(full.model)
scopevars<- attr(full$terms, "predvars") # list of model predicotrs
n <- length(full$residuals);  # sample size
current_best <- full #what is the currenly the best model ? that would be our full model for now

while(T){ #process until we break the loop

  best_cv <- CV(current_best)[1] #the CV of the current_best model
  temp <- summary(current_best) #summary output of the current_best model
  p <- dim(temp$coefficients)[1]  # current model's size

  rnames <- rownames(temp$coefficients)  # list of terms in the current model

  compare <- matrix(NA,p,1) # create a matrix to store CV information
  rownames(compare) <- rnames #name the matrix

  #create a loop that drops one predictor at a time and calculates the CV of the regression when that predictor is dropped
  #put all the information into "compare"
  #drop the variable that has the lowerst CV when it is dropped.

  for (i in 2:p) {
    drop_var <- rnames[i] #variable to be deleted
    f <- formula(current_best) #current formula
    f <- as.formula(paste(f[2], "~", paste(f[3], drop_var, sep=" - "))) # modify the formula to drop the chosen variable (by subtracting it)
    new_fit <- lm(f)  # fit the modified model
    compare[i]<-CV(new_fit)[1]
  }

  remove_var <-rownames(compare)[which.min(compare)] #drop is the varibale that is associate with the lowerst CV
  update_cv <- compare[which.min(compare)]

  if(update_cv>best_cv) break #we should not continue if dropping a variable will not improve Cv

   write(paste("--- Dropping",counter, remove_var , update_cv, "\n"), file="") # output the variables we are dropping.

  f <- formula(current_best) #current formula
  f <- as.formula(paste(f[2], "~", paste(f[3], remove_var , sep=" - ")));  # modify the formula to drop the chosen variable (by subtracting it)
  current_best <- lm(f)# we now have a new best model
  counter=counter+1 #update our counter
  next
} #end the while loop
print(current_best)
CV(current_best)


texts:
I've got this fizzbuzz project I am using for a blog series, among other things. In this version, the fizzbuzz function is fed from a Fibonacci generator. I'm particularly concerned with the efficiency of the Fibonacci generator, but all scrutiny is welcomed.

Here is a link to the entire project, but below are the parts I think would be sufficient to spot trouble with how I am generating Fibonacci numbers.

-- Driver function performs following
-- (1) checks that input is proper
-- (2) creates integer list for fibonacci generator
-- (3) calculates first x in fibonnaci sequence
-- (4) generates fizzbuzz output using (3)

fizzBuzzFib :: [Text] -> Either FizzError [Text]
fizzBuzzFib str =
mapM fizzbuzz          =<<
mapM fibb              =<< -- Possible problem here
(\x -> Right [1 .. x]) =<<
convertToPInt          =<<
mustHaveOne str

fibb :: Integer -> Either FizzError Integer
fibb n = Right $ snd . foldl' fib' (1, 0) . map (toEnum . fromIntegral) $ unfoldl divs n
  where
    unfoldl f x =
      case f x of
        Nothing     -> []
        Just (u, v) -> unfoldl f v ++ [u]

    divs 0 = Nothing
    divs k = Just (uncurry (flip (,)) (k `divMod` 2))

    fib' (f, g) p
      | p = (f*(f+c*g), f^c + g^c)
      | otherwise = (f^c+g^c, g*(c*f-g))
      where
        c :: Integer -- See codebase for reasons
        c = 2


texts:
This is a take on Pebble Solitaire. The user inputs n number of games and after that inputs a strings of length 23 that contains a combinations of only 'o' (pebble) and '-' (empty space). If there are 2 adjacent pebbles and an empty space on either side, ie (oo- OR -oo), then you remove the middle pebble and you swap other two pieces with each other, ex 'oo-' will turn into '--o'.

My current approach is pretty much an exhaustive approach where it tries out every possible move and results the move set with the least number of pebbles left.

My program is working fine, in terms of output, but for some of my test cases it takes too long to find an answer (sometimes taking 18 seconds). I would like to know how I can improve the performance of my code without making it multithreaded.

package Pebble;

import java.util.Scanner;

public class PebbleSolitaire {

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        int numOfGames = Integer.parseInt(input.nextLine());

        while (numOfGames > 0){

            char[] values = input.nextLine().toCharArray();
            long startTime = System.nanoTime();
            System.out.println(solve(values));
            System.out.println("Time to finish in ms: " + (System.nanoTime() - startTime) / 1000000);
            numOfGames--;
        }
        input.close();
    }

    private static int solve(char[] game){

        if(game != null && game.length == 0){
            return -1;
        }

        int result = 0;

        for (int i = 0; i < game.length; i++){
            if(game[i] == 'o'){
                result++;
            }
        }

        //print(game);

        for (int i = 0; i < game.length; i++ ){

            char[] temp = new char[game.length];
            copyArray(temp, game);

            if (i-2 >= 0 && temp[i] == '-' && temp[i-2] == 'o' && temp[i-1] == 'o'){//move pebble forwards
                temp[i-1] = temp[i-2] = '-';
                temp[i] = 'o';
                result = Math.min(result, solve(temp));
            }

            copyArray(temp, game);

            if(i+2 < temp.length && temp[i] == '-' && temp[i+1] == 'o' && temp[i+2] == 'o'){//move pebble backwards
                temp[i+1] = temp[i+2] = '-';
                temp[i] = 'o';
                result = Math.min(result, solve(temp));
            }
        }
        return result;
    }

    private static void copyArray(char[] copy, char[] og){
        for(int x = 0; x < copy.length; x++){
            copy[x] = og[x];
        }
    }
    private static void print(char[] c){
        for(char ch: c){
            System.out.print(ch);
        }
        System.out.println();
    }
}

My sample input and output:

2
-o----ooo----o----ooo--
6
Time to finish in ms: 0
oooooooooo-ooooooooooo-
4
Time to finish in ms: 18149


texts: More efficient solution for Project Euler #2 (sum of Fibonacci numbers under 4 million)

texts:
I would like to get some feedback on my code. I am starting to program after doing a few online Python courses.

Would you be able to help me by following my track of thinking and then pinpointing where I could be more efficient? (I have seen other answers but they seem to be more complicated than they need to be, albeit shorter; but perhaps that is the point).

Question:

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

fibValue = 0
valuesList = []

a = 0
b = 1

#create list

while fibValue <= 4000000:
    fibValue = a + b
    if fibValue % 2 == 0:
        valuesList.append(fibValue)
    a = b
    b = fibValue

print (valuesList) #just so that I can see what my list looks like after fully compiled

print() #added for command line neatness

print() #added for command line neatness

newTot = 0

for i in valuesList:
    newTot += i
print (newTot)


texts:
I was trying to write code which does a validation for the below wildcards:

  '?'  ------> The question mark indicates there is zero or one of the preceding
  element. For example, colou?r matches both "color" and "colour".
  '*'  ------>   The asterisk indicates there is zero or more of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and
  so on.
  '+'  ------>  The plus sign indicates there is one or more of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on,
  but not "ac".

I know that Java does provide pattern matching with wild cards out of box, but this is more of an exercise to understand the crux by not using libraries.

static boolean matches(String pattern, String text) {
    if (text == null && pattern == null) {
        return true;
    }
    if (text == null || pattern == null) {
        return false;
    }
    if (text.equals(EMPTY_STRING) && pattern.equals(EMPTY_STRING)) {
        return true;
    }
    if (text.equals(EMPTY_STRING) || pattern.equals(EMPTY_STRING)) {
        return false;
    }
    char[] p = pattern.toCharArray();
    char[] t = text.toCharArray();
    int indexP1 = 0, indexP2 = 1, indexT = 0;
    while (true) {
        if (indexP1 == p.length && indexT == t.length){
            return true;
        } else if (indexP1 == p.length || indexT == t.length){
            return false;
        } else {
            if (indexP2 < p.length && p[indexP2] == '*'){//case: a*
                while (t[indexT] == p[indexP1]) {
                    indexT++;
                    if(indexT==t.length)break;
                }
                indexP1 = indexP1 + 2;
                indexP2 = indexP2 + 2;
            }
            else if (indexP2 < p.length && p[indexP2] == '+') {//case: a+
                if(t[indexT] != p[indexP1]){
                    return false;
                }
                while (t[indexT] == p[indexP1]) {
                    indexT++;
                    if(indexT==t.length)break;
                }
                indexP1 = indexP1 + 2;
                indexP2 = indexP2 + 2;
            }
            else if (indexP2 < p.length && p[indexP2] == '?') {//case: a?
                if (t[indexT] == p[indexP1]) {
                    indexT++;
                }
                indexP1 += 2;
                indexP2 += 2;
            } else {//case: a
                if (t[indexT] != p[indexP1]) {
                    return false;
                }
                indexP1++;
                indexP2++;
                indexT++;
            }
        }
    }
}


texts:
I have a big project called 'PyDOS', written in Python 3.4, and it's going very well. Post your answers of anything that could make it look cleaner.

import time
import os
import sys
import random
import operator

def textviewer():
   os.system('cls' if os.name == 'nt' else 'clear')
   print ("Text Viewer.")
   file_name = input("Enter a text file to view: ")
   file = open(file_name, "r")
   print ("Loading text...")
   time.sleep(4)
   os.system('cls' if os.name == 'nt' else 'clear')
   print(file.read())
   input("Press enter to close")
def edit():
    os.system('cls' if os.name == 'nt' else 'clear')
    print ("EDIT")
    print ("-------------")
    print ("Note: Naming this current document the same as a different document will replace the other document with this one.")
    filename = input("Plese enter a file name.")
    file = open(filename, "w")
    print ("FILE: " +filename+".")
    line1 = input()
    line2 = input()
    line3 = input()
    line4 = input()
    line5 = input()
    file.write(line1)
    file.write("\n")
    file.write(line2)
    file.write("\n")
    file.write(line3)
    file.write("\n")
    file.write(line4)
    file.write("\n")
    file.write(line5)
    file.close()
    print ("File successfully saved as: " +filename+"!")
    time.sleep(3)

while True:
   os.system('cls' if os.name == 'nt' else 'clear')
   print ()
   print ("PyDOS VERSION 1.5")
   shell = input("> ")
   if shell == "textviewer":
      print ("Loading Text Viewer...")
      time.sleep(3)
      textviewer()

   elif shell == "edit":
      print ("Loading edit...")
      time.sleep(3)
      edit()

   elif shell == "dir":
      print ("The drive name is A:")
      print ()
      print ("NAME:            TYPE:     MODIFIED:")
      print ("SHUTDOWN.EXE     .EXE      12/01/15 ")
      print ("EDIT.EXE         .EXE      12/01/15 ")
      print ("TEXTVIEWER.EXE   .EXE      12/01/15 ")

   elif shell == "cls":
      os.system('cls' if os.name == 'nt' else 'clear')

   elif shell == 'shutdown':
      print ("Shutting down...")
      time.sleep(3)
      break
   else:
      print(""+ shell+ " is not a reconized command or external file.")
      time.sleep(2)
      os.system('cls' if os.name == 'nt' else 'clear')


texts: Decided to learn Scala. Here's an attempt at a Cloth simulation

texts:
I have never done anything functional before. These two functions are hideous to look at. II think the first step to do is extract the inner bits out and then map over my arrays. What else can I do to make this code a bit more functional?

https://github.com/dbousamra/scalacloth/blob/master/src/cloth/Cloth.scala

Specifically:

  def verletIntegration() = {

    for (row <- grid) {
      for (p <- row) {
        if (p.stuck) p.setCurrentPos(p.getPreviousPos)

        var multiplyByTime = Tuple2(p.getForces * timestep * timestep, gravity * timestep * timestep)
        var minusPrevPos = Tuple2(p.getCurrentPos.getX - p.getPreviousPos.getX, p.getCurrentPos.getY - p.getPreviousPos.getY)
        var together = Tuple2(multiplyByTime._1 + minusPrevPos._1 , multiplyByTime._2  + minusPrevPos._2)
        p.setPreviousPos(p.getCurrentPos)
        p.setCurrentPos(new Position(p.getCurrentPos.getX + together._1, p.getCurrentPos.getY + together._2))
      }
    }
  }

  def satisfyConstraints() = {
    for (row <- grid) {
      for (p <- row) {
        if (p.stuck) p.setCurrentPos(p.getPreviousPos)
        else {
          var neighbors = p.getNeighbors
          for (constraint <- neighbors) {
            val c2 = grid(constraint.getX)(constraint.getY).getCurrentPos
            val c1 = p.getCurrentPos
            val delta = Tuple2(c2.getX - c1.getX, c2.getY - c1.getY)
            val deltaLength = math.sqrt(math.pow((c2.getX - c1.getX), 2) + math.pow((c2.getY - c1.getY),2))
            val difference = (deltaLength - 1.0f) / deltaLength
            val dtemp = Tuple2(delta._1 * 0.5f * difference, delta._2 * 0.5f * difference)
            p.setCurrentPos(new Position(c1.getX + dtemp._1.floatValue, c1.getY + dtemp._2.floatValue))
            grid(constraint.getX)(constraint.getY).setCurrentPos(new Position(c2.getX - dtemp._1.floatValue, c2.getY - dtemp._2.floatValue))
//          }

          }
        }
      }
    }
  }


texts: Calculate sum of price on distant relation

texts:
I have a booking with a method total which calculates the total price of the booking from the sum of all the prices of activities that belong to appointments. A booking has many appointments and the following seems to give the right answer, but it seems horrid.  How can I improve this?

  def total
    # TODO  shouldn't this be a db query?
    total = 0
    self.appointments.each do |appointment|
        unless appointment.activity.price.nil?
            total += appointment.activity.price.to_f
        end
    end
    total
  end


texts: Merging multiple awk commands while retaining functionality

texts:
Turned in a project a few days ago, and I needed a way to filter and format values off a file. I decided to go for a bash script since it seemed like a good option, and I came up with the following:

#!/bin/bash

amount=100

awk '{
    if($i == "data: 1"){
        getline;
        getline;
        print $2}}' sensordata.txt > temp1.txt
awk -v m=$amount 'NR<=m' temp1.txt > temp12.txt
maxval1=$(awk -v val=0 '{
    if($i>val)
        val=$i;};
    END {print val}' temp12.txt)
minval1=$(awk -v val=1024 '{
    if($i<val)
        val=$i;};
    END {print val}' temp12.txt)
awk -v max=$maxval1 -v min=$minval1 '{
    if($i!=max && $i!=min)
        print $0}' temp12.txt > data1.txt
avgval1=$(awk -v avg=0 '{
    avg+=$i;};
    END {
        avg/=NR;
        print avg}' data1.txt)
rm temp1.txt
rm temp12.txt

This is used 3 times for different files as I need to filter it 3 times.

The original file contains several values I need to filter, all of which have a "title" ("data: 1"), and all lines are separated by a "---". It'd look something like this:

data: 1
<--->
data: 111
<--->
data: 2
<--->
data: 222

and so on.

My script copies all values 2 lines below the "title" into another file, moves a certain amount of lines to another file, finds the maximum and minimum value, then moves all values different to max and min to a last file, from which the average of all values is calculated. Then it's graphed using GNUPLOT.

I was wondering if there was a better way of achieving this, as I quite clearly abused the AWK command, and everything seems quite messy from my perspective, specially because I'm constantly moving values from the original file into a new one.


texts:
I have written some code in Java that consists of two classes. I have tried my best and I want you to tell me if I can improve and how good this is.

Also, how important is OOP? Java is an object oriented language, so I have also tried my best to use it that way (although I don't know whether I have succeeded or not).

MainClass

import java.util.Scanner;
class MainClass{
public static void main(String args[]){
    RandomDice dice = new RandomDice();
    Scanner scan = new Scanner(System.in);

    System.out.print("Please enter the number of times you want to roll the dice:");
    int arg0 = scan.nextInt();

    dice.roll(arg0);
    }
}

RandomDice

/*This program will help you to imitate the randomness of a dice roll,
 *and to represent the frequency of each face appearing in a tabular form.
 */
import java.util.Random;

public class RandomDice{
private int diceRoll;
Random rand = new Random();

    /// the method below takes an argument arg0 which indicates the amount of times the         dice has to be rolled.
    public void roll(int arg0){
    diceRoll = arg0;
    int ObservationArray[] = {0,0,0,0,0,0};
    ObserveRandom(diceRoll,ObservationArray);
    DisplayResult(ObservationArray);
}

///this method creates random numbers from 0 to 5 and respectively stores them in the     array index stimulating a dice being rolled.
public void ObserveRandom(int arg1,int ObservationArray[]){
for(int counter=0;counter<arg1;counter++){
    ++ObservationArray[rand.nextInt(6)];
    }
}
///this method displays the data collected in a tabular form.
public void DisplayResult(int arg1[]){
    System.out.println("face\tfrequency");
    for(int counter=0;counter<arg1.length;counter++){
        System.out.println(1+counter+"\t"+arg1[counter]);
        }
    }
}


texts: NetBuffer - buffer specialized for socket read / write

texts:
This class is for fast and small footprint buffering made specially for network I/O. It is similar to so-called circular buffers, but is not circular.

#ifndef _IO_BUFFER_H
#define _IO_BUFFER_H

#include <cstdint>
#include <cstring>
#include <cstdio>

namespace net{

template<size_t CAPACITY>
class IOBuffer{
public:
    using size_type = uint16_t;

private:
    size_type   head_   = 0;
    size_type   tail_   = 0;
    char        buffer_[CAPACITY];

public:
    void clear(){
        head_ = 0;
        tail_ = 0;
    }

    constexpr
    static size_t max_size(){
        return CAPACITY;
    }

    // ==================================

    const char *data() const{
        return & buffer_[head_];
    }

    char *dataTail(){
        return & buffer_[tail_];
    }

    size_t size() const{
        return tail_ - head_;
    }

    size_t capacity() const{
        return CAPACITY - tail_;
    }

    // ==================================

    bool push(const char *p){
        return p ? push(strlen(p), p) : false;
    }

    bool push(size_t const len, const void *ptr = nullptr){
        if (len == 0)
            return false;

        if (capacity() < len)
            return false;

        if (ptr)
            memmove(&buffer_[tail_], ptr, len);

        tail_ = (size_type) (tail_ + len);

        return true;
    }

    bool pop(size_t const len){
        if (len == 0)
            return false;

        auto const available = size();

        if (available < len)
            return false;

        if (available == len){
            clear();
            return true;
        }

        head_ = (size_type) (head_ + len);

        return true;
    }

    // ==================================

    void print() const{
        printf("h: %3u | t: %3u | ad: %3zu | ac: %3zu | %.*s\n",
                head_, tail_,
                size(), capacity(),
                (int) size(), buffer_ );
    }
};

} // namespace

#endif

Usual usage include several socket read() until protocol data is collected, then several write() until response is sent back.

Reads and writes will not be mixed, but for the moment this is responsibility of the caller.

print is debug method, non intended to be called.

int main(){
    using Buffer = net::IOBuffer<10>;

    Buffer b;
    b.print();

    b.push("aaa");
    b.print();

    b.push("bbb");
    b.print();

    b.push("ccc");
    b.print();

    b.push("xxx");
    b.print();

    b.push("d");
    b.print();

    b.push("xxx");
    b.print();

    b.pop(3);
    b.print();

    b.pop(3);
    b.print();

    b.pop(b.size()); // same as b.clear()
    b.print();
}


texts:
This is how I read the keyboard in my game:

    @Override
public void keyPressed(KeyEvent key) {
    keypressed=true;

    if (key.getKeyCode() == KeyEvent.VK_UP) {
        keyup=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_DOWN) {
        keydown=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_ENTER) {
        keyenter=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_ESCAPE) {
        keyesc=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_W) {
        keyw=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_S) {
        keys=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_A) {
        keya=true;
    }

    if (key.getKeyCode() == KeyEvent.VK_D) {
        keyd=true;
    }
}

Is there a more efficient, simpler, or neater way to do this?


texts: Functional organisation of JavaScript functions

texts:
In one of the web apps I contribute to, the main.js file has multiple interacting "objects". Unfortunately, I'm so bad at OOP in JavaScript, despite studying other questions, that I just have a bunch of functions divided by a comment block as follows for the editor "object":

//*****************
// Setup the editor
//*****************
//Functions for interaction with editor
var aceRange = ace.require('ace/range').Range;
var editor = null;
var marker = null;
var gui_updating = false;

function removeMarker() {
    if (marker != null) {
        editor.getSession().removeMarker(marker);
        marker = null;
    }
}

function annotateLine(d) { //Called on mouseover in graph
    removeMarker();
    marker = editor.getSession()
        .addMarker(new aceRange(d.line, 0, d.line, 10),
            'highlight', 'fullLine', true);

    editor.getSession().setAnnotations([{row: d.line, type: 'info'}]);
}

function clearAnnotation(d) { //Called on mouseout in graph
    removeMarker();
    editor.getSession().clearAnnotations();
}

The initialization of the editor "object" and it's bonding to events is called later, but isn't included here as I don't think it will help.

This seems bad, but I can't figure out how to improve it other than dividing the objects into separate files. I also think it's important to divide the code functionally, but I'm not sure how to do that. Should I wrap the whole thing up in a function?

Like so:

var app_editor = function(ace, ace_editor){
    self.aceRange = ace.require('ace/range').Range;
    self.editor = ace_editor;
    self.marker = null;

    removeMarker = function() {
        if (self.marker != null) {
            self.editor.getSession().removeMarker(self.marker);
            self.marker = null;
        }
    }

    annotateLine = function(d) { //Called on mouseover in graph
        removeMarker();
        self.marker = self.editor.getSession()
            .addMarker(new self.aceRange(d.line, 0, d.line, 10),
                'highlight', 'fullLine', true);

        self.editor.getSession().setAnnotations([{row: d.line, type: 'info'}]);
    }

    clearAnnotation = function(d) { //Called on mouseout in graph
        removeMarker();
        self.editor.getSession().clearAnnotations();
    }
};

Should I be using prototypes as well, even if there will only be one function ever? I understand what a closure is, but I still don't know how to apply it and if it's appropriate here. Alternatively, since my code has gotten so big, should I look into using a library?

This project is still in its early stages, so I'm open to radical changes.


texts:
Could someone review this PHP code to see if my pages are coded safely to not allow common attacks (SQL injection, XSS, etc.)? I would be thankful, of course, for anyone to point out other problems in my code as well.

// getpaste.php
<?php
$db_conn_config = parse_ini_file('../private/db_conn.ini');
$servername = $db_conn_config['servername'];
$username = $db_conn_config['username'];
$password = $db_conn_config['password'];
$dbname = $db_conn_config['dbname'];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// Prepare sql and bind parameters.
$stmt = $conn->prepare("SELECT key_salt, aes_iv, cipher_text, mac_tag FROM pastes WHERE paste_id =:pasteid");
$stmt->bindParam(':pasteid', $_POST["pasteID"]);
$stmt->execute();

// Only output results if 1 row is found.
if ($stmt->rowCount() == 1)
{
    $row = $stmt->fetch();
    echo $row['key_salt'];
    echo "|";
    echo $row['aes_iv'];
    echo "|";
    echo $row['cipher_text'];
    echo "|";
    echo $row['mac_tag'];
}

$conn = null;
?>

// savepaste.php
<?php
$db_conn_config = parse_ini_file('../private/db_conn.ini');
$servername = $db_conn_config['servername'];
$username = $db_conn_config['username'];
$password = $db_conn_config['password'];
$dbname = $db_conn_config['dbname'];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// Make sure that the values written to the database only include valid base64 characters.
// These are letters (upper and lower case), numbers, and /+=
$pattern = "@^[a-zA-Z0-9/+=]+$@";
if ((!preg_match($pattern, $_POST["pasteID"])) or
    (!preg_match($pattern, $_POST["keySalt"])) or
    (!preg_match($pattern, $_POST["aesIV"])) or
    (!preg_match($pattern, $_POST["cipherText"])) or
    (!preg_match($pattern, $_POST["macTag"])))
{
    echo "Invalid input characters.";
    exit(1);
}

// Depending on action variable, either do an insert or update.
if ($_POST["action"] == "insert")
{
    $pre_stmt = "INSERT INTO pastes VALUES (:pasteid, :keysalt, :aesiv, :ciphertext, :mactag)";
}
else if ($_POST["action"] == "update")
{
    $pre_stmt = "UPDATE pastes SET key_salt=:keysalt,aes_iv=:aesiv,cipher_text=:ciphertext,mac_tag=:mactag WHERE paste_id=:pasteid";
}
else
{
    echo "Invalid form action.";
    exit(1);
}

// Prepare sql and bind parameters.
$stmt = $conn->prepare($pre_stmt);
$stmt->bindParam(':pasteid', $_POST["pasteID"]);
$stmt->bindParam(':keysalt', $_POST["keySalt"]);
$stmt->bindParam(':aesiv', $_POST["aesIV"]);
$stmt->bindParam(':ciphertext', $_POST["cipherText"]);
$stmt->bindParam(':mactag', $_POST["macTag"]);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

$conn = null;
?>

// deletepaste.php
<?php
$db_conn_config = parse_ini_file('../private/db_conn.ini');
$servername = $db_conn_config['servername'];
$username = $db_conn_config['username'];
$password = $db_conn_config['password'];
$dbname = $db_conn_config['dbname'];
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// Prepare sql and bind parameters.
$stmt = $conn->prepare("DELETE FROM pastes WHERE paste_id = :pasteid");
$stmt->bindParam(':pasteid', $_POST["pasteID"]);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

$conn = null;
?>


texts:
I have a class called Task that contain a member boolean variable Completed.

I created a list of Task objects in a variable called Tasks.

I have the following code, which sorts the objects depending on whether the Task is completed. (I want the incompleted tasks to be in the list first)

private List<Task> GetSortedTask(List<Task> tasks)
{
    List<Task> completedTaskList = new List<Task>();
    List<Task> incompleteTaskList = new List<Task>();

    for (int i = 0; i < tasks.Count; i++)
    {
        HelperObject T = task[i].getHelperObject();

        if (T != null && T.Completed)
            completedTaskList.Add(tasks[i]);
        else
            incompletetaskList.Add(tasks[i]);
    }

    //merge the two lists together
    imcompleteTaskList.AddRange(completedTaskList);

    return incompleteTaskList;
}

Is there a way to do this without creating so many lists? Thanks in advance

EDIT: Made my question a bit more specific since orderBy seems to be the correct answer, however my problem may be a bit more complicated than that.


texts:
I'm trying to implement the Pollard p - 1 algorithm seen here, in Java.
It has a C implementation here. I am using it for numbers without any smaller factors so trial factorisation isn't needed.  My implementation can factor numbers such as 15236506168104630133 but it takes around ten minutes. I also would like it to factor number of up to 30 digits with it. Is there any improvements I can make?

public static void factorise(BigInteger number){

    BigInteger b = BigInteger.valueOf(10);
    //b!
    BigInteger k = Utils.factorial(b);

    while(true){

        //random number a from number 0 to n-2
        BigInteger a = Utils.generateRandomNumber(number).add(BigInteger.valueOf(-1));

        BigInteger tmp = a.modPow(k, number);
        //a^k - 1 (mod n)
        tmp.add(BigInteger.valueOf(-1));
        //gcd(a^k - 1 (mod n), number);
        BigInteger gcd = tmp.gcd(number);

        if(gcd.compareTo(BigInteger.ONE) > 0){

            if(gcd.isProbablePrime(100)){
                System.out.println("Factor:d " + gcd);

                number = number.divide(gcd);

            }

            if(number.compareTo(BigInteger.ONE) == 0){
               System.out.println("done");
                return;
            }

            if(number.isProbablePrime(10)){
                 System.out.println("Factor: " + number);
                 return;
            }

        }

    }

}

public static BigInteger generateRandomNumber(BigInteger number){

    BigInteger random;
    do {
        random = new BigInteger(number.bitLength(), new SecureRandom());
    } while (random.compareTo(number) >= 0);

    return random;

}

public static BigInteger factorial(BigInteger number){

    BigInteger mul = number.add(BigInteger.valueOf(-1));

    while(mul.compareTo(BigInteger.valueOf(1)) != 0){

        number = number.multiply(mul);
        mul = mul.add(BigInteger.valueOf(-1));

    }

    return number;
}


texts:
This is my attempt at the Problem Euler #4 in Haskell ("Find the largest palindrome made from the product of two 3-digit numbers.")

import Data.List

isPalindrome :: Show a => a -> Bool
isPalindrome n = l == reverse l
  where l = show n

maxPalindrome :: (Integral a, Show a) => a
maxPalindrome = maximum $ head . transpose $ allPalindrome <$> [999, 998 .. 1]
  where allPalindrome x = filter (isPalindrome) $ (x *) <$> [999, 998 .. x]

To my surprise I didn't see any such optimisation in the snippets I found (the head . transpose is there to only consider the highest of each pairs), which surprised me. However this is still running about 0.5 seconds which I find still slow?

Is there a way to make it run faster? I am aware of Project Euler #4 in Haskell however, my question is not about the algorithm I use but about its implementation.

Do you have any other recommendation about my code?

Thank you very much in advance


texts: Converting timedate timezones with Joda-Time

texts:
I've been struggling to get to grips with Joda-Time, but feel that I've finnaly managed to get a grip on some of the functionality that I need.

I have written a function that will convert a DateTime from one timezone to another.  I've not done any unit testing on it (but have done my own testing), but would appreciate comments on if it could be improved.  The code is in native Java.

import org.joda.time.*;
import org.joda.time.format.*;
public class testing {

    /**
     * @param args
     */
    public static void main(String[] args) {

public string ConvertTimeZones(String sFromTimeZone, String sToTimeZone, String sFromDateTime){
        DateTimeZone oFromZone       = DateTimeZone.forID(sFromTimeZone);
        DateTimeZone oToZone         = DateTimeZone.forID(sToTimeZone);

        DateTime oDateTime           = new DateTime(sFromDateTime);
        DateTime oFromDateTime       = oDateTime.withZoneRetainFields(oFromZone);

        DateTime oToDateTime         = new DateTime(oFromDateTime).withZone(oToZone);

        DateTimeFormatter oFormatter = new DateTimeFormat.forPattern("yyyy-MM-dd'T'H:mm:ss.SSSZ");
        DateTimeFormatter2           = new DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss");

        DateTime oNewDate            = oFormatter.withOffsetParsed().parseDateTime(oToDateTime.toString());

        return oFormatter2.withZone(oToZone).print(oNewDate.getMillis());
   }
}
}

The arguments:

sFromTimeZone = UTC
sToTimeZone = Europe/London
sFromDateTime = 2012-05-08 18:00:00

should produce a return of

2012-05-08 19:00:00


texts: Open a file selection window to top-most position from jupyter notebook

texts:
Background

I came up with this solution to a question that I posted on stackoverflow. It uses Tkinter to create a file select dialog window and raise it to the topmost position from jupyter notebook.

Questions

1) Is there some kind of built in or canonical way to do this in jupyter notebook that I've missed in my searches?

2) Is there any redundancy?

from tkinter import*
# Create Tk root
root = Tk()
# Hide the main window
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)

from tkinter import filedialog
infiles = filedialog.askopenfilename(multiple=True)

%gui tk


texts: Modeling a pair of dice using composition in C++

texts:
I've written a program all by myself, but I just want to make sure I did it right and if anybody has any suggestions on improving it in any way.

Define and implement the Die class depicted by the following UML diagram to create an ADT for one die (singular of dice) with faces showing values between 1 and the numberOfFaces on the die. Define a two-parameter constructor with defaults of 6 faces and 1 for face value. Define and implement a roll() method to simulate the rolling of the die by generating a random number between 1 and numberOfFaces and storing that number in faceValue. Provide an accessor to return the die’s face value and a print() method to print the die’s face value.
Use composition to design a PairOfDice class, composed of two six-sided Die objects. Create a driver program with a main() function to rolls a PairDice object 1000 times, counting then displaying the number of snake eyes (i.e. two ones) and box cars (i.e. two sixes) that occur.

die.h

#ifndef DIE_H
#define DIE_H

class die {

private:
    int numberOfFaces;
    int faceValue;
public:
    die();
    die(int, int);
    int roll();
    void print();
};
#endif

die.cpp

#include "die.h"
#include<iostream>
#include<ctime>
#include<random>
using namespace std;

die::die()
{
    numberOfFaces=6;
    faceValue=1;
}

die::die(int numOfFaces, int faceVal)
{
    numberOfFaces=numOfFaces;
    faceValue=faceVal;
}

int die::roll()
{
    faceValue=rand()%numberOfFaces;
    return faceValue;
}

void die::print()
{
    cout << faceValue << endl;
}

pairOfDice.h

#include "die.h"
#ifndef PAIROFDICE_H
#define PAIROFDICE_H

class pairOfDice :
    public die
{
private:
    die die1;
    die die2;
    int value1;
    int value2;
    int total;
public:
    pairOfDice();
    int roll();
};

#endif

pairOfDice.cpp

#include "pairOfDice.h"

pairOfDice::pairOfDice()
    :die(6,1)
{
    value1=1;
    value2=1;
    total=value1+value2;
}

int pairOfDice::roll()
{
    value1=die::roll();
    value2=die::roll();
    total=value1+value2;
    return total;
}

main.cpp

#include"pairOfDice.h"
#include<iostream>
using namespace std;

int main()
{
    int rolls=0, total=0, snakeEyes=0, boxCars=0;
    pairOfDice dice;

    while(rolls<1000)
    {
        total = dice.roll();

        if(total==2)
            snakeEyes++;
        else if(total==6)
            boxCars++;
        else
            rolls++;
    }

    cout << rolls << " " << snakeEyes << " " << boxCars << endl;
    system("pause");
    return 0;
}


texts:
I ran into the code below today, and my gut instinct tells me this is an expensive way to do a null check. The point the author was making was that if you changed the name of the object then you don't need to change the value of the string being thrown in the exception.

The proposed use would be:

string cantBeNull=...;
Guard.IsNotNull(cantBeNull);
//instead of
if(cantBeNull == null) throw new ArgumentNullException("cantBeNull");

So Is this an acceptable way of checking for null? Is this overly expensive just to save you from not having the change the value passed to the exception?

Code in question:

public static void IsNotNull<T>(Expression<Func<T>> expression) where T : class
{
    if (expression == null)
        throw new ArgumentNullException("expression");

    var value = expression.Compile()();
    var param = (MemberExpression)expression.Body;
    var paramName = param.Member.Name;

    if (value != null)
        return;

    throw new ArgumentNullException(paramName);
}


texts:
I am trying to learn how to write proper code in python, and stumbled upon the following problem.

  Bob is given a set of building blocks b, and a number n of towers
  to build. Since we are in communist land the towers should have as
  equal of an height as possible. The catch is that you are only given
  a maximum of 300 seconds to build the towers. The goal is to minimize the std of
  the tower height.

Say you are given the following vector

bricks = [8     8     8     6     6     4     4     4     4     3     3     2]

and asked to build 5 towers. One output to the problem can be

 8     4     0
 8     4     0
 8     4     0
 6     4     2
 6     3     3

Which has an std of std = ([12-12]^2+[12-12]^2+...+[12-12]^2)^1/2=0. for 3 towers the output should be

 8     4     4     4
 8     6     3     3
 8     6     4     2

Which again is optimal. Note however I am not asking for an optimal solution..
So this is similar to the knapsack problem. But here the goal is not to fill each knapsack to the brim, but rather to have each knapsack have as close weight as possible.

I came up with two possible codes

def TowerGreed(bricks,nTower):

    bricks.sort(reverse=True)
    lengthBricks = len(bricks)

    if lengthBricks > nTower:
        Tower = [[] for i in range(0,nTower)]
        for i in range(0,lengthBricks):
            if i < nTower:
                Tower[i].append(bricks[i])
            elif i == nTower:
                Height = bricks[0:nTower]
                Tower[i-1].append(bricks[i])
                Height[nTower-1] = bricks[i] + Height[nTower-1]
            else:
                lowest = Height.index(min(Height))
                Tower[lowest].append(bricks[i])
                Height[lowest] = bricks[i] + Height[lowest]

    return Tower

This is a standard Greed algorithm. It first sort the elements, then it adds one element to each tower. Then it starts checking which tower is the smallest. The smallest tower is given the next piece.

A modified version of the code above, is given below

def towerGreedImproved(bricks,numberTowers):

    # First we sort the number of bricks from greatest to smallest
    bricks.sort(reverse = True)

    # Only runs the algorithm if we have more bricks than towers to build
    if len(bricks) >= numberTowers:
        Towers = [[] for i in range(0,numberTowers)] #Empty vector [[],[],...]
        Height = [0] * numberTowers # Zero vector [0,0,...]
        avgHeight = sum(bricks)/numberTowers

        """ Loops through each tower, adds elements until that tower is just
            bellow the average tower height """
        for j in range(0,numberTowers):
            while Height[0] + bricks[0] < avgHeight:
                Towers[j].append(bricks[0])
                Height[j] = bricks[0] + Height[j]
                del bricks[0]; #Deletes used bricks

        for n in bricks:
            lowest = Height.index(min(Height))
            Towers[lowest].append(n)
            Height[lowest] = n + Height[lowest]

    print(Towers)
    return Towers

Here we also start by sorting the bricks, but the difference is we build one tower at a time. We stop building before we reach the average towerheight. This average is given as the sum of the bricks divided by the number of towers being built.

and third option was to randomize the input. The code above is somewhat slow for large vectors. To test my code, I tried the following three vectors. 2 towers, 3 towers, and finnaly 23 towers. Being more familiar with MATLAB i wrote the following code snippet. However I am not quite sure how to impliment it into python, nor if it provides any improvement.

Being a beginner in writing proper code, I have  a couple of questions

Which improvements can I make to my coding style?
People talked about dynamic solutions to this problem. Are there better algorithms for this problem?
How can I determine which algorithm is best suited for a given dataset?


texts:
I'm running into a problem with my code in a ASP.NET MVC application. Maybe it's not a problem and I'm just being paranoid, but it seems like a problem to me (might be because I've just read the book Clean Code).

I am using the repository-pattern with the unit of work-pattern to abstract the data access. In between my controllers and the repositories I have the service-layer which handles my business logic.

Now my problem is: whenever I have a bigger controller with more functionality it gets cluttered up with service declarations. Here is a little example of what one of my controllers might look like:

public class ForumController
{
    private readonly ForumAnswerService _answerService;
    private readonly ForumThreadService _threadService;
    private readonly ReputationService _repService;
    private readonly IUnitOfWork _unitOfWork;

    public ForumController()
    {
        _unitOfWork = new EFContextUnitOfWork(new MyContext());
        _threadService = new ForumThreadService(new Repository<ForumThread>(_unitOfWork));
        _answerService = new ForumAnswerService(new Repository<ForumAnswer>(_unitOfWork));
        _repService = new ReputationService(new ReputationRepository(_unitOfWork));
    }

    /* more stuff which uses the services above.. */

    protected override void Dispose(bool disposing)
    {
        if (_unitOfWork != null)
        {
            _unitOfWork.Dispose();
        }
        base.Dispose(disposing);
    }
}

This does not seem so bad right now but I had controllers with even more services and with growing functionality I think the list of services might grow even bigger and it does not seem clean to me.

Here are some ideas I have to tackle the problem:

Only initialize services when I actually need them (i.e. in the methods)

that will reduce the number of class variables but I think it might clutter up the methods and make them big and ugly

Combine multiple services

maybe I just have too many small services and need to combine them, for example combine ForumThreadService and ForumAnswerService to a single ForumService
I don't like that though because of SRP and stuff
that would just move the clutter to the services because I would have to pass multiple repositories to the service

Is that maybe a case where a DI framework would come in handy? Never used one and I only did constructor injection so I don't know..
Nope, that's it. Only got those 3 ideas..

I hope my problem is clear and you guys can point me into the right direction.


texts: Preforming some async operations with Rx.js

texts:
I tried to come up with a good challenge to learn some Rx.js programming and I came up with this chain of operations below. As well as a bit of code that works and does these things.

Take github username
Create folder based on username (/repos-${user})
Get all repos for username (https://api.github.com/users/${user}/repos)
Get the hash of the repo data
Create file where name is hash and content is repo

I'm looking for insights and optimizations, shortcuts, etc, to make this better.

Here's the code.

import { join } from 'path'
import axios from 'axios'
import Rx from 'rx'
import Promise from 'bluebird'
import crypto from 'crypto'
import fs from 'fs-extra'
import Debug from 'debug'

let debug = Debug('github-repos')

Promise.promisifyAll(fs)

let {
  ensureDirAsync,
  outputJsonAsync } = fs

function getRepos (user) {
  let theUrl = `https://api.github.com/users/${user}/repos`
  return axios.get(theUrl)
  .then(result => {
    debug(`got results back for ${user}`)
    return result.data
  })
}

function getHash (json) {
  let text = JSON.stringify(json)
  return crypto.createHash('md5').update(text).digest('hex')
}

function createDir (user) {
  return ensureDirAsync(join(__dirname, `/repos-${user}`))
}

function createFile (user, hash, data) {
  let file = join(__dirname, `/repos-${user}/${hash}.json`)
  return outputJsonAsync(file, data).then(x => file)
}

let ghUser$ = Rx.Observable.from(['reggi', 'jackofseattle', 'nolanlawson'])

let ensureUser$ = ghUser$
  .do((u) => debug(`Creating directory for: ${u}`))
  .flatMap(u => createDir(u))

let getRepos$ = ghUser$
  .do((u) => debug(`fetching user repos for: ${u}`))
  .flatMap(u => getRepos(u))

let repos$ = getRepos$
  .flatMap(repos => repos.map(repo => ({hash: getHash(repo), repo})))  // create hash for each

let fileWriter$ = repos$
  .map(repo => ({user: repo.repo.owner.login, hash: repo.hash, repo: repo.repo}))
  .flatMap(({user, hash, repo}) => {
    return createFile(user, hash, repo)
  })
  .do((file) => debug(`wrote a new repo to json ${file}`))
  .toArray()

let reposSubscription = fileWriter$.subscribe(
  function (x) {
    debug('subscription')
  },
  function (err) {
     console.log('Error: %s', err)
  },
  function (e) {
     debug('Completed')
  });


texts:
I have implemented three stacks in a single array in Java. Any advice on object oriented design, coding structure, logical part or any sort of advice would be appreciated.

public class ThreeStack {
    private int[] stack;

    private int first, last, mid;
    private final int midPosition;

    public ThreeStack(int size) {
        stack = new int[size];
        first = -1; last = size; mid = (first + last) >> 1;
        midPosition = mid;
    }

    //push
    public boolean pushFirstStack(final int val) {
        if (first + 1 < midPosition) {
            stack[++first] = val;
            return true;
        } else {
            return false;
        }
    }

    public boolean pushSecondStack(final int val) {
        if (mid + 1 < last) {
            stack[++mid] = val;
            return true;
        } else {
            return false;
        }
    }

    public boolean pushThirdStack(final int val) {
        if (last - 1 > mid) {
            stack[--last] = val;
            return true;
        } else {
            return false;
        }
    }

    //pop
    public int popFirstStack() {
        if (first < 0) {
            return Integer.MIN_VALUE;
        } else {
            int val = stack[first];
            stack[first--] = 0;
            return val;
        }
    }

    public int popSecondStack() {
        if (mid < midPosition) {
            return Integer.MIN_VALUE;
        } else {
            int val = stack[mid];
            stack[mid--] = 0;
            return val;
        }
    }

    public int popThirdStack() {
        if (last >= stack.length) {
            return Integer.MIN_VALUE;
        } else {
            int val = stack[last];
            stack[last++] = 0;
            return val;
        }
    }

    //size
    public int firstStackSize() {
        return mid - midPosition;
    }

    public int secondStackSize() {
        return last - mid;
    }

    public int lastStackSize() {
        return secondStackSize();
    }

    public void printStack() {
        for (int i = 0; i < stack.length; i++) {
            System.out.print(stack[i]);
            System.out.print((i == first || i == mid || i == last) ? "*": "");
            System.out.print(" ");
        }
        System.out.println();
    }
}

Main Method

public class MainClass {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ThreeStack stack = new ThreeStack(12);

        while (true) {
            stack.printStack();
            menu();
            int c = in.nextInt();
            switch (c) {
                case 1:
                    stack.pushFirstStack(in.nextInt());
                    break;
                case 2:
                    stack.pushSecondStack(in.nextInt());
                    break;
                case 3:
                    stack.pushThirdStack(in.nextInt());
                    break;
                case 4:
                    printPopVal(stack.popFirstStack());
                    break;
                case 5:
                    printPopVal(stack.popSecondStack());
                    break;
                case 6:
                    printPopVal(stack.popThirdStack());
                    break;
            }
        }

    }

    static void menu() {
        System.out.println("+------------------------------+");
        System.out.println("1 -> push first stack");
        System.out.println("2 -> push second stack");
        System.out.println("3 -> push third stack");
        System.out.println("4 -> pop first stack");
        System.out.println("5 -> pop second stack");
        System.out.println("6 -> pop third stack");
        System.out.println("+------------------------------+");
    }

    static void printPopVal(int val) {
        System.out.println("Pop : " + val);
    }
}


texts: Computing nth Tribonacci number at compile time using C++ template metaprogramming facilities

texts:
I have this small C++ program for computing the \$n\$th Tribonacci number at compile-time. My main concern is: is it possible to get rid of the statickeyword (I had to use it in order to silence my compiler (VS 2019))?
Code
#include <cstdint>
#include <iostream>

template<uint64_t N>
struct tribonacci {
    constexpr static uint64_t value = tribonacci<N - 1>::value +
                                      tribonacci<N - 2>::value +
                                      tribonacci<N - 3>::value;
};

template<>
struct tribonacci<0> {
    constexpr static uint64_t value = 0;
};

template<>
struct tribonacci<1> {
    constexpr static uint64_t value = 0;
};

template<>
struct tribonacci<2> {
    constexpr static uint64_t value = 1;
};

int main() {
    std::cout << tribonacci<6>::value;
    return 0;
}


texts: Meta-class to allow inspection of all __slots__of a class

texts:
If classes provide __slots__ and at the same time inherit from another class also providing __slots__, there is no straightforward way to access and list each and every slot of the class. Especially when you consider chaining of inheritance.

I've written this meta-class that adds the __all_slots__ property, listing all unique slots:

class MetaSlotMachine(type):
    """Meta-class that adds the attribute `__all_slots__` to a class.

    `__all_slots__`  is a set that contains all unique slots of a class,
    including the ones that are inherited from parents.

    """
    def __init__(cls, name, bases, dictionary):
        super(MetaSlotMachine, cls).__init__(name, bases, dictionary)
        slots_iterator = (getattr(c, '__slots__', ()) for c in cls.__mro__)
        # `__slots__` might only be a single string,
        # so we need to put the strings into a tuple.
        # `basestring` becomes just `str` in Python 3
        slots_converted = ((slots,) if isinstance(slots, basestring) else slots
                                    for slots in slots_iterator)
        cls.__all_slots__ = set()
        cls.__all_slots__.update(*slots_converted)

Let's consider classes that inherit slots, like the following:

class HasSlots1(object):
    __metaclass__ = MetaSlotMachine   # Python 2 Syntax
    __slots__ = ['x', 'y']

class HasSlots2(HasSlots1):
    __slots__ = 'zz'

class HasSlots3(HasSlots2):
    __slots__ = ()

If we create and instance via

myslots = HasSlots3()

and ask for

myslots.__slots__

Python will return the empty tuple:

 ()

However, now we can get hold of all slots via

myslots.__all_slots__

which returns all inherited slots:

{'y', 'x', 'zz'}

Is there anything flawed with the design of the meta-class? What about listing all slots based on the __mro__ in _get_all_slots function?

EDIT: Revised version with gathering slots within the init function. Moreover, special care is taken about __slots__ that only consist of a single string, like __slots__ = '__weakref__'.


texts:
In answering password cracker in c with multithreading, I ended up writing a sample in C, which is not my forte.

Is there anything that I missed which should have been included in a responsible sample (read: likely to be copied and pasted into production code)?

// compile with `gcc counter.c -o counter -lpthread -Wall -std=gnu99`
#include <pthread.h>
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

#define SEARCH_THREAD_COUNT (10)
#define SEARCH_VALUE (21325)
#define SEARCH_MAX (INT_MAX)

typedef struct {
    int start;
    int end;
    int search;

    bool* shouldStop;
    int* answer;
    pthread_mutex_t* answerMutex;
    pthread_cond_t* answerFound;

    pthread_t thisThread;
} find_worker_init;

void* find_value(void* vpInitInfo) {
    find_worker_init* pUnitOfWork = (find_worker_init*)vpInitInfo;

    int cValue = pUnitOfWork->start;
    while (!(*(pUnitOfWork->shouldStop))) {
        if (cValue == pUnitOfWork->search) {
            printf("found value\n");

            // found the search value
            pthread_mutex_lock(pUnitOfWork->answerMutex);
            if (!(*(pUnitOfWork->shouldStop))) {
                *(pUnitOfWork->shouldStop) = true;
                *(pUnitOfWork->answer) = cValue;

                pthread_cond_broadcast(pUnitOfWork->answerFound);
            }
            pthread_mutex_unlock(pUnitOfWork->answerMutex);
            return NULL;
        }

        cValue++;
        if (cValue == pUnitOfWork->end) {
            // we exhausted our search space, end.
            printf("exhausted\n");
            return NULL;
        }
    }

    // we were usurped by another thread
    printf("usurped\n");
    return NULL;
}

int main( int argc, const char* argv[] ) {
    pthread_mutex_t answerMutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t answerFound = PTHREAD_COND_INITIALIZER;
    bool shouldStop = false;
    int answer = -1;

    // initialize thread jobs
    find_worker_init startInfo[SEARCH_THREAD_COUNT];
    int current_search_start = 0;
    int search_unit = SEARCH_MAX / SEARCH_THREAD_COUNT;
    for (int i = 0; i < SEARCH_THREAD_COUNT; i++) {
        startInfo[i].start = current_search_start;

        // set the search space for this thread to be either the standard
        // search space, or for the last thread, whatever is remaining
        // (this is to prevent integer-division from skipping a portion
        // at the end)
        int current_size = (i == SEARCH_THREAD_COUNT - 1)
            ? (SEARCH_MAX - current_search_start)
            : search_unit;

        startInfo[i].end = current_search_start + current_size;
        startInfo[i].search = SEARCH_VALUE;

        startInfo[i].shouldStop = &shouldStop;
        startInfo[i].answer = &answer;
        startInfo[i].answerMutex = &answerMutex;
        startInfo[i].answerFound = &answerFound;
    }

    // start threads
    for (int i = 0; i < SEARCH_THREAD_COUNT; i++) {
        if (pthread_create(&(startInfo[i].thisThread), NULL, find_value,
            &(startInfo[i])))
        {
            fprintf(stderr, "Error creating thread\n");
            return 1;
        }
    }

    // wait for answer to be found
    pthread_mutex_lock(&answerMutex);
    while (!shouldStop) {
        pthread_cond_wait(&answerFound, &answerMutex);
    }
    printf("signaled\n");

    // join
    for (int i = 0; i < SEARCH_THREAD_COUNT; i++) {
        if (pthread_join(startInfo[i].thisThread, NULL)) {
            fprintf(stderr, "Error joining thread\n");
            return 1;
        }
    }

    // answer
    printf("answer: %d\n", answer);

    pthread_mutex_unlock(&answerMutex);

    return 0;
}


texts:
public class MergeSort {

    public static void sort(int[] array, int lo, int hi) {
        if (hi <= lo) {
            return;
        }

        int mid = lo + (hi - lo) / 2;
        sort(array, lo, mid);
        sort(array, mid + 1, hi);
        mergesort(array, lo, mid, hi);
    }

    private static void mergesort(int[] array, int lo, int mid, int hi) {
        int[] aux = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            aux[i] = array[i];
        }
        int i = lo;
        int j = mid + 1;
        for (int k = lo; k <= hi; k++) {
            if (i > mid) {
                array[k] = aux[j++];
            } else if (j > hi) {
                array[k] = aux[i++];
            } else if (aux[i] > aux[j]) {
                array[k] = aux[j++];
            } else {
                array[k] = aux[i++];
            }
        }
    }

    public static void main(String[] args) {
        int[] a = { 3, 1, 5, 1, 8, 23, 55, 54, 10, 12, 5 };
        MergeSort.sort(a, 0, a.length - 1);
        show(a);
    }

    private static void show(int[] a) {
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

}

It took me a whole day and a half to understand the code but I did a quick test and it worked. One thing I am concerned with is that the coursera class I am taking does it differently, instead of creating aux in mergesort they create aux in a helper class and pass around BOTH arrays in the sort and mergesort method. It looked like this:

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

/**
 * Rearranges the array in ascending order, using the natural order.
 * @param a the array to be sorted
 */
public static void sort(Comparable[] a) {
    Comparable[] aux = new Comparable[a.length];
    sort(a, aux, 0, a.length-1);
    assert isSorted(a);
}

and when it got to the merge sort method it finally copies the aux array, what is the point of this route?  It looks like it just takes more code.


texts: Truncating long strings when saving inventory items to database

texts:
To test incoming data for string values that are too large for the "database" (MS Access), I could do this:

private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
    invItem = TruncateVerboseStringMembers(invItem);
    . . .
}

private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
    const int DESC_MAX_LEN = 35;
    const int VENDOR_ID_MAX_LEN = 10;
    const int VENDOR_ITEM_MAX_LEN = 12;
    if (invItem.Description.Trim().Length > DESC_MAX_LEN)
    {
        invItem.Description = invItem.Description.Substring(0, DESC_MAX_LEN);
    }
    if (invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN)
    {
        invItem.vendor_id = invItem.vendor_id.Substring(0, VENDOR_ID_MAX_LEN);
    }
    if (invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN)
    {
        invItem.vendor_item = invItem.vendor_item.Substring(0, VENDOR_ITEM_MAX_LEN);
    }
    return invItem;
}

...where TruncateVerboseStringMembers() is always called, even though normally all conditions will fail (strings will not be too long), or I could do it like this:

const int DESC_MAX_LEN = 35;
const int VENDOR_ID_MAX_LEN = 10;
const int VENDOR_ITEM_MAX_LEN = 12;

private void SaveToMSAccess(InventoryItem invItem, string dbContext)
{
    if ((invItem.Description.Trim().Length > DESC_MAX_LEN) ||
        (invItem.vendor_id.Trim().Length > VENDOR_ID_MAX_LEN) ||
        (invItem.vendor_item.Trim().Length > VENDOR_ITEM_MAX_LEN))
    {
        invItem = TruncateVerboseStringMembers(invItem);
    }
    . . .
}

private InventoryItem TruncateVerboseStringMembers(InventoryItem invItem)
{
    if (invItem.Description.Trim().Length > DESC_MAX_LEN)
    {
        . . .

...where TruncateVerboseStringMembers() is only called when it needs to swing into action.

Or something fancier, where, if any strings are too long, I pass an array of bool to TruncateVerboseStringMembers().

Which is preferred?


texts:
I'm using C++11 with https://github.com/SmingHub/Sming. It has no support of std lib or exceptions. I wanted to use Either monad to return an error or result from my functions.
I implemented it using class hierarchy. I'm not a native C++ dev so I would be glad for the code review.
#pragma once

template <class L, class R>
class Either
{
    virtual bool isLeft();
    virtual bool isRight();

    virtual bool matchLeft(L& x);
    virtual bool matchRight(R& x);
};

template <class L, class R>
class Left : public Either<L, R> {
public:
    L left;

    Left(L left): left(left) {}
    constexpr bool isLeft() { return true; }
    constexpr bool isRight() { return false; }

    bool matchLeft(L& x)
    {
        x = left;
        return true;
    }
    bool matchRight(R& x) { return false; }
};

template <class L, class R>
class Right : public Either<L, R> {
public:
    R right;

    Right(R right): right(right) {}
    constexpr bool isLeft() { return false; }
    constexpr bool isRight() { return true; }

    bool matchLeft(L& x) { return false; }

    bool matchRight(R& x) {
        x = right;
        return true;
    }
};


texts: Start task as soon as multiple tasks are successful

texts:
I write an hobbyist application that collects soccer-data from different sources around the www and aggregates it for a graphical representation and sends it out as a tweet. Now I want to fully automate this process in a more or less robust way (more or less because 1. this is a hobby and 2. depends on scraped 3rd party websites).

I have problems to wrap my head around how this full automation can be organized. The following tasks need to be done:

check once daily if and when there are soccer matches I am interested in
start collecting data of these matches from all sources as soon as match is
over
retry collecting data every x minutes if it wasn't available yet (the sources have very different speed in releasing the data and it may take 24hrs. sometimes)
as soon as all sources have been collected successfully launch aggregation and tweet.

My question:
I don't know how to implement the connection between 3. and 4. in a good way. I think I need some wrapper which is called by the scheduler as soon as a match is over, but this doesn't seem to be a robust way:

class MatchCollector:

    def __init__(self,teams,sources=settings.sources):
        self.teams=teams
        self.sources = sources

    def execute(self):
        finished = False
        counter = 0
        while not finished:
            finished = True
            for source in self.sources:
                s = SourceCollector(source,self.teams)
                successful = s.execute()
                if not successful:
                    finished = False
            time.sleep(600)
            counter += counter
            if counter == 10000 # arbitrary chosen, have to make calc, when would be a good point to give up
                 raise IterationException('Tried for x hours without success. Somethings broken')
        d = DataAggregator(sources)
        d.execute()

Am I missing something problematic, by doing this?

I arrange daily scheduling (1., 2.) via cron and python-crontab in a scheduling script. It is started once daily and reads the daily matches and writes again into cron the script to handle the single matches with arguments passed via sys.argv.


texts:
I would like any advice on how to improve this code. To clarify what this code considers an intersection to be, the intersection of [3,3,4,6,7] and [3,3,3,6,7] is [3,6,7]. I would appreciate any improvements to make the code more readable or perform faster.

public ArrayList<Integer> findIt (int[] a, int[] b){
    ArrayList<Integer> result = new ArrayList<Integer>();
    Arrays.sort(a);
    Arrays.sort(b);
    int i = 0;
    int j = 0;
    while(i < a.length && j < b.length){
        if(a[i]<b[j])
            ++i;
        else if (a[i] > b[j])
            ++j;
        else{
            if (!result.contains(a[i]))
                result.add(a[i]);
            ++i;
            ++j;
        }
    }
    return result;
}


texts:
Below is a set of extensions that I use in unit tests.

The basic idea is that when creating or modifying some sort of user output type of string, I want to eyeball the output to see that it makes sense, even though it might be 'correct' in a unit test sense. But when doing almost any other tests and certainly when regression testing, I don't want the added noise or time it takes to do so.

For example:

[TestCase("US1")]
[TestCase("123")]
[TestCase("E$R")]
public void Get_From_IsoAlphaCode_IfThreeLetterCodeIsNotAllAlpha_Error(string val)
{
    var ex = Assert.Throws<IsoAlphabeticCodeFormatException>(() => Currency.Get(val));
    ex.Look();  // *** eyeball the whole exception using extension ***
    Assert.That(ex.Message, Is.StringStarting(IsoAlphabeticCodeFormatException.Not3AlphaCharsMessage));
    Assert.That(ex.ParamName, Is.StringMatching("isoAlphaCode"));
    Assert.That(ex.ActualValue, Is.EqualTo(val));
}

    // OUTPUT
IsoAlphabeticCodeFormatException: Badly formed ISO 4217 Aplhabetic Code.
The passed code was not three (3) alphabetic characters.
Parameter name: isoAlphaCode
Actual value was bubba.
   at Support.Guard.AgainstBadIsoAlphaCodeFormat(String paramName, String value) in C:\Support\Guard.cs:line 26
   at Currency.Get(String isoAlphaCode) in C:\Currency.cs:line 731
   at Tests.Currencies.CurrencyTests.<>c__DisplayClass6.<Get_From_IsoAlphaCode_IfThreeLetterCodeIsWrongSize_Error>b__5() in C:.Tests\Currencies\CurrencyTests.CacheFetching.cs:line 95
   at NUnit.Framework.Assert.Throws(IResolveConstraint expression, TestDelegate code, String message, Object[] args)

21 passed, 0 failed, 0 skipped, took 4.71 seconds (NUnit 2.5.10).

So, the design goals here are:

be short and easy to use
be configurable

And I have two concerns about the class as is:

Am I rewriting some existing functionality (ie, does Trace, Debug, NUnit, log4net, etc already do this?
What is a better way to configure the verbosity level?

Here's my code:

///
/// Helpers to 'eyeball' artifacts of a unit test
///
public static class UnitTestLoggingExtensions
{
    private enum OutputOption { OFF, VERBOSE, TERSE, }

    private static OutputOption option = OutputOption.TERSE;

    /// Writes the passed string and any passed format arguments.
    public static void Look(this string msg, params object[] args)
    {
        if (msg == null) {
            Debug.Write("");
            return;
        }
        switch (option)
        {
            case OutputOption.OFF:
                break;
            case OutputOption.VERBOSE:
                Debug.WriteLine(_createVerboseMessage(msg, args), "INFO");
                break;
            case OutputOption.TERSE:
                Debug.WriteLine(string.Format(msg, args), "INFO");
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    /// Writes the passed exception's message.
    public static void Look(this Exception ex) { Look(ex.Message); }

    /// Writes the passed object, invoking ToString().
    public static void Look(this object o) { Look(o.ToString()); }

    /// Writes the passed items, invoking ToString().
    public static void Look<T>(this IEnumerable<T> items)
    {
        foreach (var o in items)
        {
            o.Look();
        }
    }

    /// Writes the passed items along with a header.
    public static void Look<T>(this IEnumerable<T> items, string header)
    {
        header.Look();
        items.Look();
    }

    private static string _createVerboseMessage(string format, params object[] args)
    {
        return string.Format("[{0}]{1}->   {2}",
            DateTime.Now.ToString("o"),
            Environment.NewLine,
            string.Format(format, args));
    }
}


texts: Alarm clock with "ringing" functionality

texts:
I have a question regarding a program that is to run an alarm clock and display the time (HH:MM AM/PM) and also trigger the alarm and display "ringing" at 12:00 AM.

I am a beginner in Java and I am a little lost. I believe I have most of the skeletal work done. This is much like another question asked on here but I could not find an answer to my problems. So I apologize for the similarity. I am also to create a "dummy driver" in order to test the method as one of the requirements for this program is to be able to be read by a general driver someone else has created. Therefore, all of my variables and methods must be left the way I have them in order to be read by said driver. I wish I could be a little more specific in what I need assistance with but any feedback you can give me is much appreciated.

This is what I've got so far:

//dummy driver
package program5;

public class Program5 {

public static void main(String[] args) {
AlarmClock alarm = new AlarmClock();
System.out.println(alarm.getHour() + ":" + alarm.getMinute() + alarm.getAmOrPM());
System.out.println(alarm.getAlarmHour() + ":" + alarm.getAlarmMinute() + alarm.getAlarmAmOrPm());
System.out.println(alarm.isIsAlarmRinging());
}
}

package program5;

public class AlarmClock {

private int hour;
private int minute;
private String amOrPm;
private int alarmHour;
private int alarmMinute;
private String alarmAmOrPm;
private boolean isAlarmRinging;

//constructor:
AlarmClock() {
hour = 12;
alarmHour = 12;
minute = 0;
alarmMinute = 0;
alarmAmOrPm = new String();
amOrPm = new String();
isAlarmRinging = false;
}

//getters:
public int getHour() {
if ((hour >= 1) && (hour <= 12)) {
}
return hour;
}

public int getMinute() {
if ((minute >= 0) && (minute <= 59)) {
}
return minute;
}

public String getAmOrPM() {
return amOrPm;
}

public int getAlarmHour() {
return alarmHour;
}

public int getAlarmMinute() {
return alarmMinute;
}

public String getAlarmAmOrPm() {
return alarmAmOrPm;
}

public boolean isIsAlarmRinging() {
if (hour >= 12){
isAlarmRinging = true;
}
return isAlarmRinging;
}

//setters
public void setHour(int newHour) {
if ((newHour >= 1) && (newHour <= 12)) {
    hour = newHour;
}
}

public void setMinute(int newMinute) {
if ((newMinute >= 0) && (newMinute <= 59)) {
    minute = newMinute;
}
}

public void setAmOrPM(String newAmOrPm) {
amOrPm = newAmOrPm;
}

public void setAlarmHour(int newAlarmHour) {
if ((newAlarmHour >= 1) && (newAlarmHour <= 12)) {
    alarmHour = newAlarmHour;
}
}

public void setAlarmMinute(int newAlarmMinute) {
if ((newAlarmMinute >= 0) && (newAlarmMinute <= 59)) {
    alarmMinute = newAlarmMinute;
}
}

public void setAlarmAmOrPm(String newAlarmAmOrPm) {
alarmAmOrPm = newAlarmAmOrPm;
}

public void setIsAlarmRinging(boolean isAlarmRinging) {
if (isAlarmRinging = true) {
    System.out.println("Ringing!");
}
}

public void advanceOneMinute() {
minute++;
if (minute == 59) {
    hour++;
}
}

public void advanceMinutes(int minutesToAdvance) {

}

public void advanceOneHour() {
hour++;
if (hour > 12) {
hour = 1;
}
}

public void advanceHours(int hoursToAdvance) {

}

public void setTime(int newHour, int newMinute, String newAmOrPm) {
hour = newHour;
amOrPm = newAmOrPm;
}

public void setAlarmTime(int newAlarmHour, int newAlarmMinute, String newAlarmAmOrPm) {

if(hour >=0 && hour <= 23 && minute >=0 && minute <= 59) {
newAlarmHour = hour;
newAlarmMinute = minute;
}
}

public void turnOffAlarm() {
isAlarmRinging = false;
}

public void displayTime() {

}

public void displayAlarmTime() {

}

}

It's far from done but it's a start. If you can tell me anything I can do, I'll be very thankful. I'm not sure exactly what my question is. Just if I'm on the right track and what I'm doing wrong. Sorry it's not a short, concise, clear-cut question.


texts:
I am trying to learn Haskell doing some contest problems. I have worked a bit with the language but still have a very long way ahead.

Right now I am working with a problem called Ants:

  An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.

  Input

  The first line of input contains one integer giving the number of cases that follow, at most 100. The data for each case start with two integer numbers: the length l of the pole (in cm) and n, the number of ants residing on the pole. These two numbers are followed by n integers giving the position of each ant on the pole as the distance measured from the left end of the pole, in no particular order. All input integers are between 0 and 1000000 and they are separated by whitespace.

  Output

  For each case of input, output two numbers separated by a single space. The first number is the earliest possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) and the second number is the latest possible such time.

  Sample input

2
10 3
2 6 7
214 7
11 12 7 13
176 23 191

It is pretty straight forward, some parsing and minor calculation. My program finished running in 0.69 seconds, while the best result someone achieved with Haskell is something like 0.03! It is very annoying.

I have tried to speed it up with some even uglier code, but the best I have managed with this is 0.66 seconds.

Can anyone spot some obvious things about this code to improve the runtime?

main = do
    contents <- getContents
    let cases = parse contents

    mapM_ putStrLn (map showcase cases)

type Case = (Int, [Int])

showcase :: Case -> String
showcase (len, positions) =
    let ds = dists len positions
        edgiest = (snd . maximum) ds
        es = max (len - edgiest) edgiest

        midmost = (snd . minimum) ds
        mm = min (len - midmost) midmost
    in show mm ++ " " ++ show es

dists :: Int -> [Int] -> [(Float, Int)]
dists l = map (\x -> (abs (fromIntegral x - m), x))
    where m = fromIntegral l / 2.0

parse :: String -> [Case]
parse = parseCases . tail . words -- skip the first integer

parseCases :: [String] -> [Case]
parseCases [] = []
parseCases xs =
    let (cs, rest) = parseCase xs
    in cs : parseCases rest

parseCase :: [String] -> (Case, [String])
parseCase (len:a:xs) =
    let ants = read a
        positions = (map read . take ants) xs
        rest = drop ants xs
    in ((read len, positions), rest)


texts: Converting words/numbers to Discord "letter/number emojis"

texts:
I am a beginner to Python (and programming overall) and I decided that it would be funny if I wrote a program that could convert Letters/Numbers to these
"Letter Emojis" in Discord.
It works but I am quite unsure if this is the best way to do it.
There are also some bugs caused by adding spaces before actually typing Letters/Numbers.
I commented it as precisely as I could to make the Code as understandable as possible

from tkinter import *

root = Tk()

# defines the funtion click which gets called when the submitButton1 is pressed
def click():
    # makes sure the list is empty in case the user presses the button again to convert something new
    result.clear()
    # saves the text which is entered in the textentry box, this later gets converted to "Discord Letters"
    entered_text=textentry.get()
    # deletes the output box in case the user presses the button again to convert something new
    output.delete(1.0, END)
    # the function to convert a String to "Discord Letters"
    discord(entered_text)
    # loop which gets the length of the string typed in the textentry box and then outputs it to the output textbox
    for i in range(len(entered_text)):
        output.insert(END, result[i])

# A List in which the converted Letters are stored it's later used to output the converted Letters in a Textbox
result = []

# the function to convert a String to "Discord Letters"
def discord(word):
    # List of numbers from 0-9 , is used to check the string for numbers and then convert them
    # to "Discord Digits" since they have a different syntax in discord than Letters
    chars = set('0123456789')
    s = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
         'w', 'x', 'y', 'z'}
    # In case the User enters spaces they get removed since they just cause trouble
    word = word.replace(" ", "")
    word = word.lower()
    w = word
    for i in range(len(w)):
        # checks if the string has a number and outputs accordingly
        if any((c in chars) for c in w[i]):
            list_one = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]
            result.append(':' + list_one[int(w[i])] + ":" + " ")
        # checks if the string has letter and outputs accordingly (might be unnecessary)
        elif any((c in s) for c in w[i]):
            result.append(':regional_indicator_' + w[i] + ":" + " ")
        else:
            # In case the user inputs something wrong
            print("False Input")

root.title("Discord Letter Converter")
# TextInput
textentry = Entry(root, width=20, bg="white")
textentry.pack()
# submitButton
submitButton1 = Button(root, text="Submit", width=6, command=click)#
submitButton1.pack()
# TextOutput
output = Text(root, width=75, height=6, wrap=WORD, background="white")
output.pack()
root.mainloop()
```


texts:
I'm creating a small library of Python utilities, and I'd like feedback on a function which allows iterating over an arbitrary iterable in a sliding-window fashion.

Relevant parts of iteration.py:

import collections
import itertools

def sliding_window_iter(iterable, size):
    """Iterate through iterable using a sliding window of several elements.

    Creates an iterable where each element is a tuple of `size`
    consecutive elements from `iterable`, advancing by 1 element each
    time. For example:

    >>> list(sliding_window_iter([1, 2, 3, 4], 2))
    [(1, 2), (2, 3), (3, 4)]
    """
    iterable = iter(iterable)
    window = collections.deque(
        itertools.islice(iterable, size-1),
        maxlen=size
    )
    for item in iterable:
        window.append(item)
        yield tuple(window)

Relevant parts of the test file iteration_test.py:

import doctest
import unittest

import iteration
from iteration import *

class TestSlidingWindowIter(unittest.TestCase):
    def test_good(self):
        self.assertSequenceEqual(
            list(sliding_window_iter([1, 2, 3, 4], 2)),
            [(1, 2), (2, 3), (3, 4)]
        )

    def test_exact_length(self):
        self.assertSequenceEqual(
            list(sliding_window_iter(["c", "b", "a"], 3)),
            [("c", "b", "a")]
        )

    def test_short(self):
        self.assertSequenceEqual(
            list(sliding_window_iter([1, 2], 3)),
            []
        )

    def test_size_one(self):
        self.assertSequenceEqual(
            list(sliding_window_iter([1, 2, 3, 4], 1)),
            [(1,), (2,), (3,), (4,)]
        )

    def test_bad_size(self):
        with self.assertRaises(ValueError):
            list(sliding_window_iter([1, 2], 0))

def run():
    if not doctest.testmod(iteration)[0]:
        print("doctest: OK")
    unittest.main()

if __name__ == "__main__":
    run()

I'm primarily looking for feedback in these areas:

Is the code Pythonic? I'm primarily a C++ developer, so Python idioms don't come naturally to me; that's one thing I'm constantly trying to improve.
Are there any potential performance problems?
Am I reinventing a wheel and something like this already exists?

I'll welcome any other feedback too, of course.


texts: Bash Code to backup the history file in Linux

texts:
How is the logic, efficiency and can it be improved?

This is a snippet from my .bashrc file, I just wrote it.

The code is supposed to do this:

Backup my .bash_history file if it is 1000 lines or less from the defined size of HISTSIZE=100000 and HISTFILESIZE=100000 lines, then backup the file.

Check if .bash_history is 99000 lines or more.
Check if ~/.bash_history.old exists if it doesn't use that filename.
Increment i one digit larger than is already used by filenames.(filename-4.old)
Check if there are more than 20 files already backed up and warn if it is.
Set the new filename into a variable.
Check if the last file with a digit in it's filename is older than the original.
cp the file to new_name

Here is the code:

# Count the number of lines in `/.bash_history and check if it's equal or more than a thousand
if (( $(wc -l < ~/.bash_history) >= 99000 ))
then
    name=~/.bash_history
    # Here is the suffix of the new files and the ones I check for
    old=.old
    # -e FILE ==> True if FILE exists.
    if [[ ! -e ~/.bash_history.old ]]
    then
       printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
       # Here I copy $name which is ~/.bash_history and create backup file
       cp $name ~/.bash_history.old
    else
        # i is the increment in the filenames to be checked and created
        i=0
        # $name$old is ~/.bash_history.old
        if [[ -e $name$old ]]
        then
            # Here I count how many copies there are with digits in the filename
            while [[ -e "$name-$i$old" ]]
            do
                let i++
            done
        fi
        # if there are 20 files already backed up then I need to archive them somewhere else
        if [[ "$i" -ge 20 ]]
        then
            printf "%s\n" "********************************************************" "You need to arhive your history files they are mounting up!!!" "**************************************************************"
        fi
        new_name=$name-$i$old
        minus=$(( i - 1 ))
        if [ $name -nt "$name-$minus$old" ]
        then
            printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
            cp ~/.bash_history "$new_name"
        fi
    fi
fi

This is the result from shellcheck.net:

Line 16:
                let i++
                ^-- SC2219: Instead of 'let expr', prefer (( expr )) .