texts:
I have several classes for payment handling, I separate these classes into directories like below. Actually I'm going to use it for Laravel project but to make it simple, maybe we can talk as if it's native PHP code.

\Payment
    PaymentServiceAdapterInterface.php -> an interface for service adapter
    PaymentServiceBase.php -> an abstract class for doing common things
    PaymentService.php -> the class that interacts to external code that is doing Payment things

    \Paypal
        Paypal.php -> paypal wrapper class for calling API's
        PaypalService.php -> the class to provide paypal services
        PaypalServiceAdapter.php -> the class that provide uniform methods to be called by PaymentService.php

    \Stripe
        Stripe.php
        StripeService.php
        StripeServiceAdapter.php

PaymentService class:

class PaymentService {

    public function __construct(PaymentServiceAdapterInterface $gateway)
    {
         $this->gateway = $gateway;
    }

    public function authorize()
    {
         $this->gateway->authorize();
    }

    public function capture()
    {
         $this->gateway->capture();
    }
}

PaypalServiceAdapter class is like the following (for Stripe would be similar) - for simplicity let's say we have only 2 methods (authorize and capture), please don't care too much about codes inside the method, it's just an example that each gateway may have different implementation.

class PaypalServiceAdapter extends PaymentServiceBase implements PaymentServiceAdapterInterface {

    public function __construct(PaypalService $paypal)
    {
        $this->paypal = $paypal;
    }

    public function authorize()
    {
        $this->paypal->prepare();
        $this->paypal->authorize();
    }

    public function capture()
    {
        $this->paypal->capture();
    }
}

To make it short, I don't provide the code of PaypalService.php and Paypal.php, it's pretty obvious I think (but let me know if it's not).

My questions:

Am I doing it right? Please forgive me if there is any wrong term (and maybe the name of classes) and please let me know how/what it should be.
If I want to make each gateway as separate package, which means it won't use external class or interface like PaymentServiceBase and PaymentPaymentServiceAdapterInterface, where do I put PaymentServiceAdapterInterface? Do I need to duplicate it on each package (and keep one in Payment directory as it's needed by PaymentService class constructor)?


texts:
After getting suggestions for Maximum Priority Queue I have written program for Minimum Priority Queue. Help me improve this code.
#include <iostream>
#include <vector>

template<typename T>
class min_priority_queue
{

  size_t parent(size_t index)
  {
    return (index-1)/2;
  }

  void min_heapify(std::vector<T>& array, size_t index)
  {
    size_t smallest;
    size_t left  = (2*index) + 1;
    size_t right = left + 1;

    if(left < array.size() && array[left] < array[index])
      smallest = left;
    else
      smallest = index;

    if(right < array.size() && array[right] < array[smallest])
      smallest = right;

    if(smallest != index)
    {
      std::swap(array[index], array[smallest]);
      min_heapify(array, smallest);
    }
  }

public:
  min_priority_queue() {}
  min_priority_queue(const min_priority_queue<T>& mpq)     = delete;
  min_priority_queue& operator=(min_priority_queue const&) = delete;

  void build_min_heap(std::vector<T>& array)
  {
    for(int64_t i = (int64_t(array.size())/2) - 1; i >= 0; i--)
    min_heapify(array, i);
  }

  T heap_minimum(std::vector<T>& array)
  {
    return array[0];
  }

  T heap_extract_min(std::vector<T>& array)
  {
    T min = array[0];
    array[0] = array[array.size() - 1];
    array.resize(array.size() - 1);
    min_heapify(array, 0);
    return min;
  }

  void heap_decrease_key(std::vector<T>& array, size_t index, T value)
  {
    if(value > array[index])
    {
      std::cerr << "New value is larger than the current value\n";
      return;
    }
    else
    {
      array[index] = value;
      while(index > 0 && array[parent(index)] > array[index])
      {
        std::swap(array[index], array[parent(index)]);
        index = parent(index);
      }
    }
  }

  void min_heap_insert(std::vector<T>& array, T value)
  {
    array.resize(array.size() + 1);
    array[array.size() - 1] = 10^9;
    heap_decrease_key(array, array.size() - 1, value);
  }

  void print_heap(const std::vector<T>& array)
  {
    for(size_t i = 0; i < array.size(); i++)
     std::cout << array[i] << " ";
  }
};

int main()
{
  std::vector<int> v;
  min_priority_queue<int> mpq1;
  v.push_back(1);
  v.push_back(8);
  v.push_back(6);
  v.push_back(3);
  v.push_back(7);
  mpq1.build_min_heap(v);
  std::cout << "Queue: ";
  mpq1.print_heap(v);
  std::cout<< '\n';
  std::cout << "Extract-Minimum: " << mpq1.heap_extract_min(v) << '\n';
  std::cout << "New Queue: ";
  mpq1.print_heap(v);
  mpq1.min_heap_insert(v, 2);
  std::cout << "\nNew Queue after inserting 2: ";
  mpq1.print_heap(v);
  std::cout << '\n';
}

I am unable to build queue for char or string because in
void min_heap_insert(std::vector<T>& array, T value)
  {
    array.resize(array.size() + 1);
    array[array.size() - 1] = 10^9;
    heap_decrease_key(array, array.size() - 1, value);
  }

I have written array[array.size() - 1] = 10^9; How to fix this so that I can build queue for char and string values.


texts:
Can you please provide a general review the following PHP code (with MySQLi)?

The query involves an INSERT INTO statement:

public function __i($table, $arr) { $c=$this->connection;
   foreach ( $arr as $name => $val):
      $param1.=$name . ",";
      $param2.="?,";
   endforeach;

   $PARAM1 = substr_replace($param1, '', -1);
   $PARAM2 = substr_replace($param2, '', -1);

   $query = 'INSERT INTO '.$table.' ('.$PARAM1.') VALUES ('.$PARAM2.')';

   echo $query;
   foreach ( $arr as $name => $val):
    if ( is_int($val)) :
         $param = 'i';
      endif;

      if ( is_string($val)) :
         $param = 's';
      endif;

      if ( is_double($val)) :
         $param = 'd';
      endif;
      $binds.=$param;
      $values.="'".$arr[$name]."',";

    endforeach;

    $values = substr_replace($values, '', -1);
    echo "BINDS ARE: ".$binds . "
";
    echo "VALUES ARE: ".$values."
";

   if ( $s = $c->prepare($query)):

      $args = $binds + $values;
      call_user_func_array(array($s, 'bind_param'), array($binds, $values));
      $s->execute();
      $s->close();
   endif;

}


texts:
I am trying to solve ProjectEuler.net problem #50, Consecutive Prime Sum. Here is the problem:

The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?

I have written some code which solve the problem just fine when the limit is 10, 100, 1000 or 10000 but when the limit is 1000000 as the problem requires, the program takes too much time to finish running!!
What can be done to my code to make the program faster?
package com.company;
import java.util.ArrayList;

class ConsecutivePrimeSum {
    public static int limit=1000000;
    int lengthOfTheLongest =0;
    int sumOfTheLongest =0;

    void solution(){
        ArrayList<Integer> arrayOfPrimes=generatePrimes();
        scanSequences(arrayOfPrimes);
        System.out.println("The longest sum is "+ sumOfTheLongest +"  and contains "+lengthOfTheLongest+" terms");
    }
    private ArrayList<Integer> generatePrimes(){
        ArrayList<Integer> arrayOfPrimes=new ArrayList<Integer>();
        for(int i=limit;i>=2;i--){
            if(isPrime(i)){
                arrayOfPrimes.add(i);
            }
        }
        return arrayOfPrimes;
    }

    /**
     * @param s
     * this scans ArrayList s, to get sequence of prime numbers and calculate
     * their sum and corresponding length
     * then assign the longest length to the variable lengthOfTheLongest, and its sum to variable sumOfTheLongest
     */
    private void scanSequences(ArrayList<Integer> s){
        ArrayList<Integer> cumulativeSums=generateCumulativeSums(s);
        for(int start=1;start<=s.size();start++){
            for (int end=s.size()-1;end>=start;end--){
                if(!isPrime(sumFromTo(cumulativeSums,start,end)))  continue;
                if(sumFromTo(cumulativeSums,start,end)>limit) break;
                if ((end-start+1)> lengthOfTheLongest){
                    sumOfTheLongest =sumFromTo(cumulativeSums,start,end);
                    lengthOfTheLongest =(end-start+1);
                }
            }
        }

    }

    /**
     * @param s
     * @return arraylist of cumulative sums of the elements in s
     */
    private ArrayList<Integer> generateCumulativeSums(ArrayList<Integer> s){
        int sum=0;
        ArrayList<Integer> cumulativeSums=new ArrayList<Integer>();
        for (int i=0;i<s.size();i++){
            cumulativeSums.add(sum=sum+s.get(i));
        }
        return cumulativeSums;
    }

    /**
     * @param a is an ArrayList whose elements are to be summed
     * @param start is the index of where summing should start
     * @param end is the index of where summing should end
     * @return the obtained sum
     */
    private int sumFromTo( ArrayList<Integer> a,int start, int end){
        int sum;
        sum=a.get(end)-a.get(start-1);
        return sum;
    }

    private static boolean isPrime(int number){
        boolean isPrime=false;
        int divider=2;
        int count=0;
        while(divider<=number){
            if(number%divider==0)
                count=count+1;
            divider=divider+1;
        }
        if(count==1)
            isPrime=true;

        return isPrime;
    }

}
class Test{
    public static void main(String [] args){
        ConsecutivePrimeSum consecutivePrimeSum=new ConsecutivePrimeSum();
        consecutivePrimeSum.solution();
    }
}

```


texts:
Recently, I was taking up this challenge and choose my favorite language 'Ruby' to do it.
My following solution got accepted (Gist).

For each test case, I am to reverse two numbers, add them, and print the reverse of the sum.  Reversing means taking the base-10 digits of a number in reverse order, stripping any leading or trailing zeroes.

### Code
cases = gets.chomp.to_i

if cases.zero?
  puts "Enter number > 0"
  exit
end

def reverse_num(num)
  num.to_s.reverse.to_i
end

def rev_add(data)
  sum = 0
  data.each do |rec|
    sum += reverse_num(rec)
  end
  reverse_num(sum)
end

results = []

cases.times do |index|
  input_str = gets.chomp
  nums = input_str.split(' ').map(&:to_i)
  results[index] = rev_add(nums)
end

results.each { |e| puts e }

### End of Code

It showed that I have used 7.3MB memory which I don't have any idea.

I know this is not the optimized solution. I have used lots of looping which could be minizied.
Could you review it and help me to optimize it?


texts:
I'm learning bash and my goal here is from any repository on my computer to be able to type github and it will open the remote in a browser for me.

This works but I feel like I over complicated the remote=$(..) logic and arguably the get_ext() method.

get_ext() allows you to type github issues and it will open the issues page for that repo on github. I know it could work better if there was a hash map equivalent in bash but from what I can find, there's not.

code:

#! /bin/bash

endpoint=$1

get_ext() {
  case $1 in
    *github*)
      case $endpoint in
        pr)
          echo "/pulls";;
        issues)
          echo "/issues";;
        *)
          echo "";;
      esac;;
    *bitbucket*)
      case $endpoint in
        pr)
          echo "/pull-requests";;
        issues)
          # issues doesn't exist for bitbucket
          echo "";;
        *)
          echo "";;
      esac;;
  esac
}

open_site() {
  # currently only works for SSH addresses
  if [[ $remote == *@* ]]; then
    name=$(echo $remote | sed  "s/^.*:\(.*\)\.git/\1/g")
    ext=$(get_ext $1)
    open "$1/${name}${ext}"
  fi
}
remote=$(grep -A 1 "remote \"origin\"" $(pwd)/.git/config | sed -n 2p)

case $remote in
  *github*)
    open_site "https://github.com";;
  *bitbucket*)
    open_site "https://bitbucket.org";;
esac


texts: Generate simple sinusoidal sounds and plot signal/fft

texts:
I made a small python script to create an audio sound used as stimuli. It's one of my first uses of super(), and I do not know if I did it right. I'm looking for any improvement in both optimization and style you could suggest.
import pyaudio
import numpy as np

class SoundStimuli:
    def __init__(self, fs=44100, duration=1.0):
        self.fs = fs
        self.duration = duration
        self.t = np.linspace(0, duration, int(duration*fs), endpoint=False)
        self.signal = None

    def play(self):
        if self.signal is None:
            print ('WARNING: No audio signal to play.')
            return

        p = pyaudio.PyAudio()

        # for paFloat32 sample values must be in range [-1.0, 1.0]
        stream = p.open(format=pyaudio.paFloat32,
                        channels=1,
                        rate=self.fs,
                        output=True)

        # play. May repeat with different volume values (if done interactively)
        stream.write(self.signal)

        stream.stop_stream()
        stream.close()
        p.terminate()

    def convert2float32(self):
        self.signal = self.signal.astype(np.float32)

    def plot_signal(self, ax, **plt_kwargs):
        if self.signal is None:
            print ('WARNING: No audio signal to plot.')
            return

        ax.plot(self.t, self.signal, **plt_kwargs)

    def plot_signal_fft(self, ax, **plt_kwargs):
        fft_freq = np.fft.rfftfreq(self.t.shape[0], 1.0/self.fs)
        fft = np.abs(np.fft.rfft(self.signal))
        ax.plot(fft_freq, fft, **plt_kwargs)

class ASSR(SoundStimuli):
    def __init__(self, fc, fm, fs=44100, duration=1.0):
        super().__init__(fs, duration)
        self.fc = fc
        self.fm = fm

    def classical_AM(self):
        self.assr_amplitude = (1-np.sin(2*np.pi*self.fm*self.t))
        self.signal = self.assr_amplitude * np.sin(2*np.pi*self.fc*self.t).astype(np.float32)

    def DSBSC_AM(self):
        self.assr_amplitude = np.sin(2*np.pi*self.fm*self.t)
        self.signal = self.assr_amplitude * np.sin(2*np.pi*self.fc*self.t).astype(np.float32)

    def plot_signal(self, ax, amplitude_linestyle='--', amplitude_color='crimson', **plt_kwargs):
        super().plot_signal(ax, **plt_kwargs)
        ax.plot(self.t, self.assr_amplitude, linestyle=amplitude_linestyle, color=amplitude_color)

The class ASSR is imported in a second script where the stimuli is created:
sound = ASSR(fs=44100, duration=1.0, fc=1000, fm=40)
sound.classical_AM()

However, I do not play it using the .play() method because it looks like pyaudio doesn't accept the PyAudio and stream to be open/close outside the scope of .write(). And since I do not want to open a new stream every time I play a sound, I ended up using .play() to test the sound; and then create in the main program where ASSR is imported a new audio stream with different .write(sound.signal) calls.
# Initialize audio stream
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=sound.fs,
                output=True)

# Do stuff
stream.write(sound.signal)
# Do stuff
stream.write(sound.signal)

stream.stop_stream()
stream.close()
p.terminate()


texts: Implementing a stack and using it to print alternate elements in reverse

texts:
Challenge:

  Implement a stack interface.

Specifications:

  The interface should have ‘push’ and ‘pop’ functions.
  Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer.
  Your program should accept a file as its first argument.
  The file contains a series of space delimited integers, one per line.
  Print out every alternate space delimited integer, one per line.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;

public class Stack<T> {
    LinkedList<T> list = new LinkedList<>();

    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            System.out.println(
                retrieveAlternates(input.nextLine().split("\\s+"))
            );
        }
    }

    private static String retrieveAlternates(String[] input) {
        Stack<Integer> stack = new Stack<>();
        StringBuilder result = new StringBuilder();

        for (String s : input) {
            stack.push(Integer.parseInt(s));
        }

        for (int i = 0; i < input.length; i++) {
            if ((i & 1) == 0) {
                result.append(' ').append(stack.pop());
            } else {
                stack.pop();
            }
        }

        return result.substring(1);
    }

    public void push(T t) {
        list.add(t);
    }
    public T pop() {
        return list.removeLast();
    }
}

Tests:

@Test
public void test1 {
    assertEquals("4 2", Stack.retrieveAlternates("1 2 3 4"));
}

@Test
public void test2 {
    assertEquals("4 -2", Stack.retrieveAlternates("10 -2 3 4"));
}

I've never really had an "Implement X" challenge, before. This passed, but did I effectively do what was expected? Could it be better?


texts:
I have the following code which is a private method inside the form and retrieve all context menus from the form. I feel, that it is not that concise as it should be. Would be grateful for any suggestions.

  private IEnumerable<ContextMenuStrip> GetContextMenus()
    {
        var type = this.GetType();
        var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        var contextMenus = fields.Where(f => f.GetValue(this).GetType() == typeof(ContextMenuStrip));
        var menus = contextMenus.Select(f=> f.GetValue(this));
        return menus.Cast<ContextMenuStrip>();
    }


texts:
This is for homework but the deadline is over and I know the implementation is correct because it concurs with the math. At this point I just want to check my implementation for potential optimizations in terms of speed, memory usage, clarity, modularity, and anything else you guys might think of. (I know there is generally a trade-off between computation speed and memory usage, so if you have comments on that I appreciate any insight you might have)

The specs of the function are that it should be flexible as to how many doors and trials we want, and whether or not we're switching doors. We also assume that the guest always chooses the first door. This is the only non-variable component we're allowed.

For example, would using np.array make the code faster than using lists? I didn't think it'd make a difference because they're very small, but that could be wrong.

In general, what could I do better?

def monty_hall (num_doors, trials, switch):

    #count number of successful trials
    successes = 0

    for i in range(trials):
        #determine behind which door the prize is
        doors = [i for i in range(1, num_doors+1)]
        prize_door = np.random.choice(doors)

        #determine which door the host opens if guest switches
        host_doors = [i for i in range(2, num_doors+1)]
        if prize_door != 1:
            host_doors.remove(prize_door)
        host_choice = np.random.choice(host_doors)

        #determine which door the guest chooses if switching
        doors.remove(1); doors.remove(host_choice)
        guest_switch = np.random.choice(doors)

        #we assume the guest is always choosing the first door
        if prize_door == 1 and switch == 0:
            successes += 1

        elif prize_door != 1 and switch:
            if guest_switch == prize_door:
                successes += 1

    probability = successes / trials
    return probability


texts:
Ive been learning c for the past few weeks, I made a simple turn-based game to show off what I know. Is there anything I can do to improve the code or make the game run better?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>
#include <time.h>
#include <stdbool.h>

int main(){
    srand(time(NULL));
    bool play = true;

    while(play){
        int choose = -2;
        int P_h = 25;
        int E_h = 30;
        int SP_u = 3;
        puts("Do you wanna play this game. [Press 0 to exit or press any other number to play]");
        scanf("%d", &choose);

        if(choose == 0){
            play = false;
            puts("Goodbye");
            break;
        }
        else{
            puts("Okay");
            Sleep(300);

            while(E_h > 0){
                int P_at = (rand()%8);
                int E_at = (rand()%10);
                int SP = 100;
                int at_p = -5;

                if(P_h <= 0){
                    puts("You have died");
                    break;
                }
             if(E_h <= 0){
                puts("you win!");
                break;
             }

                printf("You have %d uses left of the super attack \n", SP_u);
                puts("Would you like to attack or do a super attack [Press 0 to do a super attack, Press 1 to attack]");
                scanf("%d", &at_p);

                if(at_p == 0){
                    if(SP_u <= 0){
                    puts("Sorry, you have 0 uses left, you cannot use this \n");
                }
                else{
                    E_h -= SP;
                    SP_u--;
                    printf("\nThe enemy took a damage of %d! It now has a health of %d!", SP, E_h);

                    P_h -= E_at;
                    printf("\nThe enemy attacks! Your health went down by %d it is now %d \n \n", E_at, P_h);
                }

            }
            else if(at_p == 1){
                 E_h -= P_at;
                printf("\nThe enemy took a damage of %d! It now has a health of %d!", P_at, E_h);

                P_h -= E_at;
                printf("\nThe enemy attacks! Your health went down by %d it is now %d \n \n", E_at, P_h);
            }
            else{
                puts("Thats not an option, idiot \n");
            }

        }

    }
    if(E_h <= 0){
            puts("You killed the enemy!");
            puts("Would you like to play again? [0 to exit, Press anything else to play again]");
            scanf("%d", &choose);

            if(choose == 0){
                play = false;
                break;
            }
            else{
                play = true;
            }
        }
        else if(P_h <= 0){
            puts("You died. Would you like to play again to try to defeat the enemy. [0 to exit, anything else to play again]");
            scanf("%d", &choose);

            if(choose == 0){
                play = false;
                break;
            }
            else{
                play = true;
            }
        }
    }

    return 0;
}

I feel like there is a better way to program the decisions because right now they are just nested if statements.
I think


texts: Euler 12: counting divisors of a triangle number

texts:
This is the question:

  The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five divisors.

  What is the value of the first triangle number to have over five hundred divisors?

import math
def triangulated(num):
    x = 0
    for num in range(1, num + 1):
        x = x + num
    return x

l = []

def factors(g):
    for n in range(1, triangulated(g) + 1):
        if triangulated(g) % n == 0:
            l.append(n)
    if len(l) > 500:
        print(triangulated(g))
        print(l)
    l.clear()

for k in range(1, 10000000000):
    factors(k)
    print(k)

Help optimise this problem.


texts:
I am trying to draw a heat map with a given input of points and amplitude of each point. The normal input size is around 400000 points, but the code draws every 15th point. The map is drawn onto a Canvas.

In the XAML:

<Grid x:Name="MainPanel" Width="800" Height="600">
    <Textbox Name="textbox" Grid.Column="0"/>
    <Canvas Name="canvas" Grid.Column="1" HorizontalAlignment="Left" Height="450" Margin="70,75,0,0" VerticalAlignment="Top" Width="706"/>
</Grid>

Rendering code:

public static void DrawPoints(Parser parser, Canvas canvas, double radiusX, double radiusY, double thickness, double minAmplitude, double maxAmplitude)
        {
            double cellWidth = canvas.ActualWidth;
            double cellHeight = canvas.ActualHeight;

            var list = parser.Data;

            // Draws every 15th point
            int res = 15;

            for (int i = 0; i < list.Count; i += res)
            {
                var location = list[i].Point;
                var amplitude = list[i].Amplitude;

                // Converts rgb to hsv values for representation
                var color= ColorConverter.hsv2rgb(
                    COLOR_START_H * (1.0 - ((amplitude - minAmplitude) / (maxAmplitude - minAmplitude))),
                    COLOR_START_S, COLOR_START_V);

                Point center = new Point(location.X, location.Y);
                DrawEllipse(canvas, center, radiusX, radiusY,
                    new SolidColorBrush(color), new SolidColorBrush(color), thickness);
            }
            return;
        }

In the DrawEllipse() function:

public static void DrawEllipse(Canvas canvas, Point center, double radiusX, double radiusY, Brush fill, Brush stroke, double thickness)
        {
            var ellipse = new Ellipse();
            ellipse.Width = radiusX * 2;
            ellipse.Height = radiusY * 2;
            ellipse.Fill = fill;
            ellipse.Stroke = stroke;
            ellipse.StrokeThickness = thickness;

            Canvas.SetLeft(ellipse, center.X - radiusX);
            Canvas.SetBottom(ellipse, center.Y - radiusY);

            canvas.Children.Add(ellipse);

            return;
        }

In the Main code:

private void btnDraw_Click(object sender, RoutedEventArgs e)
{
    Painter.DrawPoints(parser, canvas, 3, 3, 1, 0, 100);
}

The issue is that after rendering all the points onto Canvas, when I try to enter some text into textbox within the same grid, there is significant lag. What can I do to reduce the lag?


texts:
My Haskell set/map/list folds often become terse and difficult to read.  I'm looking for tips on how to make my functional code easier to follow.

I'm working around a bug/feature in a plotting library.  I have a map from tags to lists of (time,count) which I plot as a stacked graph:

import           Data.Time (UTCTime)
import qualified Data.Map as M
import qualified Data.Set as S

type CountMap = M.Map String [(UTCTime, Int)]

-- Data used for plotting data series 'foo' and 'bar'
test :: CountMap
test =
  M.fromList [ ("foo", [(read "2012-09-28 12:00:00", 3), (read "2012-09-29 12:00:00", 4)])
             , ("bar", [(read "2012-09-28 12:00:00", 3)])
             ]

You will note that the above "bar" series is missing a sample for 2012-09-29.  I need to fill these gaps with zeros before I pass the data to the plotting library.

The same data with the gaps closed becomes:

fromList [ ("bar",[(2012-09-28 12:00:00 UTC,3),(2012-09-29 12:00:00 UTC,0)])
         , ("foo",[(2012-09-28 12:00:00 UTC,3),(2012-09-29 12:00:00 UTC,4)])]

The code I use for filling the gaps with zero samples is as follows:

import           Data.Time (UTCTime)
import qualified Data.Map as M
import qualified Data.Set as S

-- Insert zero counts into date buckets that are missing a sample.
substZeroCount :: CountMap -> CountMap
substZeroCount m =
  M.map zeros m
  where
    allDates = M.fold (flip (foldr (\(date,_) -> S.insert date))) S.empty m

    zeros cs = M.toList $ S.fold insertMissing (M.fromList cs) allDates

    insertMissing date acc = if M.member date acc then acc else M.insert date 0 acc

It works and it's not even too long.  But somehow I don't feel happy about its readability.  It looks somehow too terse.  Maybe it's just about code layout.. or perhaps there'd be a nicer way to compose these functions.  Or maybe it's just because a lot happens in 3 lines of code. ;)

Any suggestions on how to make substZeroCount easier on the eyes?


texts: breacrumb directive for angular-ui-router

texts:
This is a simple directive that creates breadcrumbs on the fly for Angular.js pages using angular-ui-router

(function() {
  'use strict';
  var app, loaded;

  loaded = false;

  app = angular.module('uiBreadcrumbs', ['ui.router', 'ngSanitize']);

  app.directive('uiBreadcrumb', ['$state', '$rootScope', function($state, $rootScope) {
    return {
      restrict: 'E',
      transclude: true,
      link: function(scope, element, attrs) {
        var abstract;
        attrs.abstract = attrs.abstract ? attrs.abstract : false;
        abstract = JSON.parse(attrs.abstract);

        /*
         * watch for trasition success events
         * on state change success load breadcrumbs
         */
        $rootScope.$on('updateBreadCrumbs', function(event, trans) {
          var i, parentStates, stateArray;
          loaded = true;
          scope.$breadcrumbs = [];
          stateArray = [];
          parentStates = [];

          /*
           * gets all states
           */
          for (i in $state.$current.includes) {
            stateArray.push(i);
          }

          /*
           * get parent state details
           */
          for (i in stateArray) {
            if (stateArray[i] !== '') {
              if ($state.get(stateArray[i]).$$state().parent.self.name !== '') {
                parentStates.push($state.get(stateArray[i]).$$state().parent.self);
              }
            }
          }

          /*
           * if abstract is false
           * removes abstract states from breadcrumbs
           */
          if (!abstract) {
            for (i in parentStates) {
              if (!parentStates[i].abstract) {
                scope.$breadcrumbs.push(parentStates[i]);
              }
            }
          } else {
            scope.$breadcrumbs = parentStates;
          }

          /*
           * add current state to breadcrumbs
           */
          scope.$breadcrumbs.push($state.current);
        });
      },
      template: '
' + '
{{data.label || data.name}}
' + '
'
    };
  }]);

  app.run(['$rootScope', '$transitions', '$timeout', function($rootScope, $transitions, $timeout) {
    return $transitions.onSuccess({}, function(trans) {
      if (loaded) {
        $timeout(function() {
          $rootScope.$emit('updateBreadCrumbs', trans);
        }, 0);
      } else {
        $timeout(function() {
          $rootScope.$emit('updateBreadCrumbs', trans);
        }, 1000);
      }
    });
  }]);

}).call(this);

This directive creates breadcrumbs dynamically on page load and on any successful state change.

The directive works well with normal angular.js applications but does not work well with require.js apps. so I came up with a temporary solution that sets a loaded state. when the loaded state is false i.e., at page load the timeout is set for 1000 ms once the function is executed then the loaded state is set to true. then on the next time update happens with less time interval. I am not sure of things that I miss for require.js applications to load this properly.


texts:
I need to optimize this piece of code I made because this will run in real-time mode.

It's a matrix shifter that pulls downward and will neglect any transparent element.

Code:

void shiftDown(int col)
{
    int x = 0;  //transparent element
    int N = 5;  //size
    int i,j,k,l;

    for ( i = N - 1;i >= 0; --i )
    {
        if( map[i][col] == x )
        {
            for( j = i;j >= 0; --j )
            {
                if ( map[j][col] != x )
                {
                    for ( l = i, k = j;l >= 0; --l, --k )
                    {
                        map[l][col] = map[k][col];
                    }
                }
            }
        }
    }
}

Data:

(before)

0 2 3 2 0
0 1 4 0 1
1 2 2 0 3
2 1 0 0 4
4 3 1 1 3

(after)

0 2 0 0 0
0 1 3 0 1
1 2 4 0 3
2 1 2 2 4
4 3 1 1 3
    ^ ^

Other code

int map[][5] =
{
  {0, 2, 3, 2, 0},
  {0, 1, 4, 0, 1},
  {1, 2, 2, 0, 3},
  {2, 1, 0, 0, 4},
  {4, 3, 1, 1, 3}
};

void printMap();
void shiftDown(int col);

int main()
{
    cout << "before\n";
    printMap();

    for (int i = 0;i < 5; ++i)
    {
        shiftDown(i);
    }
    cout << "after\n";
    printMap();

    cin.get();
    return 0;
}

void printMap()
{
    for (int row = 0;row < 5; ++row)
    {
        for (int col = 0;col < 5; ++col)
        {
            cout << map[row][col] << '\t';
        }
        cout << endl << endl << endl << endl;
    }
}

Note: Looked at my comment again and I need to correct my error. Its int map[N][N] again. This will not work for M x N matrix.


texts: Upgrade Firefox Quantum with logging and version check

texts:
This is the updated version of the script first posted here.

Specifically, I first wanted to save the logs to a log file at "$HOME/.logs/ffupgrade.log", but I'm not sure whether that is good practice or whether I should log to syslog. When logging to a file, I would add another variable logfile at the beginning and adapt the functions like so (similarly for success and warning):

logfile="$HOME/.logs/ffupgrade.log"

error_exit() {
    msg="$1"
    echo -e "$(date) ${red}ERROR:${nocolor} ${msg}" 1>&2
    echo "$(date) ERROR: $msg" >> "$logfile"
    exit 1
}

I'm also wondering if it's better to only run the commands that need it with sudo or if I should rerun the whole script as sudo after prompting for the password like this:

if [[ "$EUID" != 0 ]]; then
    warning "Please run as root"
    sudo "$0" "$@"
fi

As always, any other comments are welcome as well.

#!/bin/bash

# firefox_upgrade - program to upgrade firefox quantum

red="\033[1;31m"
yellow="\033[1;33m"
green="\033[1;32m"
nocolor="\033[0m"

error_exit() {
    msg="$1"
    echo -e "$(date) ${red}ERROR:${nocolor} ${msg}" 1>&2
    logger "ERROR: $msg"
    exit 1
}

warning() {
    msg="$1"
    echo -e "$(date) ${yellow}WARNING:${nocolor} ${msg}"
    logger "WARNING: $msg"
}

success() {
    msg="$1"
    echo -e "$(date) ${green}SUCCESS:${nocolor} ${msg}"
    logger "SUCCESS: $msg"
}

ffbin="/opt/firefox"
fflink="/usr/bin/firefox-quantum"

ffpath=
fffile=

# check if path argument was provided
if [ $# -ne 1 ]; then
    error_exit "usage: $0 firefox_quantum_path"
fi

echo "Checking for root access.."
if [[ "$EUID" = 0 ]]; then
    success "already root"
else
    sudo -k # make sure to ask for password on next sudo
    if sudo true; then
        success "correct password"
    else
        error_exit "wrong password"
    fi
fi

# parsing path and filename
ffpath="$1"
fffile="${ffpath##*/}"

# check if input is a valid file
if [ ! -f "$ffpath" ]; then
    error_exit "Invalid file! Aborting."
fi

# check the firefox version
ffpref="${fffile%.*}"
ffversion="${ffpref//[^0-9]/}"
ffinstalled_version="$($fflink --version | sed 's/[^0-9]*//g')"

vind=0
if [[ "$ffversion" < "$ffinstalled_version" ]]; then
    warning "The version to be installed is lower than the installed version"
    vind=1
elif [[ "$ffversion" = "$ffinstalled_version" ]]; then
    warning "The version to be installed is the same as the installed version"
    vind=1
fi

if [[ "$vind" = 1 ]]; then
    echo "Do you want to continue anyway?"
    select yn in "Yes" "No"; do
        case $yn in
            Yes ) : ;;
            No ) exit;;
        esac
    done
fi

# removing previous install, if existent
if [ -e "$ffbin" ]; then
    sudo rm -rf "$ffbin"
    #mv "$ffbin" "$ffbin.old"
    success "removed previous install"
else
    warning "$ffbin doesn't exist."
fi

# removing previous symlink, if existent
if [ -L "$fflink" ]; then
    sudo rm -f "$fflink"
    success "removed previous symlink"
else
    warning "$fflink doesn't exist."
fi

# copying the tar to /opt
if ! sudo rsync -ah --progress "$ffpath" "/opt/$fffile"; then
    error_exit "Couldn't copy the tarball. Aborting."
fi
success "tarball copied"

# unpacking the tar if successfully changed directory
if ! sudo tar -jxvf "/opt/$fffile" -C /opt; then
    error_exit "Could not extract file! Aborting."
fi
success "tarball was extracted"

# if unpack was successful, set permissions, create symlink, and remove tar
sudo chmod 755 "$ffbin"
success "permissions set"
sudo ln -s "$ffbin/firefox" "$fflink"
success "symlink created"
sudo rm "/opt/$fffile"
success "tarball removed from /opt"
success "Firefox was upgraded"
```


texts: Wild and changing business rules implemented with functional programming

texts:
I attempted the Business Rules Kata. Here's a video overview.

However, I am not confident that going functional is a good strategy for the following objective:

  How can you tame these wild business rules? How can you build a system
  that will be flexible enough to handle both the complexity and the
  need for change? And how can you do it without condemning yourself to
  years and years of mindless support?

Is there an alternative FP approach that satisfies the objective stated above?

module PaymentSystem

(*Types*)
type ProductId =          ProductId of string
type MemberId =           MemberId  of string
type Email =              Email     of string
type Agent =              Agent
type RoyaltyDepartment =  RoyaltyDepartment

type PackingSlip = {
    MemberId:MemberId
    ProductId:ProductId
}

type PhysicalProducts =
    | Book
    | Video
    | Other

type MembershipType =
    | Membership of MemberId
    | Upgrade    of MemberId

type PaymentFor =
    | PhysicalProduct of PhysicalProducts * PackingSlip
    | Membership      of MembershipType

type PackingSlipOptions =
    | PackingSlip       of PackingSlip
    | DuplicateSlips    of PackingSlip
    | WithFirstAidVideo of PackingSlip

type PaymentResponse =
    | PackingSlip        of PackingSlipOptions
    | ActivateMembership of MemberId
    | UpgradeMembership  of MemberId
    | EmailOwner         of MembershipType
    | CommissionPayment  of Agent

(*Functions*)

let publish payload = ()       // Stub
let getAgent productId = Agent // Stub

let respondTo (payment:PaymentFor) =

    match payment with
    | PhysicalProduct     (kind , packingSlip) ->

        publish (CommissionPayment (getAgent packingSlip.ProductId))

        match kind with
        | Book  -> publish (DuplicateSlips    packingSlip)
        | Video -> publish (WithFirstAidVideo packingSlip)
        | Other -> publish packingSlip

    | Membership kind ->

        publish(EmailOwner kind)

        match kind with
        | MembershipType.Membership memberId -> publish(ActivateMembership memberId)
        | MembershipType.Upgrade    memberId -> publish(UpgradeMembership  memberId)


texts: Removing image records if no physical file exists

texts:
I have a working script that selects image fields in all tables and empty their values if the physical file doesnt exist.

    $query1 = "SELECT table_name,column_name
           FROM information_schema.columns
           WHERE table_schema='schemaname' AND column_name like '%image%' or column_name='video'";

$result1 = mysql_query($query1) or die(mysql_error() . " -- " . $query1);

while($row1 = mysql_fetch_row($result1)){
    if (!strpos($row1[0],'backup') > 0){
            $sql = "Select COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '".$row1[0]."' AND EXTRA = 'auto_increment'";
            $resultcol = mysql_query($sql);
            $rowcol = mysql_fetch_row($resultcol);

        $query2 = "SELECT " . $row1[1] . ", " .$rowcol[0] . "
               FROM " . $row1[0] . "
               WHERE " . $row1[1] . " != '' AND " . $row1[1] . " IS NOT NULL
               ";
        echo $query2 . "
";
        $result2 = mysql_query($query2) or die(mysql_error() . " -- " . $query2);

        while ($rowdb =  mysql_fetch_row($result2)){
            if (!strpos($rowdb[0],'facebook') > 0 && !file_exists($img_root.'/'.$rowdb[0])){
                $sql = "UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE " . $rowcol[0]. "= ".$rowdb[1];
                echo $sql . "

";
                $delete_count++;
                //mysql_query("UPDATE ".$row1[0]." SET ". $row1[1] . " = '' WHERE id = ".$row1["id"]);
            }
        }
    }
}

The script is working fine, but it takes time.  I was wondering if there is a smarter (more optimized) way to get the same function.


texts: Better alternative to $(this).off("click")

texts:
I have a notification system that looks like this:

function notificationMethod(message){
    // do stuff

    // once everything else is setup, attach a click handler to the "Okay" button
    $('#notificationOkay').click(function () {
        unBlockScreen();
        $(this).off("click"); // once they click the "Okay" button, remove the click event
    });
}

The reason that I'm putting the .click() handler in the notificationMethod() as opposed to the $(document).ready() is to be able to keep the notification code separate from the rest of the code that it has nothing to do with (other than it's on the same page). However, looking at my code it feels odd to have the .off("click") inside of the .click().

Is there anything particularly wrong with this approach?


texts: Speed up CSV reading code (vector of doubles)

texts:
I am trying to read a single-columned CSV of doubles into Java with a string header. It is 11 megabytes and takes over 15 minutes to read, which is clearly unacceptable. In R this CSV would take about 3 seconds to load.

This CSV file may contain strings so I am parsing it with this in mind.

The CSV reading method needs to return Vector<Double> due to reliance on this output by other parts of the application.

The issue is not due to the isNumber static method, since each call to that is taking 200 nanoseconds, thus contributing approximately 0.2 seconds to the 15 minutes of parsing time.

The Double.valueOf() only takes about 500 nanoseconds, so it is not that either.

csvData.add() is only taking 80 nanoseconds so it is not that.

private static Vector<Double> readTXTFileSingle(String csvFileName) throws IOException {
    String line = null;
    BufferedReader stream = null;
    Vector<Double> csvData = new Vector<Double>();

    try {
        stream = new BufferedReader(new FileReader(csvFileName));
        while ((line = stream.readLine()) != null) {
            String[] splitted = line.split(",");
            if( ! NumberUtils.isNumber(splitted[0])) {

                continue;
            }

            Double dataLine = Double.valueOf(splitted[0]);
            csvData.add(dataLine);

        }
    } finally {
        if (stream != null)
            stream.close();
    }
    return csvData;
}


texts: Auto filter data from worksheet and create vlookup using a different worksheet

texts:
I'm working on a large VBA project for work (around 1000+ lines of vba code) This module is called within another module where I disable everything possible like screen updating, events and setting calculation to manual to improve speed, yet this still seems to run slowly when I'm working with sheets with over 60,000 rows.

What this code does, is filter a row in one sheet and copy paste it into another sheet. Then use the data from this to vlookup onto another sheet. I don't understand the syntax of index match, otherwise I could have eliminated the cut/paste option to move the column on the right for the vlookup to speed it up.

I suspect a few other elements in this code chunk are slowing it down too. Could you please help me identify what is causing the issue? Is it the autofilter?

Sub AdgroupName()

Dim LrowBlk As Long
LrowBlk = Sheets("Bulk Sheet").Cells(Rows.Count, "H").End(xlUp).Row
Sheets("Bulk Sheet").AutoFilterMode = False
Sheets("Bulk Sheet").Range("H3:I3").AutoFilter field:=2, Criteria1:="AdGroup"
ActiveWorkbook.Sheets("Bulk Sheet").Range("H3:K3" & LrowBlk).SpecialCells(xlCellTypeVisible).Copy
Worksheets("Adgroup List").Paste Destination:=Worksheets("Adgroup List").Range("A1")
ActiveWorkbook.Sheets("Bulk Sheet").Range("P3:P" & LrowBlk).SpecialCells(xlCellTypeVisible).Copy
Worksheets("Adgroup List").Paste Destination:=Worksheets("Adgroup List").Range("E1")
With Sheets("Adgroup List")
    .Columns("C:C").Cut
    .Columns("E:E").Insert Shift:=xlToRight
 End With
Application.CutCopyMode = False
Dim ws As Worksheet
Dim LrowSTR As Long
Set ws = ThisWorkbook.Sheets("Search Term Report")
LrowSTR = Sheets("Search Term Report").Cells(Rows.Count, "H").End(xlUp).Row
Dim Strformulas(1 To 3) As Variant

With ws
    Strformulas(1) = "=VLOOKUP($K4,'Adgroup List'!$C:$D,2,0)"
    Strformulas(2) = "=VLOOKUP($K4,'Adgroup List'!$C:$E,3,0)"
    .Range("AJ4:AK4").Formula = Strformulas
    .Range("AJ4:AK" & LrowSTR).FillDown
    .Range("AJ3").Value = "Campaign ID"
    .Range("AK3").Value = "AdGroup Name"
    End With
     Sheets("Bulk Sheet").AutoFilterMode = False
     Sheets("Adgroup List").AutoFilterMode = False
     End Sub


texts: Return different type of response based on Accept header

texts:
I'm a novice to Scala and Akka-Http and am experimenting with Akka-Http for writing rest services. I have to return JSON or protobuf based on the Accept-Header.

optionalHeaderValueByName("Accept"){ contentType =>
  if(contentType == Some(protoEncode)) {
    complete {
      NewsService.getNewsList().map {
        case stories: List[Story] =>    HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray))
      }
    }
  } else {
      complete {
        NewsService.getNewsList().map {
          case stories: List[Story] => StoryList(stories)
          }
        }
  }

As you can see, the code repetition is happening. Can anyone suggest what could be the best way to optimise and generalise the design to avoid such a situation?


texts: Breaking up a PHP class between a master class and subclasses

texts:
I have a huge class taking care of companies informations in my app. Arrived at 4000 lines of code (!), I finally decided to break it up. However I am not too sure if the way I am doing this is the best. For example I had shareholders functions in the company class taking care of returning one or all, editing, adding, and deleting shareholders. And I had a whole bunch of other functions built in the same way for representatives, warrantors, offices, etc...

I did a new company class with some basic functions that I want shared with all subclasses, and the idea was to call from within this class the specialized subclasses.

However I would like my shareholder constructor to be protected in a way that it can only be called through the company class, which is impossible with the structure I chose. Also, I shouldn't be allowed to instantiate a new shareholder from the shareholder class which again I can with this construction.

I think I should be using traits and abstract class to achieve this, but I am not sure how to. Sorry if this is a bit confused, but any help is welcome.

class company{
  private $id;
  protected $db;

  public function __construct($id, $db){
    $this->id = $id;
    $this->db = $db;
  }

  public function get_id(){
    return $this->id;
  }
  ...
  public function shareholder(){
    if ( !isset($this->shareholder) ){
      $this->shareholder = new adherent\shareholder($this->get_id(), $this->db);
    }
    return $this->shareholder;
  }
}

// This will be implemented for all subclasses dealing with lists
interface _list {

  public function count($incl_deleted = false);

  public function get($id);

  public function get_all($incl_deleted = false);

  public function insert($cfg);

  public function update($cfg);

  public function delete($id);

}

class link extends company implements _list{
  public function count($incl_deleted = false){
    ...
  }

  public function get($id){
    ...
  }

  public function get_all($incl_deleted = false){
    ...
  }

  public function insert($cfg){
    ...
  }

  public function update($cfg){
    ...
  }

  public function delete($id){
    ...
  }
}

class shareholder extends link{

  public function insert($cfg)
  {
    // Specific to this class
    if ( is_array($cfg) &&
      isset($cfg['parts'], $cfg['id_tiers']) &&
      \bbn\str\text::is_number($cfg['parts']) &&
      ($cfg['parts'] > 0) ){
      return parent::insert($cfg);
    }
    $this->error("Problème dans la configuration pour l'insertion");
  }

  public function update($cfg)
  {
    // Specific to this class
    if ( is_array($cfg) &&
      isset($cfg['id'], $cfg['parts'], $cfg['id_tiers']) &&
      \bbn\str\text::is_number($cfg['parts']) &&
      ($cfg['parts'] > 0) ){
      return parent::update($cfg);
    }
    $this->error("Problème dans la configuration pour l'update");
  }
  // Other functions use the link class
}


texts: If a regex match is found assign it to a variable

texts:
I am searching a string for a pattern that matches Material=. Some examples are Material=ABC123,Color=444555, Material=332212,Color=192929
I am new to C# and I learned about capture groups but I am wondering if its possible to do it in a cleaner way?

var pattern = new Regex("(?<label>Material)=(?<value>[^,]+)");
Match match = pattern.Match(Row2.Attributes);
var materialCode = (match.Success) ? match.Groups["value"].Value : "NA";

Edit:

I store materialCode into a database so it can't be null. If a value isn't found it has to be "NA". Also there are lots of combos which is why I specify I need whatever value after the = but before the , in the regex


texts:
I'm working on a inventory system for a rpg. I want to be able to compare items, restrict access for specific items(i.e. consumables) for specific inventory slots(i.e. leg, head), summarize items based on their attributes and make it easy to introduce new types of items.

What is a good structure to manage these requirements?

I tried the following, but I have my doubts about it (I shorten it, to make it more readable):

class Attributes{
    public:
        int agility = 0;
};

class Stackable{};

class Inventoryable : Entity{
    public:
        string name = "";
};

class Wearable : Itemable, Attributes{};
class Consumable : Itemable, Stackable{};
class Armor : Wearable{};
class Weapon : Wearable{};
class Cloth : Armor{};
class Pike : Weapon{};

class Item : Inventoryable{
    private:
        Inventoryable inv_;
    public:
        Item(Inventoryable inv_type) : inv_(inv_type) {};
}

int main(void) {
    Item socks = new Item(Cloth);
    socks.name = "Stinky Socks"; //Inventoryable
    socks.agility = 10; //Attributes
}


texts: Checking some rules before a Telegram bot replies to a message

texts:
So far, I've created a couple of programs, and the issue that comes up is how ugly and non-scalable they look.

For example, currently I'm working on a telegram bot. Before replying to a message I need to check that the message follows a couple of rules. In order to minimize the number of if/elif statements. I've even created a couple of functions that return True or False if my condition is met, but the code still looks very ugly:

# only if messages are not empty and description has a hyphen
if channel and (description and description[0] == '-'):

    if is_channel(channel) and is_length(description):

        if channel_is_size(channel):
            bot.reply_to(message, replies.success_add.format(channel))
            write_results(' '.join(message_words[1:]))
        else:
            bot.reply_to(message, replies.small_chan.format(min_channel_size))

    else:
        bot.reply_to(message, replies.enter_chan)

elif not description and channel:
    bot.reply_to(message, replies.enter_desc_error)
else:
     bot.reply_to(message, replies.enter_addmessage_error) # if empty

As you can see, these are the conditions for which the user message will be accepted into the database (it's a text file), and this can be seen right under the triple nested if statements.
I've tried to make this code look nicer many times over, but now it seems very messy and if I would want to add more conditions, which I am planning to do, these nested statements will grow out of proportion.


texts:
I implemented the intersection of two (convex) polygons in C++. It finds the polygon in the intersection like in this image.
Looking for any and all feedback. I left the logic for line intersection and point containment out.
#include <algorithm>
#include <cmath>
#include <iostream>
#include <optional>

using std::atan2;
using std::move;
using std::optional;
using std::vector;
using std::sort;

struct Point {
  double x;
  double y;
};

struct LineSegment {
  Point u;
  Point v;
};

// Returns the intersection point of l1 and l2 if it exists, nullopt otherwise.
// Unimplemented.
optional<Point> lineIntersection(const LineSegment& l1, const LineSegment& l2);

class Polygon {
public:
  Polygon(const vector<Point>& points) : points_{points} {};
  Polygon(const vector<Point>&& points) : points_{move(points)} {};

  // Returns true if point is in Polygon, false otherwise.
  // Unimplemented.
  bool contains(const Point& point) const;

  static Polygon intersect(const Polygon& p1, const Polygon& p2) {
    vector<Point> points;
    for (size_t i = 0; i < p1.points_.size(); ++i) {
      // Add points of p1 contained in p2.
      if (p2.contains(p1.points_[i])) {
        points.emplace_back(p1.points_[i]);
      }
      for (size_t j = 0; j < p2.points_.size(); ++j) {
        // Add points of intersection.
        auto intersection = lineIntersection(
          LineSegment{p1.points_[i], p1.points_[(i+1) % p1.points_.size()]},
          LineSegment{p2.points_[j], p2.points_[(j+1) % p2.points_.size()]});
        if (intersection != nullopt) {
          points.emplace_back(move(intersection.value()));
        }
      }
    }

    // Add points of p2 contained in p1.
    for (size_t i = 0; i < p2.points_.size(); ++i) {
      if (p1.contains(p2.points_[i])) {
        points.emplace_back(p2.points_[i]);
      }
    }

    // Sort into counter-clockwise order.
    sort(points.begin(), points.end(), [](Point a, Point b){ return atan2(a.y, a.x) > atan2(b.y, b.x); });
    return Polygon{points};
  }

private:
  vector<Point> points_;
};


texts:
I'd like a review of this implementation of Async in ASP.NET 2.0 web form page below.  Let me know if I am missing something.

AsyncPagesASPNET20.aspx

<%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="AsyncPagesASPNET20.aspx.cs" Inherits="AsyncPagesASPNET20" %>

AsyncPagesASPNET20.aspx.cs

public partial class AsyncPagesASPNET20 : System.Web.UI.Page
{
    private string queryCustomerSelect = "SELECT FirstName, LastName FROM SalesLT.Customer";
    private DataAccess dataAccess = new DataAccess(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.PreRenderComplete += AsyncPage_PreRenderComplete;
            AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
        }
    }

    private void EndAsyncOperation(IAsyncResult ar)
    {
        Trace.Write("EndAsyncOperation...");
        this.dataAccess.EndAsyncSelect(ar);
    }

    private IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object extraData)
    {
        Trace.Write("BeginAsyncOperation...");
        return dataAccess.BeginAsyncSelect(sender, e, cb, extraData, this.queryCustomerSelect);
    }

    void AsyncPage_PreRenderComplete(object sender, EventArgs e)
    {
        this.GridView1.DataSource = this.dataAccess.reader;
        this.GridView1.DataBind();
    }

    public override void Dispose()
    {
        this.dataAccess.Dispose();
    }
}

DataAccess.cs

public class DataAccess : IDisposable
{
    string connectionString = string.Empty;
    private SqlConnection connection;
    private SqlCommand command;
    public SqlDataReader reader;
    public DataAccess(string connectionString)
    {
        this.connectionString = connectionString;
        this.connection = new SqlConnection(this.connectionString);
        this.command = new SqlCommand();
    }

    public IAsyncResult BeginAsyncSelect(object sender, EventArgs e, AsyncCallback cb, object extraData, string query)
    {
        this.command.CommandText = query;
        this.command.CommandType = CommandType.Text;
        this.command.Connection = this.connection;
        this.connection.Open();
        return this.command.BeginExecuteReader(cb, extraData);
    }

    public void EndAsyncSelect(IAsyncResult ar)
    {
        this.reader = this.command.EndExecuteReader(ar);
    }

    public SqlDataReader SelectSync(string query)
    {
        this.command.CommandText = query;
        this.command.Connection = connection;
        this.connection.Open();
        this.command.Connection = connection;
        return this.command.ExecuteReader();
    }

    #region IDisposable Members

    public void Dispose()
    {
        if (this.connection != null)
        {
            this.connection.Close();
        }
    }

    #endregion
}


texts: First project in Javascript: NearestNeighbor Calculator

texts:
I just finished my first project in Javascript. It takes an array of locations (with coordinates on position 6 and 7) as Input, then the first location is checked against all other locations. After that it takes the closest neighbor and adds it to the route. Then it takes the coordinates of the neighbor which it just found and does same for it (excluding locations that already have a connection). In the end it returns to the starting point. Please give me some hints how i can write better, cleaner and more readable code. Any feedback is appreciated.

var listCoordinates = [
  [1, "München", "Robert-Bürkle-Straße", "1", 85737, "Ismaning", 48.229035, 11.686153, 524, 854],
  [2, "Berlin", "Wittestraße", "30", 13509, "Berlin", 52.580911, 13.293884, 648, 302],
  [3, "Braunschweig", "Mittelweg", "7", 38106, "Braunschweig", 52.278748, 10.524797, 434, 341],
  [4, "Bretten", "Edisonstraße", "2", 75015, "Bretten", 49.032767, 8.698372, 276, 747],
  [5, "Chemnitz", "Zwickauer Straße", "16a", 9122, "Chemnitz", 50.829383, 12.914737, 622, 525],
  [6, "Düsseldorf", "Gladbecker Straße", "3", 40472, "Düsseldorf", 51.274774, 6.794912, 138, 455]
];
//Haversine formula: calulate distance between two locations
const haversineDistance = ([lat1, lon1], [lat2, lon2], isMiles = false) => {
  const toRadian = angle => (Math.PI / 180) * angle;
  const distance = (a, b) => (Math.PI / 180) * (a - b);
  const RADIUS_OF_EARTH_IN_KM = 6371;
  const dLat = distance(lat2, lat1);
  const dLon = distance(lon2, lon1);
  lat1 = toRadian(lat1);
  lat2 = toRadian(lat2);
  //Haversine Formula
  const a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
  const c = 2 * Math.asin(Math.sqrt(a));
  let finalDistance = RADIUS_OF_EARTH_IN_KM * c;
  if (isMiles) {
    finalDistance /= 1.60934;
  }
  return finalDistance;
};
//heuristic strict nearest neighbor (points that already have a connection do not get calculated)
function nearestNeighbor(coordinates) {
  var route = {
    msg: '',
    distance: 0,
    route: [0]
  }
  var currentPoint = 0;
  for (var i = 0; i <= coordinates.length - 2; i++) {
    var nearestNeighbor = {
      key: 0,
      distance: 0
    }
    var pointaLat = coordinates[currentPoint][6],
      pointaLon = coordinates[currentPoint][7];
    for (var j = 0; j <= coordinates.length - 1; j++) {
      if (j != currentPoint) {
        if (!route.route.includes(j)) {
          var pointbLat = coordinates[j][6],
            pointbLon = coordinates[j][7];
          var currentDistance = haversineDistance([pointaLat, pointaLon], [pointbLat, pointbLon], 0);
          if (nearestNeighbor.distance === 0 || nearestNeighbor.distance > currentDistance) {
            nearestNeighbor.key = j;
            nearestNeighbor.distance = currentDistance;
          }
        }
      }
    }
    route.distance += nearestNeighbor.distance;
    route.route.push(nearestNeighbor.key)
    currentPoint = nearestNeighbor.key;
  }
  //return to start point
  var pointaLat = coordinates[0][6],
    pointaLon = coordinates[0][7],
    pointbLat = coordinates[route.route[route.route.length - 1]][6],
    pointbLon = coordinates[route.route[route.route.length - 1]][7];
  route.distance += haversineDistance([pointaLat, pointaLon], [pointbLat, pointbLon], 0);
  route.route.push(0);
  route.distance = Math.round((route.distance + Number.EPSILON) * 100) / 100;
  route.msg = "Die kürzeste Strecke beträgt " + route.distance + " km";
  return route;
}

console.log(nearestNeighbor(listCoordinates));


texts: Choosing a movement strategy based on the type of chess piece

texts:
PawnMovement ... KingMovement are of type Movement. This is implementation of strategy pattern. Basing on actual value of PieceType I want to choose proper strategy. How to avoid long if/else statements or switch?

    PieceType pieceType;
    if(this.board.getPieceAt(from) != null) {
        pieceType = this.board.getPieceAt(from).getType();
    } else {
        throw new InvalidMoveException();
    }

    if (pieceType == PieceType.PAWN) {
        contextMovement.setContext(new PawnMovement());
    } else if (pieceType == PieceType.ROOK) {
        contextMovement.setContext(new RookMovement());
    } else if (pieceType == PieceType.KNIGHT) {
        contextMovement.setContext(new KnightMovement());
    } else if (pieceType == PieceType.BISHOP) {
        contextMovement.setContext(new BishopMovement());
    } else if (pieceType == PieceType.QUEEN) {
        contextMovement.setContext(new QueenMovement());
    } else if (pieceType == PieceType.KING) {
        contextMovement.setContext(new KingMovement());
    }
    return contextMovement.executeMovement(from, to, board);


texts:
I have the following constructor

 /**
 * @param codePath path to player's code. If ends in '/' it assumes the code is in .class'es in
 *            a directory; otherwise assumes a jar
 * @throws PlayerException if there is a problem loading the code
 */
public Player(File codePath) throws PlayerException {
if (!codePath.exists() || !codePath.canRead()) {
    throw new IllegalArgumentException("Path is invalid: " + codePath
        + ". It can't be read or it doesn't exist");
}

if (Thread.currentThread().getPriority() < ROBOTS_MAX_PRIORITY) {
    throw new PlayerException("Robot priority cannot be greater than game's");
}

try {
    loader = new URLClassLoader(new URL[] { codePath.toURI().toURL() });
    InputStream stream = loader.getResourceAsStream(PLAYER_PROPERTIES_FILE);

    if (stream == null) {
    throw new PlayerException("Player Specification File not found: " + codePath + "!"
        + PLAYER_PROPERTIES_FILE);

    } else {
    Properties playerInfo = new Properties();
    playerInfo.load(stream);

    // read parameters
    author = playerInfo.getProperty("Author", "Unknown programmer");

    teamName = playerInfo.getProperty("Team", "Unknown team");

    robotsThreads = new ThreadGroup(PLAYERS_GROUP, teamName + " Threads");
    robotsThreads.setMaxPriority(ROBOTS_MAX_PRIORITY);

    String banksList = playerInfo.getProperty("Banks");

    if (banksList == null) {
        throw new PlayerException("Error loading configuration property: No banks definition found");
    }
    String[] banksClasses = banksList.split(",");

    teamId = getNextTeamId();
    teamIds.add(teamId);

    banks = loadBanks(loader, banksClasses);

    log.info("[Player] Successfully loaded Player: {}. Banks found = {}", this, banksClasses.length);
    }

} catch (ClassCastException | IOException | ClassNotFoundException | InstantiationException
    | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException exc) {
    closeClassLoader();
    throw new PlayerException("Error loading player's code", exc);

} catch (PlayerException exc) {
    closeClassLoader();
    throw exc;
}

}

The problem is that the fact that it takes a File makes it hard to test, i don't want to create dummy files. My usual technique is to find what the logic does with the File and then create a constructor that takes that actual object and use that constructor in the unit tests with the original constructor calling the new one. In this case it can be seen that what's needed from the File is the loader so I tried creating a package-protected constructor

Player(URLClassLoader pLoader, String codePath) throws PlayerException { .. } //the second parameter is just used for logging

However, the problem is that I obviously can't do something like this

public Player(File codePath) throws PlayerException, MalformedURLException {
  if (!codePath.exists() || !codePath.canRead()) {
    throw new IllegalArgumentException("Path is invalid: " + codePath
        + ". It can't be read or it doesn't exist");
    }
this(new URLClassLoader(new URL[] { codePath.toURI().toURL() }), "test");

}

i.e. first validate the File and then invoke the other constructor, because this() calls need to be the first in the method.
I also tried extracting the initialization code into a separate method that then maybe i could test by itself, but the variables to initialize (author, teamName, etc) are final, so the compiler again complains. I'm trying to leave those variables as final.

Can anyone suggest another way to refactor this so that i can test the logic that populates the player's data at least. For the full class see here


texts: Querying list of servers with PS to report on Scheduled Tasks

texts:
I work in a Windows environment where Scheduled Tasks have never been documented or kept up with, leaving us with about 150 servers that have a random smattering of tasks. I am attempting to construct something that will query specific information about these tasks and output them in a pretty format that I can sort through.

Here is what I have currently cobbled together:

Import-Module ActiveDirectory
$VerbosePreference = "continue"
$list = (Get-ADComputer -LDAPFilter "(&(objectcategory=computer)(OperatingSystem=*server*))").Name
$logfilepath = "$home\Desktop\TasksLog.txt"
$ErrorActionPreference = "SilentlyContinue"

invoke-command -ComputerName $list -ScriptBlock { $sched = New-Object -Com "Schedule.Service"
$sched.Connect()
$out = @()
$sched.GetFolder("\").GetTasks(0) | % {
    $xml = [xml]$_.xml
    $out += New-Object psobject -Property @{
        "Name" = $_.Name
        "Status" = switch($_.State) {0 {"Unknown"} 1 {"Disabled"} 2 {"Queued"} 3 {"Ready"} 4 {"Running"}}
        "NextRunTime" = $_.NextRunTime
        "LastRunTime" = $_.LastRunTime
        "Author" = $xml.Task.Principals.Principal.UserId
    }
}

$out | fl Name,Status,NextRunTime,LastRunTime,Author, } | Out-File $logfilepath

The "pretty" part is a work in progress. However, if I am correct, this should query a list of server names from AD and then invoke the command on all of them, then output the results to the designated file. I have tested with one server...

$list = "Server1"

...but am hesitant to attempt to invoke these all at once. I am not even sure if this is the correct/most effective way of passing a list of servers to the invoke-command cmdlet.


texts: Find missing numbers in a range, with duplicate numbers in a sorted array

texts:
Suggestions for cleanup and optimization request.

This question is a follow-up question on this post.

Lets assume the range of

  1, 2, 3, 4.

This function takes in an array of repeated elements, [1,1,4,4] and the output is [2, 3].

The question marked as duplicate takes an input of [1, 4] and output is [2, 3].
While output is same, the input differs.
Please make a note of this difference between two questions causing confusion.

final class Variables {
    private final int x;
    private final int y;

    Variables(int x2, int y2) {
        this.x = x2;
        this.y = y2;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override public String toString()  {
        return "x = " + x + " y = " + y;
    }
}

    public final class FindMissingRepeating {

        /**
         * Takes an input a sorted array with only two variables that repeat once. in the
         * range. and returns two variables that are  missing.
         *
         * If any of the above condition does not hold true at input the results are unpredictable.
         *
         * Example of input:
         * range: 1, 2, 3, 4
         * input array [1, 1, 4, 4]
         * the variables should contain 2 missing elements ie 2 and 3
         *
         * @param a : the sorted array.
         */
        public static Variables sortedConsecutiveTwoRepeating (int[] a, int startOfRange) {
            if (a == null) throw new NullPointerException("a1 cannot be null. ");

            int low = startOfRange;
            int high = low + (a.length - 1);

            int x = 0;
            int i = 0;
            boolean foundX = false;

            while  (i < a.length) {
                if (a[i] < low) {
                    i++;
                } else {
                    if (a[i] > low) {
                        if (foundX) {
                            return new Variables(x, low);
                        } else {
                            x = low;
                            foundX = true;
                        }
                    }
                    low++;
                    i++;
                }
            }

            int val = foundX ? x : high - 1;
            return new Variables(val, high);
         }

        public static void main(String[] args) {
            int[] ar1 = {1, 2, 2, 3, 4, 4, 5};
            Variables v1 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar1, 1);
            System.out.println("Expected x = 6, y = 7 " + v1);

            int[] ar2 = {2, 2, 4, 4, 5, 6, 7};
            Variables v2 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar2, 1);
            System.out.println("Expected x = 1, y = 3 " + v2);

            int[] ar3 = {3, 3, 4, 4, 5, 6, 7};
            Variables v3 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar3, 1);
            System.out.println("Expected x = 1, y = 2 " + v3);

            int[] ar4 = {1, 3, 3, 4, 4, 6, 7};
            Variables v4 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar4, 1);
            System.out.println("Expected x = 2, y = 5 " + v4);
        }
    }


texts:
I've been wondering about simple collision in C++ for a while now, and I've tried to make up my own code.

The code posted below works when walls are placed in a perfect rectangle around the player. However, once you randomly place them in the array, as in the code, weird inconsistencies seem to occur. Sometimes the player collides, sometimes the player doesn't.

If anyone would be as kind as to point out what the error is, I'd be much appreciated. In a clear step by step manner, if you would: I'm very new to this and chances are small that I can make the logical steps of thought necessary to successfully implement your suggestions.

#include "string.h"
#include "surface.h"
#include "stdlib.h"
#include "template.h"
#include "game.h"

using namespace Tmpl8;

int pacmanPosX = 32;
int pacmanPosY = 32;
int indexX;
int indexY;

bool colR;
bool colL;
bool colU;
bool colD;

Sprite pacman (new Surface( "assets/pacmanLeft.png"), 1);

Surface* tileSet[3];

int levelMap[8][8] =
{{1,1,1,1,1,1,1,1},
 {1,0,0,0,0,0,0,1},
 {1,0,0,0,0,1,0,1},
 {1,0,0,1,0,0,0,1},
 {1,0,0,0,1,0,0,1},
 {1,1,0,0,1,1,1,1},
 {1,0,0,0,0,0,1,1},
 {1,1,1,1,1,1,1,1}};

void Game::Init()
{
   // put your initialization code here; will be executed once
   tileSet[0] = new Surface( "assets/pacmanFloor.png" ); // Sets up data for tileSet
   tileSet[1] = new Surface( "assets/pacmanWall.bmp" );
   tileSet[2] = new Surface( "assets/pacmanCookie.png" );

}

void Game::Tick( float a_DT )
{
    m_Screen->Clear( 0 );

     for (indexX = 0; indexX < 8; indexX++)
    {
        for (indexY = 0; indexY < 8; indexY++)
        {
            int tile = levelMap[indexY][indexX];
            tileSet[tile]->CopyTo( m_Screen, indexX * 32, indexY * 32 );
        }
    }

    pacman.Draw(pacmanPosX, pacmanPosY, m_Screen);

    //Defining collision requirements for walls//

    if(levelMap[(pacmanPosX+32)/32][pacmanPosY/32] == 1) //Right collision
    {
        colR = true;
    }else colR = false;

    if(levelMap[(pacmanPosX-2)/32][pacmanPosY/32] == 1) //Left collision
    {
        colL = true;
    }else colL = false;

    if(levelMap[pacmanPosX/32][(pacmanPosY-2)/32] == 1) //Upward collision
    {
        colU = true;
    }else colU = false;

    if(levelMap[pacmanPosX/32][(pacmanPosY+32)/32] == 1) //Downward collision
    {
        colD = true;
    }else colD = false;

    //Setting Up Controls//

    if (GetAsyncKeyState(VK_RIGHT) && colR == false){pacmanPosX += 2;}
    if (GetAsyncKeyState(VK_LEFT) && colL == false){pacmanPosX -= 2;}
    if (GetAsyncKeyState(VK_UP) && colU == false){pacmanPosY -= 2;}
    if (GetAsyncKeyState(VK_DOWN) && colD == false){pacmanPosY += 2;}

    Sleep( 10 );
}


texts:
Pretty printer in ABAP does not take care of all my aligning need, so I wrote a small JS script that tabulates/aligns with a custom string. It contains HTML, CSS and script in 1 file because this is a small tool.

Link : https://github.com/konijn/aligner

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Aligner</title>

Aligner

      Editor:

      <textarea id="editor">
  DATA : wa_ekpo TYPE ekpo.
  DATA : wa_eket TYPE eket.
  DATA : wa_decision TYPE zrms_performance_decision.
  DATA : wa_receipt_item TYPE zrmt_rcpt_items.
  DATA : wa_container TYPE zrmt_rcpt_hdrs_c.
      </textarea>

      Align at
      <input type="text" id="token" class="emo" value="TYPE">
      <button type="button" id= "button">Align</button>

      Output:

      <textarea id="output"></textarea>

Please review for style and maintainability.


texts:
I've been studying compiler construction theory. Right now, I'm studying Finite State Automaton and I've tried to create my own implementation. I'm not sure if my implementation is right.

<?php
/**
 * FINITE STATE AUTOMATON
 * ======================
 * - states
 * - starting state
 * - accept state
 * - transition table
 *
 * Input string examples:
 * 10112 - Accepted
 * 222 - Rejected
 *
 * Diagram: http://i.imgur.com/pDl1VZM.png
 */
$s1 = 'S1';
$s2 = 'S2';

$states = [];
$starting_state = $s1;

$transition_table = [
    'S1' => [
        '2' => 'S3',
        '1' => 'S1',
        '0' => 'S2',
    ],
    'S2' => [
        '1' => 'S1',
        '0' => 'S2',
    ],
    'S3' => [],
];
$input_string = '10112';

$current_state = $starting_state;
foreach (str_split($input_string) as $character) {
    if (isset($transition_table[$current_state][$character])) {
        $current_state = $transition_table[$current_state][$character];
        $states[] = $current_state;
    }
}
if (count($states) == strlen($input_string)) {
    echo 'Accepted';
} else {
    echo 'Rejected';
}
echo PHP_EOL;

Did I get the whole idea? Are there something that I've missed?

Is this FSA thing related to regular expressions? It seems to be similar.


texts: Codility's BinaryGap: Hardware-aware answer

texts:
This is a well-known question, which some others have posted about on this site.

Here's my first shot following a state machine approach:

int solution(int N) {
    int longestSizeGap{};
    int sizeGap{};
    bool gapStarted{};
    while (N > 0) {
        int remainder{N%2};
        switch (remainder) {
            case 0: {
                if (gapStarted) {
                    sizeGap++;
                }
                break;
            }
            case 1: {
                if (!gapStarted) {
                    gapStarted = true;
                } else {
                    if (sizeGap > longestSizeGap) {
                        longestSizeGap = sizeGap;
                    }
                }
                sizeGap = 0;
                break;
            }
        }
        N /= 2;
    }
    return longestSizeGap;
}

How could I improve this solution to be more "hardware-aware", i.e. what about branch prediction and pipelining, cache misses and page faults, memory hierarchy and data locality? How could I improve my code to just run better?


texts: Printing a string in NASM Win16 Assembly

texts:
A small script that simply prints a given string. It's an improved snippet that combines some recommendations given in my post on string helper functions.

org 100h

mov     si, hello
call    puts
ret

puts:
    jmp     .run
.putc:
    mov     ah, 0Eh
    mov     bx, 7
    int     10h
.run:
    lodsb
    cmp     al, 0
    jne     .putc
    ret

hello db "Hello World!", 0


texts: Consuming an ASP.NET Web API call in an MVC controller

texts:
In a new project I am creating for my work, I am creating a fairly large ASP.NET web API. The API will be in a separate Visual Studio solution that also contains all of my business logic, database interactions, and Model classes.

In the test application I am creating (which is ASP.NET MVC4), I want to be able to hit an API URL I defined from the control and cast the return JSON to a Model class. The reason behind this is that I want to take advantage of strongly typing my views to a Model. This is all still in a proof of concept stage, so I have not done any performance testing on it, but I am curious if what I am doing is a good practice, or if I am crazy for even going down this route.

Here is the code on the client controller:

public class HomeController : Controller
{
    protected string dashboardUrlBase = "http://localhost/webapi/api/StudentDashboard/";

    public ActionResult Index() //This view is strongly typed against User
    {
        //testing against Joe Bob
        string adSAMName = "jBob";
        WebClient client = new WebClient();
        string url = dashboardUrlBase + "GetUserRecord?userName=" + adSAMName;
        //'User' is a Model class that I have defined.
        User result = JsonConvert.DeserializeObject<User>(client.DownloadString(url));
        return View(result);
    }
. . .
}

If I choose to go this route, another thing to note is I am loading several partial views in this page (as I will also do in subsequent pages). The partial views are loaded via an $.ajax call that hits this controller and does basically the same thing as the code above:

Instantiate a new WebClient
Define the URL to hit
Deserialize the result and cast it to a Model Class

So it is possible (and likely) I could be performing the same actions 4-5 times for a single page.

Is there a better method to do this that will:

Let me keep strongly typed views
Do my work on the server rather than on the client (this is just a preference since I can write C# faster than I can write JavaScript)


texts:
Following this idea for pretty printing of numpy ndarrays, I have developed a very primitive prototype:

def ndtotext(A, w=None, h=None):
    if A.ndim==1:
        if w == None :
            return str(A)
        else:
            s ='['+' '*(max(w[-1],len(str(A[0])))-len(str(A[0]))) +str(A[0])
            for i,AA in enumerate(A[1:]):
                s += ' '*(max(w[i],len(str(AA)))-len(str(AA))+1)+str(AA)
            s +='] '
    elif A.ndim==2:
        w1 = [max([len(str(s)) for s in A[:,i]])  for i in range(A.shape[1])]
        w0 = sum(w1)+len(w1)+1
        s= u'\u250c'+u'\u2500'*w0+u'\u2510' +'\n'
        for AA in A:
            s += ' ' + ndtotext(AA, w=w1) +'\n'
        s += u'\u2514'+u'\u2500'*w0+u'\u2518'
    elif A.ndim==3:
        h=A.shape[1]
        s1=u'\u250c' +'\n' + (u'\u2502'+'\n')*h + u'\u2514'+'\n'
        s2=u'\u2510' +'\n' + (u'\u2502'+'\n')*h + u'\u2518'+'\n'
        strings=[ndtotext(a)+'\n' for a in A]
        strings.append(s2)
        strings.insert(0,s1)
        s='\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings)))
    return s

for example:

shape = 4, 5, 3
C=np.random.randint(10000, size=np.prod(shape)).reshape(shape)
print(ndtotext(C))

┌┌────────────────┐┌────────────────┐┌────────────────┐┌────────────────┐┐
│ [9298 4404 1759]  [5426 3488 9267]  [8884 7721  579]  [6872 4226 1858] │
│ [6723  271 8466]  [9885 6760 8949]  [ 295 7422 5659]  [5322 4239 7446] │
│ [7156 6077 9390]  [2712 6379 2832]  [6956  626 5534]  [ 142 4090 6390] │
│ [9377 9033 1953]  [8986 3791 4538]  [2466 8572  662]  [1528 8922 9656] │
│ [1449 7319 3939]  [7350 9619  928]  [7542 4704 1477]  [ 980 6037  869] │
└└────────────────┘└────────────────┘└────────────────┘└────────────────┘┘

I would appreciate it if you could review this code and let me know how I can improve it.

I hope to see:

possible mistakes or cases to break the code
how to make it faster, more performant, pythonic
how to extend it to higher dimensions

P.S. For those who follow up this idea I have integrated everythin here in this Jupyter Notebook


texts: Conditional callback for asynchronous file copy

texts:
I'm trying to figure out the most elegant solution to do the following asynchronously using JavaScript (specifically node):

Given a destination file name, check if it is a directory
If it is a directory, delete it
Copy a source file onto the destination file name

I would like to do this asynchronously using callbacks.

Here is what I have come up with:

  var preCopyOp = fs.lstatSync(dstFilename).isDirectory() ?
    function(callback) {
      rimraf(dstFilename, callback)
    } :
    function(callback) {
      callback();
    };

  preCopyOp(function() {
    ncp(srcFilename, dstFilename, function(err) {
      if(err) {
        return console.error(err);
      }
    });
  });

The no-op passthrough function seems like a bit of a kludge to me. Is there a more elegant way to do this?


texts:
Checking if all five vowels are present in a string.

String phrase = "Hello, how are you keeping?";
String vowelsInPhrase = phrase.toLowerCase().replaceAll("[^aeiou]", "");
String temp = vowelsInPhrase;
String usedVowels = "";
    while(temp.length() > 0){
        usedVowels += temp.substring(0, 1);
        temp = temp.replaceAll(temp.substring(0, 1), "");
    }
    if(usedVowels.length() == 5){
        result += "At least one occurrence of each vowel.\n";
    }

Does anyone have a better solution?? I am thinking some sort of pattern to check if each required character has appeared one or more times but I don't know if it is possible. This would save using the while loop.

Something like this is what I was thinking:

String pattern = "[[a]+[e]+[i]+[o]+[u]+]";
if(usedVowels.matches(pattern){
        result += "At least one occurrence of each vowel.\n";
    }


texts: How and where to define a partial helper module

texts:
I want to split my helpers in different modules (and files), but I found some problems which I got around with the following solution:

# app/helpers/application_helper.rb
module ApplicationHelper
  include ApplicationContainer
  # ...
end

# app/helpers/partials/application_container.rb
module ApplicationContainer
  # ...
end

In particular at the beginning I was looking to have a file /app/helpers/_application_container_helper.rb that gave me uninitialized constant ApplicationHelper::ApplicationContainer (and different other errors playing around it), but right now I'm not even sure that makes sense.
Any Idea or suggestions?


texts:
Could you help me to speed up/optimize this code:

// Get API Keys
var keys = xRoot.Elements("key").Select(key => new { ID = int.Parse(key.Attribute("id").Value), VerificationCode = key.Attribute("verificationCode").Value });

// Get status of account using API Key
var tasks = keys.Select(key => EveOnlineClient.GetAccountStatusAsync(key.ID, key.VerificationCode));

// Get info about API Key
// Each API key may contain one or more game characters
var tasks2 = keys.Select(key => EveOnlineClient.GetAPIKeyInfoAsync(key.ID, key.VerificationCode).ContinueWith(x =>
    {
        var characters = x.Result.Characters;

        // Get the sheet for each character in each API key
        var tasks3 = characters.Select(character => EveOnlineClient.GetCharacterSheetAsync(key.ID, key.VerificationCode, character.ID));

        // Get skill in training for each character in each API key
        var tasks4 = characters.Select(character => EveOnlineClient.GetSkillInTrainingAsync(key.ID, key.VerificationCode, character.ID));

        Task.WaitAll(tasks3.ToArray());
        Task.WaitAll(tasks4.ToArray());
    }));

await Task.WhenAll(tasks.Concat(tasks2));

Every method of EveOnlineClient downloads XML to local cache if needed (if local cache has expired), parses it and returns as an object.


texts: Citadel's VisualEncrypt and VisualDecrypt

texts:
I was skimming through this paper out of boredom. On pages 5 and 6, the paper shows a simple encryption/decryption scheme that Citadel uses to obfuscate data. The algorithm basically XORs the next character with the previous character. The code is roughly this (ugly, I know):

void VisualEncrypt (void *buffer, unsigned size) {
  for (unsigned i = 1; i < size; ++i) {
      ((unsigned char *) buffer) [i] ^= ((unsigned char *) buffer) [i - 1] ;
  }
}

void VisualDecrypt (void *buffer, unsigned size) {
  if (!size) {
      return ;
  }

  for (unsigned i = size - 1; i > 0; --i) {
      ((unsigned char *) buffer) [i] ^= ((unsigned char *) buffer) [i - 1] ;
  }
}

I decided to make a more generic version of this code so that it could work on different containers and values:

template <class InputIterator, class OutputIterator>
OutputIterator VisualEncrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    if (begin == end) {
        return destination ;
    }

    auto value = *begin ;
    *destination++ = value ;

    while (++begin != end) {
        value ^= *begin ;
        *destination++ = value ;
    }

    return destination ;
}

template <class InputIterator, class OutputIterator>
OutputIterator VisualDecrypt (InputIterator begin, InputIterator end, OutputIterator destination)
{
    if (begin == end) {
        return destination ;
    }

    auto value = *begin ;
    *destination++ = value ;

    while (++begin != end) {
        auto temp = *begin ;
        *destination++ = value ^ temp ;
        value = temp ;
    }

    return destination ;
}

template <class Iterator>
Iterator VisualEncrypt (Iterator begin, Iterator end)
{
    return VisualEncrypt (begin, end, begin) ;
}

template <class Iterator>
Iterator VisualDecrypt (Iterator begin, Iterator end)
{
    return VisualDecrypt (begin, end, begin) ;
}

Here are two sample cases of it being used:

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

int main ()
{
    // Test char
    std::string plaintext = "Please encrypt me!" ;

    std::vector <unsigned char> cyphertext ;
    VisualEncrypt (plaintext.cbegin (), plaintext.cend (), std::back_inserter (cyphertext)) ;

    std::string decrypttext ;
    VisualDecrypt (cyphertext.cbegin (), cyphertext.cend (), std::back_inserter (decrypttext)) ;

    // Test long
    long arr [] = {1, 2, 3, 4, 5} ;
    const auto size = sizeof (arr) / sizeof (arr [0]) ;
    VisualEncrypt (arr, arr + size) ;
    VisualDecrypt (arr, arr + size) ;

    return 0 ;
}

The code seems to work fine. I want to make sure I'm not misusing the iterators and invoking undefined behavior. I couldn't find a clean way to simplify any of this with the <algorithm> library. Any tips on that would be great too.


texts:
I have this Objective-C code for use in an iOS app that makes a 'bar' on the screen, with a red exclamation mark that flashes in it at random places.

Here's what it looks like:

Header file:

#import <UIKit/UIKit.h>

@interface ESFlashingErrorBar : UIView
@property (nonatomic, strong) NSArray *points;
@property (nonatomic, strong) NSString *character;
@property (nonatomic, strong) UIColor *color;
@end

Implementation:

#import "ESFlashingErrorBar.h"
#import "ESThemeManager.h"
@implementation ESFlashingErrorBar
#define kNumOfPoints    7
int lastFlash;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];

        CGFloat width = frame.size.width;

        CGFloat perItemWidth = width/kNumOfPoints;

        int i = 0;

        NSMutableArray *mA = @[].mutableCopy;

        while (i < kNumOfPoints)
        {
            UILabel *exPoint = [[UILabel alloc] initWithFrame:CGRectMake(perItemWidth * i, 0, perItemWidth, self.frame.size.height)];
            exPoint.backgroundColor = [UIColor clearColor];
            exPoint.textColor = [UIColor redColor];
            exPoint.textAlignment = NSTextAlignmentCenter;
            exPoint.text = @"!";
            exPoint.font = [UIFont fontWithName:exPoint.font.fontName size:27];
            exPoint.alpha = 0.1;
            [self addSubview:exPoint];
            [mA addObject:exPoint];

            i++;
        }

        self.points = mA;
    }
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(flashPoint) userInfo:nil repeats:YES];
    return self;
}
- (void)setColor:(UIColor *)color
{
    for (UILabel *l in self.points) {
        l.textColor = color;
    }
}
- (void)setCharacter:(NSString *)character
{
    for (UILabel *l in self.points) {
        l.text = character;
    }
}
- (void)flashPoint
{
    int randomNumber = lastFlash;

    while (randomNumber == lastFlash) {
        randomNumber = arc4random() % kNumOfPoints;
    }

    lastFlash = randomNumber;

    UILabel *l = self.points[randomNumber];

    [UIView animateWithDuration:0.4 delay:0 options:kNilOptions animations:^
    {
        l.alpha = 1;
    }
    completion:^(BOOL finished) {
        [UIView animateWithDuration:0.4 animations:^{
            l.alpha = 0.1;
        }];
    }];
}
- (void)drawRect:(CGRect)rect
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(self.frame.size.width, 0)];
    [[ESThemeManager theme].navLineColor setStroke];
    [path stroke];
}
@end

ESThemeManager is a thing that manages the colors shown in the app.  It returns an ESTheme object which contains a bunch of properties of colors.

I'm wondering if there's a way to make this code simpler - in particular, I don't like how I store a bunch of labels in an array, then loop through it every time I want to change something. Is this best practice?


texts: Casting calls with the same parent class

texts:
I'm using Telegram API and I've different methods which returns different type of information like this:
public SendMessage getTextMessage(Long chatId, String text) {
        return new SendMessage()
                .enableMarkdown(false)
                .setChatId(chatId)
                .setText(text);
    }

public AnswerCallbackQuery getPopUpAnswer(String callbackId, String text) {
        return new AnswerCallbackQuery()
                .setCallbackQueryId(callbackId)
                .setText(text)
                .setShowAlert(true);
    }

public EditMessageText getEditedMessage(Long chatId, Integer messageId, String text){
        return new EditMessageText()
                .setChatId(chatId)
                .setMessageId(messageId)
                .setText(text);
    }

public SendPhoto getPhotoMessage(Long chatId, GooglePlayGame game) {
        return new SendPhoto().setChatId(chatId)
                .setPhoto(game.getPictureURL())
                .setCaption(game.toString());
    }

They have one parent PartialBotApiMethod.
In main method I handle and execute (send) them:
PartialBotApiMethod<?> responseToUser = updateReceiver.handleUpdate(update);
try {
     execute(responseToUser); //error
    }
catch (TelegramApiException e){
     e.printStackTrace();
    }

But I can't execute PartialBotApiMethod object, only BotApiMethod and their subs. SendPhoto is not in one hierarchy with others, that's why I can't put SendPhoto result to BotApiMethod type variable.
And I can't cast like this:
try {
     execute((BotApiMethod)responseToUser);
    }
catch (TelegramApiException e){
     e.printStackTrace();
    }

Because SendPhoto doesn't extends BotApiMethod and I'll give a ClassCastEx.
So I gonna use instanceof and cast "personally":
PartialBotApiMethod<?> responseToUser = updateReceiver.handleUpdate(update);
        if (responseToUser instanceof SendMessage) {
            try {
                execute((SendMessage)responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        else if (responseToUser instanceof SendPhoto) {
            try {
                execute((SendPhoto) responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        else if (responseToUser instanceof AnswerCallbackQuery) {
            try {
                execute((AnswerCallbackQuery)responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
        else if (responseToUser instanceof EditMessageText) {
            try {
                execute((EditMessageText)responseToUser);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }

Do I've better options or just stay with instanceof?
Can I replace instanceof if I cannot use a common interface (third pary API)?
UPDATE
updateReceiver.handleUpdate()
public PartialBotApiMethod handleUpdate(Update update) {
   if (updateHasTextMessage(update)){
       try {
           return processInputMessage(update.getMessage());
       } catch (NotSupportedChatCommandException e) {
           return replyMessageService.getTextMessage(update.getMessage().getChatId(), "Not available");
       }
   }
   else if (updateHasCallbackQuery(update)) {
       return callbackQueryHandler.handleCallbackQuery(update.getCallbackQuery());
   }
   else {
       return replyMessageService.getTextMessage(update.getMessage().getChatId(),
                    "Can't handle");
        }
}


texts:
With the following Code I try to compare the content of two Worksheets.
The first column contains a key that is unique and the following columns contain  data that I want to compare (My data sets contain around 7000 rows and up to 40 columns).

My question is if there is a way to make the code run faster. Since the program has to find the key first, it takes longer and longer the further down the row with the key is on the worksheet. A second thing I noticed is that the code generally runs a lot faster with Excel 2007 than 2013. Any ideas why?

Count = 1
LastRowNew= Sheets("Data_new").Cells(Rows.Count, "A").End(xlUp).Row
LastRowOld = Sheets("Data_old").Cells(Rows.Count, "A").End(xlUp).Row
LastColumn = Sheets("Data_old").UsedRange.Columns.Count
For i = 1 To LastRowOld
Set rngA = Sheets("Data_new").Range(Sheets("Data_new").Cells(1, 1), Sheets("Data_new").Cells(LastRowNew, 1)).Find(Sheets("Data_old").Cells(i, 1), lookat:=xlWhole)
If Not rngA Is Nothing Then
    Count = Count + 1
    Sheets("Comparison").Cells(Count, 1).Value = Sheets("Data_old").Cells(i, 1)
    For j = 2 To LastColumn
        If Sheets("Data_old").Cells(i, j).Value <> Sheets("Data_new").Cells(rngA.Row, j).Value Then
            Sheets("Comparison").Cells(Count, j).Value = "NOK"
        Else
            Sheets("Comparison").Cells(Count, j).Value = "OK"
        End If
    Next j
Else
    Count = Count + 1
    Sheets("Comparison").Cells(Count, 1).Value = Sheets("Data_old").Cells(i, 1)
    Sheets("Comparison").Cells(Count, 2).Value = "Doesn't exist in old system"
End If
Application.StatusBar = "Comparing entries " & Format(i / LastRowOld, "0 %") & "..."
Next i


texts:
I have implemented a very basic TODO List with no database or backend support. Though I have coded in C++ and Python before, this is my first HTML and JavaScript code. Please review the code and let me know where it can be improved.

var numericalID = 1
function addNewTask() {
var container = document.getElementById("taskContainer")

var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var idStr="id:"+numericalID
checkbox.id = idStr
checkbox.addEventListener('change',function() {
    var idSplitArray=this.id.split(':')
    var labelStr="label:"+idSplitArray[1]
    var labelTask=document.getElementById(labelStr)
    //alert(idSplitArray)
    if(this.checked) {
       labelTask.style.setProperty("text-decoration", "line-through");
    } else
    {
       labelTask.style.setProperty("text-decoration","none");
    }})

var label = document.createElement('label')
var labelStr="label:"+numericalID
label.id=labelStr
label.htmlFor = "id";
label.appendChild(document.createTextNode(document.getElementById('taskName').value +"                  "));

var delButton=document.createElement('input')
delButton.type="image"
delButton.src="delButton.png"
delButton.id="del:"+numericalID
delButton.addEventListener('click',function(){
    var idSplitArray=this.id.split(':')
    var checkBoxId="id:"+idSplitArray[1]
    var labelStrId="label:"+idSplitArray[1]
    var delButton="del:"+idSplitArray[1]
    var lineBreakId="line:"+idSplitArray[1]
    console.log(lineBreakId)
    console.log(checkBoxId)
    console.log(labelStrId)
    console.log(delButton)
    document.getElementById(checkBoxId).remove();
    document.getElementById(labelStrId).remove();
    document.getElementById(delButton).remove();
    document.getElementById(lineBreakId).remove();

})

container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(delButton)

var linebreak=document.createElement("br")
linebreakID="line:"+numericalID
linebreak.id=linebreakID
numericalID+=1
container.appendChild(linebreak)
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>To Do</title>

  <form action="">
  Task Name: <input type="text" id="taskName" name="fname">

  <input type="submit"  value="Submit" onclick="addNewTask() ; return false;">

</form>