texts: An alternative to loop constructs in Java

texts:
Java allows methods to make recursive calls.  This can be dangerous because an infinite recursive call will fill up the stack. It can be useful, however, for calculations that need iteration when the number of "self calls" is limited (it save a few keystrokes as well). The code below, although not very useful, does demonstrate the technique.  What are some more practical uses of this technique and how could this code be modified for those uses?

class NoForLoop {
        int sayHello(int num) {
            System.out.println("Hello World!");
            return (1 > num) ? 1 : sayHello(num -1); //self call
        }
    public static void main (String [] args) {
        NoForLoop n = new NoForLoop();
        n.sayHello(5);
    }
}


texts: Find all triplets in array that add up to a given sum

texts:
Given an array and a value, find all the triplets in the array whose sum is equal to the given value. For example, if the given array is {12, 3, 4, 1, 6, 9} and the given sum is 24, then this is one triplet (12, 3 and 9) which contributes to the total sum of 24.
Solution for given example:
6, 9, 9
6, 6, 12
3, 9, 12
The ordering of the numbers in the solution does not matter.
Duplicate triplet is not allowed.
A number is not allowed to be used multiple time.

Here is my code:
package kata.array;

import java.util.*;

public class ThreeSum {

  static class Triplet {
        int x, y, z;

        public Triplet(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        @Override
        public int hashCode() {
            return Objects.hash(x, y, z);
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof Triplet) {
                Set<Integer> numbers = new HashSet<>();
                numbers.addAll(new ArrayList<>(Arrays.asList(x, y, z)));

                Triplet other = (Triplet) o;
                return numbers.containsAll(new ArrayList<>(Arrays.asList(other.x, other.y, other.z)));
            }

            return false;
        }
    }

    public static Set<Triplet> findTriplets(int numbers[], int targetSum) {
        Set<Triplet> triplets = new HashSet<>();

        // insert all pairs in the look up table
        Map<Integer, int[]> lookup = new HashMap<>();
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                int total = numbers[i] + numbers[j];
                lookup.put(total, new int[]{i, j});
            }
        }

        // look for the complement, if found viola! here you go with the matching triplet
        for (int number : numbers) {
            int complement = targetSum - number;

            if (lookup.containsKey(complement)) {
                int indexes[] = lookup.get(complement);
                int x = numbers[indexes[0]], y = numbers[indexes[1]];
                triplets.add(new Triplet(x, y, number));
            }
        }

        return triplets;
    }
}

To run this code:
public void findTriplets() throws Exception {
    int numbers[] = {12, 3, 4, 1, 6, 9};

    System.out.print(ThreeSum.findTriplets(numbers, 24));

    for (ThreeSum.Triplet triplet : ThreeSum.findTriplets(numbers, 24)) {
        System.out.println(triplet.x + ", " + triplet.y + ", " + triplet.z);
    }

    // can handle duplicate?
    System.out.println("==============================");
    numbers = new int[] {12, 3, 4, 1, 6, 9, 9, 9, 9, 9};

    System.out.print(ThreeSum.findTriplets(numbers, 24));

    for (ThreeSum.Triplet triplet : ThreeSum.findTriplets(numbers, 24)) {
        System.out.println(triplet.x + ", " + triplet.y + ", " + triplet.z);
    }
}

GitHub


texts:
I need to get from an array of booleans to a Flags enum.

Here's what my enum looks like:

[Flags]
public enum UserContactPreferences { None = 0, SMS = 1, Email = 2, Phone = 4 }

Here's what my parsing code looks like currently.

private UserContactPreferences GetContactPreferences(bool email, bool phone, bool sms)
{
    var contactByEmail = email ? UserContactPreferences.Email : UserContactPreferences.None;
    var contactByPhone = phone ? UserContactPreferences.Phone : UserContactPreferences.None;
    var contactBySms = sms ? UserContactPreferences.SMS : UserContactPreferences.None;

    return contactByEmail | contactByPhone | contactBySms;
}

That's horrible! I must be able to do better. Any ideas?


texts:
This is my take on the first challenge on the cryptopals crypto challenges list. I think that i made it quite simple but i feel like it is possible to optimize it further. Any suggestion?

The code:

import qualified Data.HashMap.Strict as HM
import qualified Data.IntMap.Strict as IM
import Data.Maybe
import Data.Char (digitToInt)
import Numeric (readInt)

type BinString = String
type HexString = String
type Base64String = String

base64 = IM.fromList (zip [0..63] (['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ ['+','/']))

hexToBinDict = HM.fromList [('0',"0000"),('1',"0001"),('2',"0010"),('3',"0011"),('4',"0100"),('5',"0101"),
                                ('6',"0110"),('7',"0111"),('8',"1000"),('9',"1001"),('a',"1010"),('b',"1011"),
                                    ('c',"1100"),('d',"1101"),('e',"1110"),('f',"1111")]

hexToBase64 :: HexString -> Base64String
hexToBase64 xs = map fromJust [IM.lookup x base64 | x <- base10] ++ padMissingSextets sextets
    where base10 = map (fromJust) (map (binToDec) sextets)
          sextets = binToSextets (hexToBin xs)

--returns a list of the 4-digit binary encodings of the given string's hex codes
hexToQuartets :: HexString -> [BinString]
hexToQuartets [] = []
hexToQuartets hexCode = fromJust (HM.lookup (head hexCode) hexToBinDict) : hexToQuartets (tail hexCode)

--converts an hex string into a binary string
hexToBin :: HexString -> BinString
hexToBin xs = concat (hexToQuartets xs)

--pads the string with 0's on the right until its a sextet
padRight :: BinString -> BinString
padRight xs = xs ++ (replicate n '0')
    where n = 6 - length xs

--returns a list of all full sextets on the string
binToSextets :: BinString -> [BinString]
binToSextets xs = binToSextetsAux (tail xs) [] [head xs] 1

--recursiverly find sextets and pad the last one if necessary
binToSextetsAux :: BinString -> [BinString] -> BinString -> Int -> [String]
binToSextetsAux [] sextets ys _
    |length ys == 6     = sextets ++ [ys]
    |otherwise          = sextets ++ [padRight ys]
binToSextetsAux xs sextets ys i
    |i == 6     = binToSextetsAux (tail xs) (sextets ++ [ys]) [head xs] 1
    |otherwise  = binToSextetsAux (tail xs) sextets (ys ++ [head xs]) (i+1)

--binary string to decimal conversion
binToDec :: Integral a => BinString -> Maybe a
binToDec = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt

--pads with "=" on the right for each empty sextet
--if the length is not divisible by 4, then theres 1 or 2 empty sextets
padMissingSextets :: [BinString] -> BinString
padMissingSextets sextets
    |(length sextets) `mod` 4 /= 0      = if (length sextets) `mod` 4 == 2 then "=="
                                            else "="
    |otherwise                          = ""

```


texts: Determine the complexity of sorting a binary array

texts:
The challenge is to sort an integer array containing only ones and zeros with the lowest complexity possible.
As always, I am interested in any improvements suggested but in this question I am most interested in whether the complexity that I have assigned to the algorithm is correct (as well as the lowest possible). I have included two implementations that have two different running times. I believe that they are still both the same complexity. The larger purpose in posting this is to improve or verify my understanding of Complexity and big oh notation.
I assign the complexity as O(n) to this first algorithm since it only looks at every value in the array once, and only once.
Algorithm I
    /// <param name="value">A list of values to sort where all values are either one or zero.</param>
    /// <returns>Sorted value array.</returns>
    public static int[] SortOnesZeros(int[] value)
    {
        int j = value.Length - 1;
        int i = 0;
        while (i < j)
        {
            if (value[i] < 0 || value[i] > 1 || value[j] < 0 || value[j] > 1)
            {
                throw new Exception("Value array can only contain 1's and 0's.");
            }
            while (value[i] == 0)
            {
                i++;
            }
            while (value[j]== 1)
            {
                j--;
            }
            if (j > i && value[i] > value[j] )
            {
                int temp = value[j];
                value[j] = value[i];
                value[i] = temp;
                j--;
                i++;
            }
        }
        return value;
    }

I have a second implementation that I believe is also O(n) though it is longer since it runs through n twice, but it is not nested. I believe this is true because O(2n) reduces to O(n) since multiplied constants are not considered in big-oh complexity analysis. It is also longer because it changes every value on the second pass. No need to improve on this algorithm, I believe that the first algorithm is already better.:
Algorithm II
    public static int[] SortOnesZerosAlternate(int[] values)
    {
        int countOfZeros = 0;
        foreach(int value in values)
        {
            if (value == 0)
            {
                countOfZeros++;
            }
            if (value <0 || value > 1)
            {
                throw new Exception("Value array can only contain 1's and 0's.");
            }
        }
        for (int i = 0; i < countOfZeros; i++)
        {
            values[i] = 0;
        }
        for (int i = countOfZeros; i < values.Length; i++)
        {
            values[i] = 1;
        }

        return values;
    }

EDIT ***************************************
@superb rain is correct: The first algorithm has a mistake where, under the right conditions, it tries to sort values in the value array that are not actually on the list. This issue will occur on any list where all the values are the same. I have fixed this in my own code by making the change below:
            while (i < j && value[i] == 0)
            {
                i++;
            }
            while (i < j && value[j]== 1)
            {
                j--;
            }


texts:
For practicing purposes, I had the idea of making a sorting algorithm in Python.

My approach to it was to iterate through a given unsorted list to find the shortest number in it, add the number to a second list, remove shortest number from unsorted list, do that until the unsorted list is empty and return the sorted list.

How could my code be improved?

from math import inf
from random import randint

def my_sort(my_list):
    """
    Iterate through list and find shortest number, add
    shortest number to list until there are none left,
    return sorted list (shortest to highest).
    """
    unsorted_list = [*my_list]
    sorted_list = []
    for item in my_list:
        shortest_num = inf
        for num in unsorted_list:
            if num < shortest_num:
                shortest_num = num
        unsorted_list.remove(shortest_num)
        sorted_list.append(shortest_num)
    return sorted_list

# Randomly generate a list of 20 numbers ranging from -20 to 20
random_list = [randint(-20, 20) for i in range(20)]

print(random_list)
print(my_sort(random_list))


texts:
Following this question, I realized there is no built-in data structure like that, so I implement my own queue using List<T>.

Please comment on performance (is there any better way instead of using List<T>?)

public class MyQueue<T>
{
    private List<T> _items;
    private int index;

    public int Count
    {
        get
        {
            return _items.Count;
        }
    }

    public T Last
    {
        get
        {
            return _items[index];
        }
    }

    public MyQueue()
    {
        index = -1;
        _items = new List<T>();
    }

    public void Enqueue(T item)
    {
        _items.Add(item);
        index++;
    }

    public T Dequeue()
    {
        T i = _items[0];
        _items.RemoveAt(0);
        index--;
        return i;
    }

    public T Peek()
    {
        return _items[0];
    }
}


texts: Perl module to deal with numbered nested objects

texts:
I wrote a small perl module that dealing with PHP-ish array structures, and I'm going to release it to CPAN.

I want it to be reviewed before the release about the module naming and the code itself.

Could you please give me improvements?  Any suggestions are appreciated.

https://github.com/ernix/p5-Object-Squash

use strict;
use warnings;
package Object::Squash;
# ABSTRACT: Remove numbered keys from a nested object

use parent 'Exporter';
use List::Util qw/max/;

use version; our $VERSION = version->declare("v0.0.1");

our @EXPORT_OK = qw(squash);

sub squash {
    my $obj = shift;
    return $obj unless ref $obj;

    $obj = _squash_hash($obj);
    $obj = _squash_array($obj);

    return $obj;
}

sub _squash_hash {
    my $obj = shift;
    return $obj unless ref $obj eq 'HASH';

    my @keys = keys %{$obj};

    if (grep {/\D/} @keys) {
        return +{
            map { $_ => squash($obj->{$_}) } @keys,
        };
    }

    my $max = max(@keys) || 0;

    my @ar;
    for my $i (0 .. $max) {
        push @ar, sub {
            return (undef) unless exists $obj->{$i};
            return squash($obj->{$i});
        }->();
    }

    return \@ar;
}

sub _squash_array {
    my $obj = shift;
    return $obj unless ref $obj eq 'ARRAY';

    return (undef) if @{$obj} == 0;
    $obj = squash($obj->[0]) if @{$obj} == 1;

    return $obj;
}

1;
__END__

=head1 NAME

Object::Squash - Remove numbered keys from a nested object

=head1 DESCRIPTION

This package provides B<squash> subroutine to simplify hash/array structures.

I sometimes want to walk through a data structure that consists only of a bunch
of nested hashes, even if some of them should be treated as arrays or single
values.  This module removes numbered keys from a hash.

=head1 SYNOPSIS

=head2 C<squash>

    use Object::Squash qw(squash);
    my $hash = squash(+{
        foo => +{
            '0' => 'nested',
            '1' => 'numbered',
            '2' => 'hash',
            '3' => 'structures',
        },
        bar => +{
            '0' => 'obviously a single value',
        },
    });

$hash now turns to:

    +{
        foo => [
            'nested',
            'numbered',
            'hash',
            'structures',
        ],
        bar => 'obviously a single value',
    };

=head1 AUTHOR

Shin Kojima <shin@kojima.org>

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.


texts: Project Euler 6: Sum square difference in Functional Programming (FP)

texts:
I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from Project Euler:

  The sum of the squares of the first ten natural numbers is,

  12 + 22 + ... + 102 = 385

  The square of the sum of the first ten natural numbers is,

  (1 + 2 + ... + 10)2 = 552 = 3025

  Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

  Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

My solution in FP:

/*jshint esversion: 6*/
(function () {
  'use strict';

  const range = f => num => Array.from(new Array(num), f);
  const quadRange = range((_, i) => (i + 1) * (i + 1));
  const simpRange = range((_, i) => i + 1);
  const sum = (acc, val) => acc + val;
  const sumOfQuads = quadRange(100)
    .reduce(sum);
  const quadsOfSum = simpRange(100)
    .reduce(sum) * simpRange(100)
    .reduce(sum);
  console.log("solution ", quadsOfSum - sumOfQuads);
})();

Is there a better way to write it in FP (without any libraries and with vanilla JS only)?


texts: Color image classification and labeling algorithm

texts:
I have some code I've been using to de-noise some images and then label all unique and contiguous elements. The function zoneMap() de-noises the image by picking a random, unclassified point and then averages all points that are within a certain euclidean distance in color space. This repeats until each point has been classified. The function labelPix() handles the labeling by finding the unique elements in the image processed by zoneMap(), and then labelleing each individual contiguous region.

I am pleased with the output of the functions, however, I would really appreciate any advice on how they can be sped up.

import numpy, random, glob, os,
from skimage import io

def zoneMap(RGB, colorThreshold):

    [height, width, _] = RGB.shape
    mask = numpy.ones((height, width), dtype = bool)
    whiteValues = (RGB == 255).all(-1)
    mask[whiteValues] = False

    WHITEMASK = mask

    pix = RGB.astype(int)

    while True in mask:
        nextPossible = numpy.argwhere(mask == True)
        x, y = nextPossible[random.randint(0, len(nextPossible) - 1)]
        point = pix[x, y]

        distance = numpy.sqrt(numpy.sum((pix - point)**2, axis = -1))
        distance[numpy.invert(mask)] = 500
        toAverageCoords = (distance <= colorThreshold)
        mask[toAverageCoords] = False

        pointsToAverage = pix[toAverageCoords]
        average = pointsToAverage.mean(axis = 0)
        pix[toAverageCoords] = average

        unique, counts = numpy.unique(mask, return_counts=True)
        progress = dict(zip(unique, counts))
        print('Progress: ', (progress[False]/(height*width))*100, '%')

    return pix, WHITEMASK

def labelPix(pix):
    height, width, _ = pix.shape
    pixRows = numpy.reshape(pix, (height * width, 3))
    unique, counts = numpy.unique(pixRows, return_counts = True, axis = 0)

    unique = [list(elem) for elem in unique]
    del(unique[unique.index(list(pix[0,0]))])

    labeledPix = numpy.zeros((height, width), dtype = int)
    offset = 0
    for index, zoneArray in enumerate(unique):
        index += offset
        zone = list(zoneArray)
        zoneArea = (pix == zone).all(-1)
        elementsArray, numElements = scipy.ndimage.label(zoneArea)

        elementsArray[elementsArray!=0] += offset

        labeledPix[elementsArray!=0] = elementsArray[elementsArray!=0]

        offset += numElements

    return labeledPix

def main():
            file = PATH

            im = io.imread(file)
            pix = im[:,:,:3]

            mapArray, _ = zoneMap(pix, 25)

            labeledPix = labelPix(mapArray)

            toSave = NEWPATH

            io.imsave(toSave, mapArray)

I have been using this on images similar to the one linked, though any image should be suitable as input:


texts: dequeue() in Queue implememtation that uses a circular linked list

texts:
I use a circular linked list to implement a queue, and it only holds one last (note that last.next links to the first, not null).

public class Queue<T> {

    private Node last;
    private int n;

    private class Node {
        T value;
        Node next;
        Node(T t, Node n) {
            value = t;
            next = n;
        }
    }

    public Queue() {
        last = null;
        n = 0;
    }

    public boolean isEmpty() {
        return n == 0;
    }

    public void enqueue(T item) {
        if (isEmpty()) {
            last = new Node(item, null);
            last.next = last;
        } else {
            Node tmp = new Node(item, last.next);
            last.next = tmp;
            last = tmp;
        }
        n++;
    }

   // other code
}

I think the correct way of dequeue() is :

public T dequeue() {
    if (isEmpty()) throw new NoSuchElementException();
    Node first = last.next;
    T t = first.value;
    if (last == first) {
        last = null;
    } else {
        last.next = first.next;
    }
    n--;
    return t;
}

This is because we should set last to null if there is one element.

However, the alternative way in following also works, why?

public T dequeue2() {
    if (isEmpty()) throw new NoSuchElementException();
    Node first = last.next;
    T t = first.value;
    last.next = first.next;
    n--;
    return t;
}

I call N times dequeue2() after N times enqueue(), and assert queue.last== null. To my surprize, the assertion passes. I think the last can never be null if I use dequeue2().
So, is the dequeue2() correct?


texts: Reduce JavaScript code. Double event, selector into one

texts:
Any idea how to write this code better."the html is nested tabs"
Two selectors and two similar events, in a function would be better or a pattern to reduce lines. eg .jsbin

$(function() {
  var $items  = $('#vtab>ul>li'),
      $items2 = $('#vtab2>ul>li');

  $items.mouseover(function() {
    var index = $items.index($(this));
    $items.removeClass('selected');
    $(this).addClass('selected');
    $('#vtab>div').hide().eq(index).show();
  }).eq(1).mouseover();

  $items2.mouseover(function() {
    var index = $items2.index($(this));
    $items2.removeClass('selected');
    $(this).addClass('selected');
    $('#vtab2>div').hide().eq(index).show();
  }).eq(1).mouseover();

});


texts:
This code works and does exactly what I want it to, but I feel that it is inelegant.  It seems like there should be a way to use get() and/or setdefault(), for example.  All comments and suggestions are appreciated!

Here is a function that builds a dict.  The dict's values are also dicts.  Some of the values are empty dicts {} and some are dicts that have a {key:value} pair.

def my_function(my_string, my_key):

    d = {}

    for i in range(3):
        d['test' + str(i)] = {}

    d['test3'] = {'a_key': 'a_value'}

    # d = { 'test0': {}, 'test1': {}, 'test2': {}, 'test3': {'a_key': 'a_value'} }

    if my_string != '':
        d[my_key] = {my_string: None}

    else:
        # check if d[my_key] exists
        try:
            # d[my_key] exists and it is not empty, don't overwrite
            if d[my_key]:
                pass
            # d[my_key] exists, but it is empty, write NULL
            else:
                my_string = 'NULL'
                d[my_key] = {my_string: None}

        # d[my_key] did not exist, create it and write NULL
        except KeyError:
            my_string = 'NULL'
            d[my_key] = {my_string: None}

    return d

# my_string not blank, my_key is new
f = my_function('hello', 'test4')
print(f)

# my_string not blank, my_key exists
f = my_function('hello', 'test0')
print(f)

# my_string blank, my_key exists and its value is not empty
f = my_function('', 'test3')
print(f)

# my_string blank, my_key exists and its value is empty
f = my_function('', 'test0')
print(f)

# my_string blank, my_key is new
f = my_function('', 'test4')
print(f)

Typical (and desired) output:

{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}, 'test4': {'hello': None}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {'hello': None}, 'test1': {}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {'NULL': None}, 'test1': {}}
{'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}, 'test4': {'NULL': None}}


texts: Filtering query by date built from integers

texts:
I am trying to make a stored procedure and pass some parameters for filtering. As soon as filtering is in horizon, code has to be as generic as possible with as few as possible if, else, etc.

How could I make this more readable? Can I use functions for this?

ALTER PROCEDURE [dbo].[Stats] @network VARCHAR(9) = NULL,
                                               @name    VARCHAR(100) = NULL,
                                               @version VARCHAR(15) = NULL,
                                               @year    INT = NULL,
                                               @month   INT = NULL,
                                               @day INT = NULL,
                                               @from DATE = null,
                                               @to DATE = null
AS
  BEGIN
      SET nocount ON;

          DECLARE @fromYear INT = NULL;
      SET @fromYear = CASE WHEN @from IS NOT NULL THEN Datepart(year, @from) END

          DECLARE @fromMonth INT = NULL;
      SET @fromMonth = CASE WHEN @from IS NOT NULL THEN Datepart(month, @from) END

          DECLARE @fromDay INT = NULL;
      SET @fromDay = CASE WHEN @from IS NOT NULL THEN Datepart(day, @from) END

          DECLARE @toYear INT = NULL;
      SET @toYear = CASE WHEN @to IS NOT NULL THEN Datepart(year, @to) ELSE @fromYear END

          DECLARE @toMonth INT = NULL;
      SET @toMonth = CASE WHEN @to IS NOT NULL THEN Datepart(month, @to) ELSE @fromMonth END

          DECLARE @toDay INT = NULL;
      SET @toDay = CASE WHEN @to IS NOT NULL THEN Datepart(day, @to) ELSE @fromDay END

      SELECT GS.[contractaddress],
             GS.[network],
             GS.[rounds],
             GS.[sessions],
             GS.[handle],
             GS.[hold],
             GS.[year],
             GS.[month],
             GS.[day],
             G.[name],
             G.[version],
             DATEFROMPARTS(GS.[Year], GS.[Month], GS.[Day]) as [Date]
      FROM   [dbo].[gamestatsdaily] AS GS
             INNER JOIN [dbo].[game] AS G
                     ON GS.contractaddress = G.[contractaddress]
      WHERE  ( @network IS NULL
                OR ( GS.network = Upper(@network) ) )
             AND ( @name IS NULL
                    OR ( GS.[contractaddress] IN (SELECT [contractaddress]
                                                  FROM   [dbo].[game]
                                                  WHERE  [name] = @name
                                                         AND [version] =
                                                             @version
                                                         AND [network] =
                                                             @network)
                       ) )
             AND ( @year IS NULL OR GS.[Year] = @year )
             AND ( @month IS NULL OR GS.[Month] = @month )
             AND ( @day IS NULL OR GS.[Day] = @day )
             AND ( @from IS NULL OR ( GS.[Year] <= @fromYear AND @toYear >= GS.[Year] AND GS.[Month] <= @fromMonth AND @toMonth >= GS.[Month] AND GS.[Day] <= @fromMonth AND @toMonth >= GS.[Day]))

      ORDER  BY GS.[year] ASC,
                GS.[month] ASC,
                GS.[day] ASC
  END


texts: Minimum number of coins - (dynamic programming solution - topdown approach)

texts:
This is a problem from topcoder tutorials

Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type as we want), or report that it's not possible to select coins in such a way that they sum up to S.

This is my first attempt at a DP solution. Did I do it right? How to make this code better, faster and less ugly? Is there a better solution than what I did?

#include <iostream>
#include <vector>
#include <set>

int coins_td(std::vector<int>& v, int n, std::set<int>& s);

int coins_td(int n, std::set<int>& s) {
    std::vector<int> coins(n+1, -1);
    coins[0] = 0;
    return coins_td(coins, n, s);
}

int coins_td(std::vector<int>& v, int n, std::set<int>& s) {
    static const int coin = 1;
    if (n < 0) {
        return -2;
    }
    if (n == 0) {
        return 0;
    }
    if (v[n] != -1) {
        return v[n];
    }
    int tcoins = coin+coins_td(v, n-*s.begin(), s);
    for (auto i = s.rbegin(); i != s.rend(); ++i) {
        if (n >= *i) {
            tcoins = std::min(tcoins, coin+coins_td(v, n-*i, s));
            break;
        }
    }
    v[n] = tcoins;
    return tcoins;
}

int main() {
    int value;
    std::cin >> value;
    if (value <= 0) {
        std::cout << value << '\n';
    } else {
        std::set<int> values;
        int v;
        while (std::cin >> v) {
            values.insert(v);
        }
        int result = coins_td(value, values);
        if (result == 0) {
            std::cout << "it's not possible to select coins in such a way that they sum up to " << value << "." << '\n';
        } else {
            std::cout << result << '\n';
        }
    }
}


texts:
I am an experienced Python developer learning C. I solved this assignement:

  Write a program that reads a word and some sentences from stdin. The word is separated by space from a sentences. The sentences are separated by one of the following characters: .!?. Words in sentences are separated by any char for which one of library functions isspace and ispunct returns nonzero result.

  Your program should output average usage of the word in the sentences (a number of matched words divided by a number of sentences).

  Example input:

  two one four two seven eight two four two. two, one, nine, two, two, three, two!

  Example expected output: 3.5

  Explanation: The word is "two". Then we have two sentences: "one four two seven eight two four two." and "two, one, nine, two, two, three, two!". The word occurs 7 times, so result is 7/2 = 3.5.

Here is my solution:

# include <ctype.h>
# include <stdbool.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>

void check_malloc_result(void* malloc_result) {
    if (!malloc_result) {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }
}

int main(void) {
    char stdin_ch;

    size_t buff_size = 8;
    size_t word_len = 0;
    bool reading_word = false;

    char* word = malloc(buff_size);
    check_malloc_result(word);

    // reading the word
    while(read(STDIN_FILENO, &stdin_ch, 1) > 0) {
        if (isspace(stdin_ch)) {
            if (reading_word) {
                break;
            } else {
                continue;
            }
        }
        reading_word = true;
        ++word_len;

        if (word_len > buff_size) {
            buff_size *= 2;
            word = realloc(word, buff_size);
            check_malloc_result(word);
        }

        word[word_len - 1] = stdin_ch;
    }

    // counting matches
    size_t sen_count = 0, matched_count = 0, cur_word_pos = 0;
    bool matching = true;
    reading_word = false;

    while(word_len && read(STDIN_FILENO, &stdin_ch, 1) > 0) {
        if (ispunct(stdin_ch) || isspace(stdin_ch)) {
            if (reading_word) {
                // end of a word
                if (matching) {
                    ++matched_count;
                }
                if (stdin_ch == '.' || stdin_ch == '?' || stdin_ch == '!') {
                    ++sen_count;
                }
                reading_word = false;
                matching = true;
                cur_word_pos = 0;
            }
            continue;
        }

        reading_word = true;
        if (matching) {
            if (cur_word_pos >= word_len || word[cur_word_pos] != stdin_ch) {
                matching = false;
            }
            ++cur_word_pos;
        }
    }
    free(word);

    // printing the result
    double result = 0.0;
    if (sen_count) {
        result = (double)matched_count / (double)sen_count;
    }
    printf("%f", result);

    return EXIT_SUCCESS;
}

Some notes:

I don't want to use fixed max length for the word so I use dynamic allocation here.
The reading of sentences is done using two boolean flags. reading_word means are actualy reading a word, and if it's false, we are somewhere in between. It's used for dealing with consecutive separators. matching becomes false when we know that current scanned word doesn't match, so we just scan to the end of the word, not checking anything.

What could be better in this code? Is it "idiomatic" C, or is it obvious that it's written by someone without much language experience?


texts: Drawing an ASCII grid in Ruby based on a 2D array

texts:
I'm writing a function that renders a grid using ASCII line-drawing characters, based on a provided 2D array (or array of arrays), with each top-level array representing a row, and the items inside those arrays as columns.

The function works, but it is absurdly ugly and hard to read. I want to resolve that somehow, but the only things I can think of would already make a massive function even longer and more verbose.

How can this function be improved?

drawgrid

# Renders an ASCII grid based on a 2D array
def drawgrid(args, boxlen=3)
  #Define box drawing characters
  side = '│'
  topbot = '─'
  tl = '┌'
  tr = '┐'
  bl = '└'
  br = '┘'
  lc = '├'
  rc = '┤'
  tc = '┬'
  bc = '┴'
  crs = '┼'
  ##############################
  draw = []
  args.each_with_index do |row, rowindex|
    # TOP OF ROW Upper borders
    row.each_with_index do |col, colindex|
      if rowindex == 0
        colindex == 0 ? start = tl : start = tc
        draw << start + (topbot*boxlen)
        colindex == row.length - 1 ? draw << tr : ""
      end
    end
    draw << "\n" if rowindex == 0

    # MIDDLE OF ROW: DATA
    row.each do |col|
      draw << side + col.to_s.center(boxlen)
    end
    draw << side + "\n"

    # END OF ROW
    row.each_with_index do |col, colindex|
      if colindex == 0
        rowindex == args.length - 1 ? draw << bl : draw << lc
        draw << (topbot*boxlen)
      else
        rowindex == args.length - 1 ? draw << bc : draw << crs
        draw << (topbot*boxlen)
      end
      endchar = rowindex == args.length - 1 ? br : rc

      #Overhang elimination if the next row is shorter
      if args[rowindex+1]
        if args[rowindex+1].length < args[rowindex].length
          endchar = br
        end
      end
      colindex == row.length - 1 ? draw << endchar : ""
    end
    draw << "\n"
  end

  draw.each do |char|
    print char
  end
  return true
end

Usage

drawgrid([[123,456,789,'baz'], ['abc','def','ghi'], ['foo', 'bar'], ['buz']])

# Output
┌───┬───┬───┬───┐
│123│456│789│baz│
├───┼───┼───┼───┘
│abc│def│ghi│
├───┼───┼───┘
│foo│bar│
├───┼───┘
│buz│
└───┘

It is a known limitation with the code given that grids with more columns in later rows will display incorrectly. For the purpose this function is being used for, it is an acceptable limitation. I'm okay with fixing it as long as it doesn't bloat this method even further.

I'm also aware of a ruby library, terminal-table, but it's not 100% suited for the kind of terse output I'm looking for. This will be used to display an IP space map, while terminal-table appears to work better for formatted tables like MySQL output.


texts:
Below is my code for building the collatz sequence so a given number.  I'm trying to make the function tail recursive and I believe that this impelemtation is tail recursive but I'm not yet so comfortable with F# that I can convince myself 100%.

let collatzSeq n =
    let collatz m =
        match m%2 with
        | 0 -> m/2
        | _ -> 3*m + 1
    let rec loop (l,acc) =
        match l with
        | 1 -> acc
        | _ -> let l' = (collatz l) in loop (l',l'::acc)
    loop (n,[n]) |> List.rev

[<EntryPoint>]
let main argv =
    let col12 = collatzSeq 12
    printfn "%A %d" col12 col12.Length
    0 // return an integer exit code

My concern is does the let .. in loop construct stop this being tail recursive and if it does how do I improve the code to make it tail recursive?


texts: Dependency injection with asp.net identity and property injection with dbcontext

texts:
I configure asp.net identity using Simple Injector

  var container = new Container();
  container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

  //Identity
  container.RegisterPerWebRequest<AppDbContext>();
  container.RegisterPerWebRequest<IUserStore<User, int>>(() => new UserStore<User, Role, int, UserLogin, UserRole, UserClaim>(new AppDbContext()));
  container.RegisterPerWebRequest<IRoleStore<Role, int>>(() => new RoleStore<Role, int, UserRole>(new AppDbContext()));
  container.RegisterPerWebRequest<AppRoleManager>();
  container.RegisterPerWebRequest<AppUserManager>();
  container.RegisterPerWebRequest<AppSignInManager>();

  container.RegisterPerWebRequest(() =>
  {
    if (HttpContext.Current != null && HttpContext.Current.Items["owin.Environment"] == null && container.IsVerifying)
    {
      return new OwinContext().Authentication;
    }
    return HttpContext.Current.GetOwinContext().Authentication;

  });

And configure a property injection for BaseController and my DbContext

My BaseController

 public class BaseController : Controller
  {
    public ISessionContext SessionContext { get; set; }
  }

My register in simple injector

  container.Register<ISessionContext,ClaimsSessionContext>();
  container.RegisterInitializer<BaseController>(ctrl =>
  {
    ctrl.SessionContext = container.GetInstance<ISessionContext>();
  });

My DbContext

  public class AppDbContext : IdentityDbContext<User, Role, int, UserLogin, UserRole, UserClaim>
  {
    public ISessionContext SessionContext { get; set; }
    public AppDbContext()
      : base("AppConnection")
    {
    }
    public static AppDbContext Create()
    {
      return new AppDbContext();
    }

And my simple injector register for property injection

   container.RegisterInitializer<AppDbContext>(db =>
      {
        db.SessionContext = container.GetInstance<ISessionContext>();
      });

I wonder if there would be no problem injecting  SessionContext property next to my DbContext, for every request it is also instantiated

Suggestions? This ok ?


texts: Codility's count passing cars in opposite directions in C#

texts:
I programmed a few things in java and now I'm learning C#. I've been doing exercises from Codility.

The first 3 or 4 were very difficult to me but now I guess I've got the hang of it. This site helped a lot at improving my style and the things I now think I should be looking at before contenting myself with the final code. I comment a lot less than previous posts because I guess the names and the constants are self explanatory.

Are there still things to improve in my code in easy exercises like this?

Task score: 100%

Detected time complexity: $O(N)\$

  Task description

  A non-empty array A consisting of N integers is given. The consecutive
  elements of array A represent consecutive cars on a road.

  Array A contains only 0s and/or 1s:

  0 represents a car traveling east, 1 represents a car traveling west.
  The goal is to count passing cars. We say that a pair of cars (P, Q),
  where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q
  is traveling to the west.

  For example, consider array A such that:

  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1
  We have five
  pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

  Write a function:

  class Solution { public int solution(int[] A); }

  that, given a non-empty array A of N integers, returns the number of
  pairs of passing cars.

  The function should return −1 if the number of pairs of passing cars
  exceeds 1,000,000,000.

  For example, given:

  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1
  the function should return 5, as explained above.

  Write an efficient algorithm for the following assumptions:

  N is an integer within the range [1..100,000]; each element of array A
  is an integer that can have one of the following values: 0, 1.

And this is my solution, please note that if 1000000000+ passing cars are counted, then the return value of the function should be -1. I had to check for overflows, because one of the tests returned a huge negative number if overflowing, also if overflow occurs before 1000000000 (I don't know if an int holds that number), then it would stop counting sooner, hence than try/catch block improves performance(?).

public static int GetNumberOfPassingCars( int[] passingCars )
{
    const int OVERFLOW = -1 ;
    const int EAST = 0 ;
    const int WEST = 1 ;
    int carTravelingEast = 0, pairOfPassingCars = 0;
    foreach( var passingCar in passingCars )
    {
        if ( passingCar == EAST )
        {
            ++carTravelingEast;
        }
        else if ( passingCar == WEST )
        {
            try
            {
                pairOfPassingCars = checked( pairOfPassingCars + carTravelingEast );
                if ( pairOfPassingCars > 1000000000 )
                {
                    return OVERFLOW;
                }
            }
            catch( OverflowException )
            {
                return OVERFLOW;
            }
        }
    }
    return pairOfPassingCars;
}


texts: javascript multiple inheritance code review

texts:
i had made a small code snippet for multiple inheritance in js. this code is working for me but actually i like to get the review, that its good and if any problem; provide the solution. etc. the code snippet is below.

/**
 * WebbaseUtility provide the bundle of utilities used for support the webbase
 * functionalities;
 * @package : WebbaseUtility;
 * @version : 1.0.0;
 */
var WebbaseUtility = {};

/**
 * ObjectExt module extends the object properties and functionalities like inheritance etc;
 * @module : ObjectExt;
 * @package : Webbase;
 * @version : 1.0.0;
 * @return Object;
 */

var ObjectExt = WebbaseUtility.ObjectExt = (function()  {

    /**
     * ObjectExt Constructor;
     */
    var ObjectExt = function()  {
    };

    /**
     * This method provide inheritance to the object supplied; this method inherit the
     * public methods from the Parent class to the Child class. this also provide
     * multiple inheritance, in which the method ambiguity is solved by the overriding
     * the last inherited class's method;
     * @access public;
     * @method inherit;
     * @param Object Parent;
     * @param Object Child;
     * @return Object;
     */
    ObjectExt.prototype.inherit = function(Parent, Child)   {
        var TempObj = function(){}, MultipleInheritanceTempObj = function(){};

        MultipleInheritanceTempObj.prototype = Child.prototype;
        TempObj.prototype = Parent.prototype;

        for(var key in MultipleInheritanceTempObj.prototype)    {
            TempObj.prototype[key] = MultipleInheritanceTempObj.prototype[key];
        }
        MultipleInheritanceTempObj = null;
        Child.prototype = new TempObj();

        if(Child.uber === undefined)    {
            Child.uber = Parent.prototype;
        }else   {
            for(var key in Parent.prototype)    {
                Child.uber[key] = Parent.prototype[key];
            }
        }
        Child.prototype.constructor = Child;

        return Child;
    };

    return new ObjectExt();

})();

Child = WebbaseUtility.ObjectExt.inherit(ParentA, Child);
Child = WebbaseUtility.ObjectExt.inherit(ParentB, Child);


texts:
I'm writing an app to let me interact and debug my android over USB using the android SDK and the ADB command.  I create a Process with redirected input and output streams and basically run "ADB shell", and I want to be able to wait for the prompt, enter commands and parse the results.

Here's a sample running ps and getting the results:

CreateProcess("shell");
string data = await ReadToPrompt(":/ $ ");
_Process.StandardInput.WriteLine("ps");
string echo = await ReadLine(); // my command echoed back
string dataAndPrompt = await ReadToPrompt(":/ $ ");

It works (although I'm getting extra CR in the byte stream, CR/LF is coming as CR/CF/LF), but I can't help but wonder if there's a better way than what I have:

Process _Process;
MemoryStream _Remaining; // bytes left after ReadToPrompt
byte[] _Buffer = new byte[0x10000];

public async Task<string> ReadLine()
{
    return await ReadToPrompt("\r\n");
}

public async Task<string> ReadToPrompt(string prompt)
{
    MemoryStream ms = _Remaining == null ? new MemoryStream() : _Remaining;
    int promptSize = prompt.Length;
    int pos = 0;

    while (true)
    {
        // read what we can from the process's standard output
        int count = await _Process.StandardOutput.BaseStream.ReadAsync(_Buffer, 0, _Buffer.Length);
        ms.Write(_Buffer, 0, count); // write new data to memory stream

        // convert all new bytes to check for prompt
        string testString = Encoding.ASCII.GetString(ms.GetBuffer(), pos, (int)(ms.Position - pos));
        int promptPos = testString.IndexOf(prompt);
        if (promptPos > 0)
        {
            // we found it, result is up to and including prompt
            int stripLength = pos + promptPos + promptSize;
            string result = Encoding.ASCII.GetString(ms.GetBuffer(), 0, stripLength);

            // store remaining data in a MemoryStream for the next call
            _Remaining = new MemoryStream();
            _Remaining.Write(ms.GetBuffer(), stripLength, (int)(ms.Position - stripLength));
            return result.Replace("\r\r", "\r");
        }

        // we didn't find it but we know it isn't in what we got, so move first position
        // to check to the position - promptSize
        pos = (int)(ms.Position - promptSize);
        pos = (pos < 0) ? 0 : pos;
    }
}

Is there something I can reliably do to keep from creating new MemoryStreams?  For instance, could I do an array copy on MemoryStream.GetBuffer() to itself and use MemoryStream.SetLength()?  Is there an entirely better way to do it than using async and await?


texts:
So, given a file with the following format:

  [header]
  line of data
  line of data
  line of data
  line of data

  [header 2]
  line of data
  line of data
  line of data

  ...

I add a line of data to a specific header so the result would be:

  ...
  [target header]
  line of data
  ...
  new line inserted

The program currently only adds lines but is written so it accepts an input file that lists instructions with the format instruction|[header]|line to add e.g.  A|[Passions]|Code Review would add Code Review to the Passions section.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class AdjustList {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("No arguments provided.");
            System.exit(1);
        }

        try (Scanner fileScanner = new Scanner(new File(args[0]))) {
            while (fileScanner.hasNextLine()) {
                String[] commandParameters = fileScanner.nextLine().split("\\|");
                if (commandParameters.length != 3) {
                    throw new IllegalArgumentException("Invalid parameter format");
                }

                File targetFile = new File("ImportantList.md");
                processCommand(targetFile, commandParameters[0], commandParameters[1], commandParameters[2]);
            }
        } catch (FileNotFoundException fnfe) {
            System.err.println("File doesn't exist / wrong directory");
        }
    }

    private static void processCommand(File file, String instruction, String targetSection, String inputLine) {
        boolean taskComplete = false;
        StringBuilder fileBuilder = new StringBuilder();

        try (Scanner fileScanner = new Scanner(file)) {
            if (instruction.equals("A")) { // add
                System.out.println("Adding " + inputLine + " to " + targetSection);
                while (fileScanner.hasNextLine()) {
                    String line = fileScanner.nextLine();
                    if (line.equals(targetSection)) {
                        fileBuilder.append(line).append('\n');
                        while (!taskComplete) {
                            line = fileScanner.nextLine();
                            if (line.isEmpty()) {
                                fileBuilder.append(inputLine).append('\n');
                                taskComplete = true;
                            } else {
                                fileBuilder.append(line).append('\n');
                            }
                        }
                    } else {
                        fileBuilder.append(line).append('\n');
                    }
                }
            }
        } catch(FileNotFoundException fnfe) {
            System.err.println("File doesn't exist / wrong directory");
            System.exit(1);
        }

        writeOutput(file, fileBuilder.toString());
    }

    private static void writeOutput(File file, String output) {
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
            writer.write(output);
        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }
}

The file is read, line by line, storing the input into a StringBuilder with the additional line added based on a flag. This works but I get the feeling it's not the cleanest way.


texts: Hello World using Python embedded in C++, with RAII library initialization

texts:
I have written a small Hello World application that uses Python's C-API. The C library requires some functions to be called for global library (de-)initialization and the objects created by the library eventually need to be released by passing the pointer to a specific function. I think this is a fairly common pattern in C libraries.

I attempted to use RAII, to get automatic cleanup, even when exceptions interfere with the planned control flow.

#include <tr1/memory>
#include <Python.h>

// helper to get function pointer for the macro
void Python_DecreaseRefCount(PyObject* p) {
    Py_DECREF(p);
}

int main() {
    // declare struct and create instance that handles global initialization and
    // deinitialization of Python API
    static struct PythonApi {
        PythonApi() { Py_Initialize(); }
        ~PythonApi() { Py_Finalize(); }
    } python_api;
    // create object
    // use smart pointer for automatic refcount decrement at scope end
    std::tr1::shared_ptr<PyObject> string(
        PyString_FromString("Hello World!\n"),
        &Python_DecreaseRefCount);
    // do something with object
    PyObject_Print(string.get(), stdout, Py_PRINT_RAW);
}

Compiles and runs with:

$ g++ test.cc `pkg-config --cflags --libs python2` && ./a.out
Hello World!

I'm interested in all kinds of feedback, as to whether my attempt makes sense and if there is room for improvement. Are there best practices, or certain idioms that facilitate this, that I might have missed in my approach?


texts: Scraping content from yellowpage and write them to a csv file

texts:
I've written a script in python to scrape names and phone numbers of a certain search from yellowpage traversing multiple pages. The scraper has the ability to collect all the links connected to all the names. Once the links are collected, the scraper goes to the target page to parse the name and website address. Finally, it will produce a csv file with data filled-in. Although the scraper is doing it's job errorlessly, I'm little dubious as to whether I used the best way to write items in a csv file. Any betterment to the pattern will be highly appreciated.

Here is what I've written:

import requests
import csv
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = "https://www.yellowpages.com/search?search_terms=+Injury+Law+Attorneys&geo_location_terms=California"

def get_links(session,link):
    session.headers['User-Agent'] = 'Mozilla/5.0'
    res = session.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select(".info h2 a[data-analytics]"):
        get_info(session,urljoin(url,items.get("href")))

    nextpage = soup.select_one("a.next")
    if nextpage:  #If there is no more next page link, it should break
        nexturl = urljoin(link,nextpage.get("href"))
        print(nexturl)        #check to see which page I'm on
        get_links(session,nexturl)  #supply the newly produced next page link to grab the next one

def get_info(session,tlink):
    session.headers['User-Agent'] = 'Mozilla/5.0'
    res = session.get(tlink)
    soup = BeautifulSoup(res.text,"lxml")
    name = soup.select_one("#main-header .sales-info h1").get_text(strip=True)
    website = soup.select_one("#main-header a.website-link").get("href") if soup.select_one("#main-header a.website-link") else ""
    print(name,website)
    writer.writerow([name,website])  #writing data in a csv file

if __name__ == '__main__':
    with open("yellowpageinfo.csv","w",newline="") as infile: #creating a csv file to write populated results
        writer = csv.writer(infile)
        writer.writerow(['Name','Website'])
        with requests.Session() as session:
            get_links(session,url)


texts: Merging two Excel sheets by matching on two columns

texts:
I have 2 sheets with the exact format, 5 columns (Category1, Category2, Category3, Month, Amount) - "Temp" and "Source".

My goal is to copy the data from "Source" to a new sheet("Combined"), append the data from "Temp" but replace the rows that are matching on column C and D with the new rows from "Temp".

For now I have the following code that does the job:

Option Explicit

Sub Verify()
Dim c As Range
Application.ScreenUpdating = False
last3 = Sheets("Temp").Cells(Application.Rows.count, "A").End(xlUp).row
last4 = Sheets("Source").Cells(Application.Rows.count, "A").End(xlUp).row
last5 = Sheets("Combined").Cells(Application.Rows.count, "A").End(xlUp).row

' Clear Contents
Sheets("Combined").Range("A1:E" & last5).ClearContents

    Sheets("Temp").Range("G2").Formula = "=C2&D2"
    Sheets("Temp").Range("G2").Copy Destination:=Sheets("Temp").Range("G3:G" & last3)

    Sheets("Source").Range("G2").Formula = "=C2&D2"
    Sheets("Source").Range("G2").Copy Destination:=Sheets("Source").Range("G3:G" & last4)

    Sheets("Source").Range("H2").Formula = "=MATCH(G2,Temp!$G$2:$G$" & last3 & ",0)"
    Sheets("Source").Range("H2").Copy Destination:=Sheets("Source").Range("H3:H" & last4)

' Copy & Format Headers
Sheets("Temp").Range("A1:E1").Copy Destination:=Sheets("Combined").Range("A1")

' Copy All Data from Temp
Sheets("Temp").Range("A2:E" & last3).Copy Destination:=Sheets("Combined").Range("A2")

' Copy Selected Data from Source
    For Each c In Sheets("Source").Range("H2:H" & last4)
        If IsError(c) Then
          last5 = Sheets("Combined").Cells(Application.Rows.count, "A").End(xlUp).row
          Sheets("Source").Range("A" & c.row & ":E" & c.row).Copy Destination:=Sheets("Combined").Range("A" & last5 + 1)
        End If
    Next c

' Clean temp Columns
Sheets("Temp").Columns("G:G").Delete
Sheets("Source").Columns("G:H").Delete
Application.ScreenUpdating = True
End Sub

My problem with it is that is too slow(~15.000 rows). It freezes my excel with a white screen for a few minutes but in the end it works. I have tried using DoEvents but it is still really slow.

I am sure there a better way to achieve what I am looking for. Can someone please help me rewrite the VBA to speed it up? I would be grateful if I could at least get it not to freeze or increase the performance somehow.


texts: Good, flexible and secure MVC router PHP

texts:
I have developed a new router after having learnt a lot from my previous attempts and I will be using this in sites I make from now on.

In a previous question, the issue of REQUEST_URI being too inflexible made me wonder if I could make adjustments to allow it to route $_POST and $_GET requests too?

Please let me know what you think and how it could be improved as I am still learning:

class Router {

public $offset = 9 ; // Adjust according to subdir length.
public $start_page = 'Index' ; // Change to your home/default page.
private $classAliases = array(
    'pretty-url' => 'UglyClassName',
) ;

private $methodAliases = array(
    'pretty-method' => 'uglyMethodName',
) ;

function __construct()
{
    $url = substr(rtrim($_SERVER['REQUEST_URI'], '/'), $this->offset) ;

    $command = explode('/', $url, 3) ;

    if(isset($command[0]))
    {
        $class = ucfirst($this->autoMap($command[0]), $this->classAliases) ;
    }

    if(class_exists($class) && preg_match('/[^A-Za-z0-9]/', $class) == false)
    {
        $controller = new $class ;

        if($method = (isset($command[1]) ? $command[1] : NULL))
        {
            $method = (strstr($method, '?') ? substr($url, 0, strrpos($method, '?')) : $method) ;
            $method = $this->autoMap($method, $this->methodAliases) ;
            if(method_exists($class, $method) && preg_match('/[^A-Za-z0-9]/', $method) == false)
            {
                $params = array() ;
                if(stristr($url, '?')) // Parameters passed the conventional way...
                {
                    $queryString = substr($url, strrpos($url, '?')+1) ;
                    parse_str($queryString, $params) ;
                }
                elseif(isset($command[2])) // ...or the clean URL way.
                {
                    $params = explode('/', $command[2]) ;
                }
                call_user_func_array(array($controller, $method), $params) ;
            }
            elseif($method)
            {
                $this->throwError('Method '.$method.' does not exist.') ;
            }
        } else { // Default index method.
            if(method_exists($class, 'index'))
            {
                $controller->index() ;
            } else {
                $this->throwError('Class '.$class.' has no index method.') ;
            }
        }
    }
    elseif(!$class)
    {
        $controller = new $this->start_page ;
        $controller->index() ;
    } else {
        $this->throwError('Class '.$class.' does not exist.') ;
    }
}

private function throwError($e)
{
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) // Ajax request...
    {
        echo $e ;
    } else { // ...or normal request.
        new Error($e) ;
    }
}

private function autoMap($alias, $routes)
{
    if(array_key_exists($alias, $routes))
    {
        return $routes[$alias] ;
    }
    return $alias ;
}

}


texts: Testing input validation and an AJAX request with Javascript and QUnit

texts:
I have a simple web page where the user enters the name and rank of a soldier and hits submit. If the input is invalid, an appropriate error message gets displayed. Otherwise, it adds the soldier to a database and adds it to a list of current Soldiers via AJAX request.

//Find elements on page
var rankField = $("input[name='rank']");
var nameField = $("input[name='name']");
var submit = $("input[type='submit']");
var list = $("ul");

//attach event-handler to submit button
submit.click(function() {
  var rank = rankField.val();
  var name = nameField.val();
  onSoldierSubmitted(rank, name);
});

function onSoldierSubmitted(rank, name) {
  clearErrors();

  var rankIsValid = isValidRank(rank);
  var hasErrors = false;

  if (!rankIsValid) {
    addError('rank is invalid');
    hasErrors = true;
  };

  if (!name) {
    addError('Please enter a name for your Soldier');
    hasErrors = true;
  };

  if (hasErrors) {return;}
  appendSoldier();
};

function clearErrors() {
  $('.alert-danger').empty();
};

function addError(errorText) {
  var errorDiv = $('.alert-danger');
  var currentError = errorDiv.html();

  if (currentError) {
    currentError += '
';
  };

  errorDiv.html(currentError + errorText);
};

function isValidRank(rank) {
  var ranks = ['GEN', 'LTG', 'MG', 'BG', 'COL', 'LTC', 'MAJ',
      'CPT', '1LT', '2LT', 'CW5', 'CW4', 'CW3', 'CW2', 'WO1',
      'SMA', 'CSM', 'SGM', '1SG', 'MSG', 'SFC', 'SSG', 'SGT',
      'CPL', 'SPC', 'PFC', 'PV2', 'PVT']
  normalizedRank = rank.toUpperCase();
  return ranks.indexOf(normalizedRank) != -1;
};

function appendSoldier() {
  $.get("/ajax/soldier",
  {
    rank: rankField.val(),
    name: nameField.val(),
  }).done(
    function(data) {
      soldiers = extractSoldiersFromList(data);
      renderHTMLListFromData(soldiers);
    }
  );

  clearInput();
};

function extractSoldiersFromList(data) {
  var soldierData = $.parseJSON(data);
  var soldiers = [];

  for (var i=0; i < soldierData.length; ++i) {
    var soldier = soldierToString(soldierData[i]);
    soldiers[i] = soldier;
  }

  return soldiers;
};

function renderHTMLListFromData(data) {
  list.empty();
  elements = data;
  addSoldiersToUL(elements);
}

function addSoldiersToUL(soldiers) {
  for (var i = 0; i < soldiers.length; ++i) {
    list.append("
" + soldiers[i] + "
");
  }
}

function clearInput() {
  rankField.val('');
  nameField.val('');
}

function soldierToString(soldierDict) {
  var rank = soldierDict.rank;
  var name = soldierDict.name;

  return rank + " " + name;
};

(Yes, I realize I am a horrible person for using GET instead of POST for this. I was having trouble getting POST to work with my back-end.)

I'm having trouble figuring out the right unit tests for the appendSoldier function:

test("appendSoldier makes request with correct args", function() {
  sinon.spy($, 'get');
  rankField.val('PVT');
  nameField.val('Snuffy');

  appendSoldier();

  ok($.get.calledWith("/ajax/soldier", {rank: 'PVT', name: 'Snuffy'}));
  $.get.restore();
});

test("UL of Soldiers populates correctly", function() {
  renderHTMLListFromData(soldierData);
  ok(list.has('li').text('PVT Snuffy'));
});

My reasoning here is that unit tests aren't supposed to test anything external, so I make sure the right request gets called, and that the proper thing is done with the response. I'm unhappy with this, because it still doesn't tell me that appendSoldier works like it's supposed to. I guess that's just something I leave to my functional tests?

I'm also not sure about my tests for the onSoldierSubmitted function, which displays appropriate errors, or calls appendSoldier if there aren't any errors.

Here is my test for valid input:

test("Get request called with valid input", function() {
  sinon.spy($, "get");
  onSoldierSubmitted('pvt', 'snuffy');
  ok($.get.called, "method called");
  $.get.restore();
});

I'm not sure whether I ought to be uncomfortable that this tests that appendSoldier sends the get request, rather than testing that appendSoldier gets called.


texts: Integer to Alphabet string ("A", "B", ...."Z", "AA", "AB"...)

texts:
So this question is prompted by two things.

I found some code in our source control doing this sort of things.
These SO questions:

https://stackoverflow.com/questions/297213/translate-an-index-into-an-excel-column-name
https://stackoverflow.com/questions/837155/fastest-function-to-generate-excel-column-letters-in-c-sharp
https://stackoverflow.com/questions/4075656/how-to-get-continuous-characters-in-c/4077835#4077835
https://stackoverflow.com/questions/1011732/iterating-through-the-alphabet-c-sharp-a-caz

So when I thought about this problem this popped into my head almost immediately.

class Util
{
    private static string[] alphabetArray = { string.Empty, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
    public static IEnumerable<string> alphaList = alphabetArray.Cast<string>();

    public static string IntToAA(int value)
    {
        while (Util.alphaList.Count() -1 < value)
        {
            Util.IncreaseList();
        }

        return Util.alphaList.ElementAt(value);
    }

    private static void IncreaseList()
    {
        Util.alphaList = Util.alphabetArray.Take(1).Union(
            Util.alphaList.SelectMany(currentLetter =>
               Util.alphabetArray.Skip(1).Select(innerLetter => currentLetter + innerLetter)
            )
        );
    }
}

My question is this: Is this approach a better solution (performance wise)?
 or is a recursive / computed value better (eg. this answer )?


texts:
I'm trying to optimize the following method. Any suggestions on how this can be done better? The shipping cost is based on weight and the total cost of products. Following are the conditions for calculating cost.

When order is under $100, and all items under 10 lb, then shipping is $5 flat.
When order is $100 or more, and each individual item is under 10 lb, then shipping is free.
Items over 10 lb always cost $20 each to ship.

public function addShippingCost($subtotal)
        {
            $shipCost = 0;
            $totalWeight = 0;
            $itemUnder10lb = true;
            foreach ($this->products as $product) {
                if($product->getWeight() > 10){
                    $shipCost += $this::RATE_HEAVY;
                    $itemUnder10lb = false;
                }
                $totalWeight += $product->getWeight();
            }
            //When order is under $100, and all items under 10 lb, then shipping is $5 flat
            //When order is $100 or more, and each individual item is under 10 lb, then shipping is free
            //Items over 10 lb always cost $20 each to ship

            if($subtotal > 100 && $itemUnder10lb)
                return $this::RATE_FREE;
            elseif($subtotal < 100 && $totalWeight < 10)
                return $this::RATE_FLAT;
            elseif($itemUnder10lb == false)
                return shipCost;
        }


texts:
I wrote this with-input-from-pipe function for Guile. I’m not that comfortable with dynamic-wind or set-current-input-port, so I’d appreciate any critiques.

(use-modules (ice-9 popen)
             (srfi srfi-26))

(define (with-input-from-pipe command thunk)
  (let ((old (current-input-port))
        (pipe (open-input-pipe command)))
    (dynamic-wind
      (cute set-current-input-port pipe)
      thunk
      (lambda ()
        (set-current-input-port old)
        (close-pipe pipe)))))


texts:
I spent about an hour and a half attempting to complete a problem from W3Resource. Here is what I came up with, which works. How can I shorten it?

function dateGet(){
var newDate = new Date();
var newMonth = newDate.getMonth() + 1;
var newDay = newDate.getDate();
var newYear = newDate.getFullYear();
var twoYear = (""+newYear).split("");
var combinedYear = twoYear[2] + twoYear[3];
var fullDate = 0;

if (newMonth < 10){
    fullDate += 0 + newMonth + '/';
} else {
    fullDate += newMonth + '/';
}

if (newDay < 10){
    fullDate += 0 + newDay + '/';
} else {
    fullDate += newDay + '/';
}

if (combinedYear < 10){
    fullDate += 0 + combinedYear;
} else {
    fullDate += combinedYear;
}

console.log(fullDate);

}


texts:
This works, and I personally find it elegant and kind of "neat," but then I worry it's a bit too tricky. Comments welcome:

function (reports) {
    reports.forEach(function (report, i) {
        report.upPercentage = report.upTime / report.totalTime;
        report.rank = i; // temporary storage in a convenient location
    });
    _.sortBy(reports, 'upPercentage').forEach(function (report, i) {
        reports[report.rank].rank = i; // the 'trick'
    });
    return reports;
}

The first loop goes through the array of reports, and calculates the upPercentage for each report. This part should arguably be done on the backend but it isn't and it isn't going to be. Not my call.

The first loop also assigns each element's own position in the array to its rank. This is not the report's actual rank, it's just data I need for the second loop.

The second loop is iterating over a sorted copy of the reports array (it is important that the original sorting of reports be maintained), and uses the element's original position, stored in rank, to find it in the original, unsorted array. It then assigns the element's position in the sorted array to the rank of the element in the original, unsorted array.

Thus rank ends up being equal to the number of reports that have a lower upPercentage than does the given report.


texts: Matplotlib-venn and keeping lists of the entries

texts:
Having come upon the wonderful little module of matplotlib-venn I've used it for a bit, I'm wondering if there's a nicer way of doing things than what I have done so far. I know that you can use the following lines for a very simple Venn diagram:

union = set1.union(set2).union(set3)
indicators = ['%d%d%d' % (a in set1, a in set2, a in set3) for a in union]
subsets = Counter(indicators)

... but also want to have lists of entries in the various combinations of the three sets.

import numpy as np
from matplotlib_venn import venn3, venn3_circles
from matplotlib import pyplot as plt
import pandas as pd

# Read data
data = pd.read_excel(input_file, sheetname=sheet)

# Create three sets of the lists to be compared
set_1 = set(data[compare[0]].dropna())
set_2 = set(data[compare[1]].dropna())
set_3 = set(data[compare[2]].dropna())

# Create a third set with all elements of the two lists
union = set_1.union(set_2).union(set_3)

# Gather names of all elements and list them in groups
lists = [[], [], [], [], [], [], []]
for gene in union:
    if (gene in set_1) and (gene not in set_2) and (gene not in set_3):
        lists[0].append(gene)
    elif (gene in set_1) and (gene in set_2) and (gene not in set_3):
        lists[1].append(gene)
    elif (gene in set_1) and (gene not in set_2) and (gene in set_3):
        lists[2].append(gene)
    elif (gene in set_1) and (gene in set_2) and (gene in set_3):
        lists[3].append(gene)
    elif (gene not in set_1) and (gene in set_2) and (gene not in set_3):
        lists[4].append(gene)
    elif (gene not in set_1) and (gene in set_2) and (gene in set_3):
        lists[5].append(gene)
    elif (gene not in set_1) and (gene not in set_2) and (gene in set_3):
        lists[6].append(gene)

# Write gene lists to file
ew = pd.ExcelWriter('../Gene lists/Venn lists/' + compare[0] + ' & '
                    + compare[1] + ' & ' + compare[2] + ' gene lists.xlsx')

pd.DataFrame(lists[0], columns=[compare[0]]) \
    .to_excel(ew, sheet_name=compare[0], index=False)

pd.DataFrame(lists[1], columns=[compare[0] + ' & ' + compare[1]]) \
    .to_excel(ew, sheet_name=compare[0] + ' & ' + compare[1], index=False)

pd.DataFrame(lists[2], columns=[compare[0] + ' & ' + compare[2]]) \
    .to_excel(ew, sheet_name=compare[0] + ' & ' + compare[2], index=False)

pd.DataFrame(lists[3], columns=['All']) \
    .to_excel(ew, sheet_name='All', index=False)

pd.DataFrame(lists[4], columns=[compare[1]]) \
    .to_excel(ew, sheet_name=compare[1], index=False)

pd.DataFrame(lists[5], columns=[compare[1] + ' & ' + compare[2]]) \
    .to_excel(ew, sheet_name=compare[1] + ' & ' + compare[2], index=False)

pd.DataFrame(lists[6], columns=[compare[2]]) \
    .to_excel(ew, sheet_name=compare[2], index=False)

ew.save()

# Count the elements in each group
subsets = [len(lists[0]), len(lists[4]), len(lists[1]), len(lists[6]),
           len(lists[2]), len(lists[5]), len(lists[3])]

# Basic venn diagram
fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
v = venn3(subsets, (compare[0], compare[1], compare[2]), ax=ax)
c = venn3_circles(subsets)

# Annotation
ax.annotate('Total genes:\n' + str(len(union)),
            xy=v.get_label_by_id('111').get_position() - np.array([-0.5,
                                                                   0.05]),
            xytext=(0,-70), ha='center', textcoords='offset points',
            bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.3))

# Title
plt.title(compare[0] + ' & ' + compare[1] + ' & ' + compare[2] +
          ' gene expression overlap')

plt.show()

So, there's basically a lot of different cases, each handled manually, and I'm wondering if there's a more "automated" / less verbose / better way of doing this. For example, can I get out the entries from the three line code snippet in the beginning somehow?


texts: Caching lookup values in an e-commerce website

texts:
I am working on an e-commerce website. I have a CarMake dropdown which contains car make names and their corresponding Id, for example: { 1:Alfa romeo}, { 2:Audi }, { 3:BMW }, etc

I want to keep this lookup in cache, so I won't have to make a trip to DB every time I want to get the corresponding Name or Id...

So in my infrastructure layer, I read the data from DB and keep it in cache, I am using a static CarMakeLookup class:

public static class CarMakeLookup
{
    private static readonly Dictionary<short, string> _carMakeIdLookup;
    private static readonly Dictionary<string, short> _carMakeNameLookup;

    static CarMakeLookup()
    {
        _carMakeIdLookup = new Dictionary<short, string>();
        _carMakeNameLookup = new Dictionary<string, short>();

        using (var context = ApplicationDbContext.Create())
        {
            DropdownRepository dropdownRepository = new DropdownRepository(context);

            var carMakes = dropdownRepository.GetCarMakes();
            foreach (var carMake in carMakes)
            {
                _carMakeIdLookup[carMake.CarMakeId] = carMake.CarMakeName;
                _carMakeNameLookup[carMake.CarMakeName.ToLower()] = carMake.CarMakeId;
            }
        }
    }

    public static string GetCarMakeName(short carMakeId)
    {
        if (carMakeId <= 0)
        {
            return string.Empty;
        }

        if (_carMakeIdLookup.ContainsKey(carMakeId))
        {
            return _carMakeIdLookup[carMakeId];
        }

        return string.Empty;
    }

    public static short GetCarMakeId(string carMakeName)
    {
        if (!string.IsNullOrEmpty(carMakeName))
        {
            string lowerCaseCarMakeName = carMakeName.ToLower();
            if (_carMakeNameLookup.ContainsKey(lowerCaseCarMakeName))
            {
                return _carMakeNameLookup[lowerCaseCarMakeName];
            }
        }

        return -1;
    }

    public static Dictionary<short, string> GetCarMakeLookup()
    {
        return _carMakeIdLookup;
    }
}

I also need to display car make in a dropdown in my View... so I need a List<SelectListItem> to be displayed as a dropdown. So in my Application layer I have another static class which holds this list:

public static class CarCache
{
    static CarCache()
    {
        var selectCarMake = new SelectListItem { Value = "-1", Text = "Select a car", Disabled = true, Selected = true };
        CarMakeItemsIncludingSelect = new List<SelectListItem>(); // Dropdown's first option should be "select a car"
        CarMakeItemsIncludingSelect.Insert(0, selectCarMake);

        foreach (KeyValuePair<short, string> carMakeKeyPair in CarMakeLookup.GetCarMakeLookup())
        {
            var selectListItem = new SelectListItem { Value = carMakeKeyPair.Key.ToString(), Text = carMakeKeyPair.Value };
            CarMakeItemsIncludingSelect.Add(selectListItem);
        }
    }

    public static List<SelectListItem> CarMakeItemsIncludingSelect { get; private set; }

    public static string GetCarMakeName(short carMakeId)
    {
        return CarMakeLookup.GetCarMakeName(carMakeId);
    }

    public static short GetCarMakeId(string carMakeName)
    {
        return CarMakeLookup.GetCarMakeId(carMakeName);
    }
}

I have a few more dropdowns like this in my application, for example HouseType, JobType, etc

Everything works fine, the only problem is that my application startup time is slow... I assume one problem is that when I start debugging the application, the application starts building all these static cache classes, and since these classes are static I cannot inject the DbContext into them... so each dropdown should build its own DdContext instance, get corresponding data from DB and Dispose of DbContext. There is no performance problem with the production server...

Any recommendation on how to improve this cache?


texts:
I want to convert an integer to a perfect square by multiplying it by some number. That number is the product of all the prime factors of the number which not appear an even number of times. Example 12 = 2 x 2 x 3; 2 appears twice (even number of times) but 3 just once (odd number of times), so the number I need to multiply 12 by to get a perfect square is 3. And in fact 12 x 3 = 36 = 6 * 6.

I converted my code to Haskell and would like to know what suggestions you have.

import Data.List (group)

toPerfectSquare :: Int -> Int
toPerfectSquare n = product . map (\(x:_) -> x) . filter (not . even . length) . group $ primefactors n

primefactors :: Int -> [Int]
primefactors n = prmfctrs' n 2 [3,5..]
  where
    prmfctrs' m d ds | m < 2     = [1]
                     | m < d^2   = [m]
                     | r == 0    = d : prmfctrs' q d ds
                     | otherwise = prmfctrs' m (head ds) (tail ds)
      where (q, r) = quotRem m d

Sorry about the naming, I'm bad at giving names.

One particular doubt I have is in the use of $ in toPerfectSquare, that I first used . but it didn't work and I needed to use parenthesis. Why? And is it usual to have that many compositions in one line?


texts: Exercise 1_2 multiple console outputs. I would like to reduce the number of console output statements

texts:
Please could we examine the below code for anyway to put all console output in one statements?

 #include <iostream>
 using namespace std;

 int main( )
 {  //print("") in Python
   cout<<"Hello " "everybody!"<<endl;
   cout<<"My name is AK."<<endl;
   cout<<"Goodbye."<<endl;
   cout<<""<<endl;

   //Poem
   cout<<"Twinkle, twinkle, little bat!"<<endl;
   cout<<"How I wonder what you're at?"<<endl;
   cout<<"Up above the world you fly,"<<endl;
   cout<<"Like a tea-tray in the sky."<<endl;
   return 0;
}


texts: Getting value from a property according to some parameters

texts:
Im curious if my approach is correct in this case:
I would like to get two DateTimes from a public property, but one of the dates i want them only if a user has purchase a feature or if he has not activate a switch, otherwise i want to get the same DateTime twice.
More specifically, the way im getting the values now is this:
public class MainApplication : Application
{
public DateTime DateFrom { get; set; } = DateTime.Now;
public DateTime DateTo { get; set; } = DateTime.Now;
}

AnotherClass
{
            SearchButton.Click += async (sender, e) =>
            {
                await SearchFoNumbersAsync(ApplicationState.DateFrom, ApplicationState.DateTo, DailySearchSwitch.Checked, SeperateCheckBox.Checked, ShowListsCheckBox.Checked).ConfigureAwait(false);
            };
            private async Task SearchFoNumbersAsync(DateTime dateFrom, DateTime dateTo, bool isDailySearchEnabled, bool seperateSearch, bool showDrawTime)
            {
                ((MainActivity)Activity).DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle), GetString(Resource.String.Common_SearchMessage));

                if (isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection())
                    dateTo = dateFrom;
...
            }
}

So i want to get DateTo only
if (isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection()), otherwise i want to get the DateFrom value in the place of DateTo
Im sure this approach is not correct so im thinking i should get the DateTo this way:
public class MainApplication : Application
{
    public DateTime DateFrom { get; set; } = DateTime.Now;
    private DateTime DateTo { get; set; } = DateTime.Now;

    public DateTime GetDateTo(bool isDailySearchEnabled)
    {
        if (isDailySearchEnabled || !PurchaseFunctions.HasPurchasedDateRangeSelection())
             return DateFrom;
        else
             return DateTo;
    }

    public void SetDateTo(DateTime dateTime)
    {
        DateTo = dateTime;
    }
}

Is my new approach a good idea?


texts:
I'd like to generate an infinite list of prime candidates of the form 6k±1, but I'm looking for the fastest possible solution.

Currently I have this:

primeCands :: [Integer]
primeCands = concatMap (\i -> [6*i-1, 6*i+1]) [1..]

but I feel that concat is wasting too much time. Using all the odd numbers is almost the same thing in terms of performance. Maybe a list is not the right datatype for this task?


texts:
Our professor has given us the following task (its part of a bigger document full of tasks):

Write a function in C that handles strings like "233+343" and parse them into the variables "iNum1", "cOp" and "iNum2". (I tried to translate it into english).

We mostly program in Java and my C knowledge consists of mostly provisional half knowledge.

But is my program beautiful enough to show it to a professor?

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

#define ASCII_POS_OF_0 0x30
#define ASCII_POS_OF_9 0x39

void parse_calc_string(char string[])
{

    // get first number
    int iNum1 = 0;
    int index = 0;
    char current_char = string[index];
    while (current_char >= ASCII_POS_OF_0 && current_char <= ASCII_POS_OF_9)
    {
        iNum1 *= 10;
        iNum1 += (int)current_char - ASCII_POS_OF_0;
        current_char = string[++index];
    }

    // get operation symbol
    char cOp = current_char;
    current_char = string[++index];

    // get second number
    int iNum2 = 0;
    while (current_char >= ASCII_POS_OF_0 && current_char <= ASCII_POS_OF_9)
    {
        iNum2 *= 10;
        iNum2 += (int)current_char - ASCII_POS_OF_0;
        current_char = string[++index];
    }

    printf("iNum1: %i\n", iNum1);
    printf("cOp  : %c\n", cOp);
    printf("iNum2: %i\n", iNum2);
    printf("\n");
}

int main()
{
    parse_calc_string("219+43");
    parse_calc_string("195-143");
    parse_calc_string("15*13");
    parse_calc_string("212/14");
}


texts: Procedure to determine minimum number of stamps to make up a given monetary value

texts:
I'm following the Udacity intro to CompSci, and I don't know why my answer isn't quite correct:

Question:

  Define a procedure, stamps, which takes as its input a positive
  integer in pence and returns the number of 5p, 2p and 1p stamps (p is
  pence) required to make up that value. The return value should be a
  tuple of three numbers (that is, your return statement should be
  followed by the number of 5p, the number of 2p, and the nuber of 1p
  stamps).

  Your answer should use as few total stamps as possible by first using
  as many 5p stamps as possible, then 2 pence stamps and finally 1p
  stamps as needed to make up the total.

My attempt

def stamps(targetvalue):
    currentvalue = 0
    fives = 0
    twos = 0
    ones = 0
    while True:
        if targetvalue == currentvalue:
            return fives, twos, ones
        if targetvalue - currentvalue >= 5:
            fives = fives + 1
            currentvalue = currentvalue + 5
        if targetvalue - currentvalue < 5:
            if targetvalue - currentvalue >= 2:
                twos = twos + 1
                currentvalue = currentvalue + 2
            if targetvalue - currentvalue == 1:
                ones = ones + 1
                currentvalue = currentvalue + 1
            else:
                return fives, twos, ones


texts: Fetching / formatting / storing tweets to my database

texts:
I am periodically getting tweets, formatting them, and storing them into the database. Now the line of code I use for this is an awful lot. I was wondering if this could be improved.

// This is the wordpress way of getting a json object
// Wordpress will determine how the data is going to
// be fetched looking at what PHP functions are
// enabled for the user, wget, curl, etc.
$json_body = wp_remote_retrieve_body(
    wp_remote_get(
        'http://twitter.com/statuses/user_timeline/'.$options['username'].'.json?count='.$options['count'] ) );

$tweet = json_decode( $json_body, true );
for( $i = 0; $i < $options['count']; $i++ ){
  $latestTweet = htmlentities($tweet[$i]['text'], ENT_QUOTES);
  $latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', 'http://$1', $latestTweet);
  $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '@$1', $latestTweet);

  // This array $data will be stored to the DB
  // I will use the *serialize()* function for this.
  $data[] =  array( 'text' => $latestTweet, 'time' => timespan( $tweet[$i]['created_at'] ) );
}

function timespan( $a )
{
  //get current timestampt
  $b = strtotime("now");
  //get timestamp when tweet created
  $c = strtotime($a);
  //get difference
  $d = $b - $c;
  //calculate different time values
  $minute = 60;
  $hour = $minute * 60;
  $day = $hour * 24;
  $week = $day * 7;

  if(is_numeric($d) && $d > 0) {
    //if less then 3 seconds
    if($d < 3) return "right now";
    //if less then minute
    if($d < $minute) return floor($d) . " seconds ago";
    //if less then 2 minutes
    if($d < $minute * 2) return "about 1 minute ago";
    //if less then hour
    if($d < $hour) return floor($d / $minute) . " minutes ago";
    //if less then 2 hours
    if($d < $hour * 2) return "about 1 hour ago";
    //if less then day
    if($d < $day) return floor($d / $hour) . " hours ago";
    //if more then day, but less then 2 days
    if($d > $day && $d < $day * 2) return "yesterday";
    //if less then year
    if($d < $day * 365) return floor($d / $day) . " days ago";
    //else return more than a year
    return "over a year ago";
  }
}


texts:
As part of a web-based claims system I have created, there is a view for logging telephone calls. If a call is incoming, the claims handler asks the caller a series of data protection questions to validate who they are. The questions are generated from a database and each question has one or more valid answers. The valid answers are also generated from the database.

Example view:

Things of note for my question:

In addition to the valid answers, there are also 'Unanswered' and 'Incorrect Response' answers. These are added via client code and are not part of the original valid answers generated by the database.
Each valid answer has a 'check' icon
The invalid answer has a 'cross' icon
The unanswered answer has no icon

Here's my client code for each type of answer:

class Answer {
    constructor(answer, state) {
        this.el = document.createElement('option');
        this.el.value = answer;
        this.el.textContent = answer;

        state.apply(this);
    }
}

class AnswerState {
    constructor(validationIcon, validationColor) {
        this.validationIcon = validationIcon;
        this.validationColor = validationColor;
    }

    apply(answer) {
        answer.el.setAttribute('data-validation-icon', this.validationIcon);
        answer.el.setAttribute('data-validation-color', this.validationColor);
    }
}

class UnansweredState extends AnswerState {
    apply(answer) {
        super.apply(answer);
        answer.el.setAttribute('data-unanswered', '');
    }
}

class ValidAnswerState extends AnswerState {
    apply(answer) {
        super.apply(answer);
        answer.el.setAttribute('data-valid', '');
        answer.el.setAttribute('data-icon', 'icons/round-done-24px.svg');
    }
}

class InvalidAnswerState extends AnswerState {
    apply(answer) {
        super.apply(answer);
        answer.el.setAttribute('data-invalid', '');
        answer.el.setAttribute('data-icon', 'icons/round-clear-24px.svg');
    }
}

export { Answer, UnansweredState, ValidAnswerState, InvalidAnswerState };

And this is how I create the answer select element for each question:

function createAnswerSelect(validAnswers) {
    const select = document.createElement('select');
    const unansweredState = new UnansweredState('remove', 'grey');
    const invalidAnswerState = new InvalidAnswerState('clear', 'red');
    const validAnswerState = new ValidAnswerState('done', 'green');

    select.add(new Answer('Unanswered', unansweredState).el);

    validAnswers.forEach(answer => {
        select.add(new Answer(answer.answer, validAnswerState).el);
    });

    select.add(new Answer('Incorrect response', invalidAnswerState).el);

    return select;
}

Is this a reasonable way to encapsulate the variability of the different type of answers (unanswered, valid, invalid)? It feels like 'unanswered' should be the state of a question, not an answer.

As per usual, I am questioning myself. The code works, but I have a nagging feeling it is a 'bad' design somehow.


texts:
I want to print the following triangle:

1
1  2
1  2  3
1  2  3  4
1  2  3  4  5
1  2  3  4
1  2  3
1  2
1

I tried to do but I cannot avoid two for loops. Is it possible to achieve the result in a single for loop?

 static void printtriangle()
{
    for (int i = 1; i <= 5; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            Console.Write("" + (j));

        }
        Console.WriteLine("");

    }

        for (int k = 4; k >= 0; --k)
        {

            for (int j = 1; j <= k; j++)
            {
                Console.Write("" + (k));

            }
            Console.WriteLine("");
         }

    }


texts: Toggle button that will hide/unhide columns within a range

texts:
I have the below toggle button sub that works;

Private Sub Toggle_Unused_Click()
    Dim xAddress As String
    xAddress = "DR:FI"

Call KeyOpen 'unprotects the sheet
If Toggle_Unused.Value Then
    Application.ActiveSheet.Columns(xAddress).Hidden = True
    'This returns a value to my notes tab.
    ActiveWorkbook.Sheets("Notes").Cells(5, 11).Value = "Hidden"
Else
    Application.ActiveSheet.Columns(xAddress).Hidden = False
    'This returns a value to my notes tab.
    ActiveWorkbook.Sheets("Notes").Cells(5, 11).Value = "Visible"
End If
'This will record how many times the button has been used.
     ActiveWorkbook.Sheets("Notes").Cells(9, 8).Value = _
     ActiveWorkbook.Sheets("Notes").Cells(9, 8).Value + 1
Call KeyLock 'protects the sheet
End Sub

Then I updated the code to look like this-

Private Sub Toggle_Unused_Click()
    Application.ScreenUpdating = False
    'This will unprotect the sheet
    Call ActiveWorkbook.Sheets("Notes").All_Sheets_UnProtect("Notes")

    If Toggle_Unused.Value Then
        Application.ActiveSheet.Range("NAMED_RANGE").Columns.Hidden = True
        'This will return a value to my notes tab.
        ActiveWorkbook.Sheets("Notes").Cells(5, 11).Value = "Hidden"
    Else
        Application.ActiveSheet.Range("NAMED_RANGE").Columns.Hidden = False
        'This will return a value to my notes tab.
        ActiveWorkbook.Sheets("Notes").Cells(5, 11).Value = "Visible"
    End If
    'This will track how many times the button has been used.
    ActiveWorkbook.Sheets("Notes").Cells(9, 8).Value = _
    ActiveWorkbook.Sheets("Notes").Cells(9, 8).Value + 1
    'This will protect the sheet
    Call ActiveWorkbook.Sheets("Notes").All_Sheets_Protect ("Notes")
    Application.ScreenUpdating = True
    'This will close the user form.
    Control_Buttons.Hide

End Sub

I have updated to use a named range because my sheet keeps growing with new columns and I am trying to limit how many declared columns I have in my code. I have four of these in a user form that each toggle a different section of sheet(Master).


texts: Project Euler #15: counting paths through a 20 × 20 grid

texts:
I've recently solved Project Euler's 15th problem stating:

  Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

  How many such routes are there through a 20×20 grid?

This is my dynamic approach in C++

#include <cstdio>

const unsigned short n = 20;

int main() {
    unsigned long long p[n][n];
    for (unsigned short i = 2; i <= n; i++)
        p[n - i][n - 1] = i + 1;
    for (unsigned short i = n - 2; i >= 1; i--) {
        p[i][i] = 2 * p[i][i + 1];
        for (unsigned short k = i; k >= 1; k--)
            p[k - 1][i] = p[k][i] + p[k - 1][i + 1];
    }
    printf("%llu", 2 * p[0][1]);
}

I am aware that this problem could be solved way more efficiently and faster by simply calculating \${(2n)!}/{(n!)^2}\$, however I decided to look at this problem from a programmer's point of view, rather than a mathematician's.


texts: Avoiding Duplicate Boilerplate Code in WCF Service

texts:
I'm responsible for maintaining a web service project in c#.  I have one service class with a bunch of methods that look a lot like this:

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "v1/Login", ResponseFormat = WebMessageFormat.Json)]
    public string Login()
    {
        try
        {
            JObject incomingRequestJson = retrieveJson();
            JObject returningJson = new JObject();

            string accountId = incomingRequestJson.SelectToken("accountId", true).ToString();
            string username = incomingRequestJson.SelectToken("userName", true).ToString();
            string password = incomingRequestJson.SelectToken("password", true).ToString();

            LoginResult result = readerBLL.Login(accountId, username, password);
            returningJson.Add(new JProperty("userSessionId", result.userSessionId));
            returningJson.Add(new JProperty("friendlyUserName", result.friendlyUserName));

            return returningJson.ToString(Newtonsoft.Json.Formatting.None);
        }
        catch (Exception ex)
        {
            throw new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);
        }
    }

Note that retrieveJson() grabs a JSON string from the HttpContext and runs JObject.Parse() on it.
Note also that the consumer of this service is a Flex app, so I do need the WebFaultException business with the "OK" response code (The networking component in Flex treats connection timeouts and all HTTP error codes exactly the same - no further data other than

I don't like the way I have the try-catch block repeated in every method, so I tried making the following method:

private object invokeBusinessLogic(Func<JObject, object> f)
    {
        try
        {
            return f(retrieveJson());
        }
        catch (Exception ex)
        {
            WebFaultException<string> wfe = new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);
            throw wfe;
        }
    }

Then my service methods can look like this:

public object Login()
{
    LoginResult result = (LoginResult) invokeBusinessLogic(readerBLL.Login);
    returningJson.Add(new JProperty("userSessionId", result.userSessionId));
    returningJson.Add(new JProperty("friendlyUserName", result.friendlyUserName));

    return returningJson.ToString(Newtonsoft.Json.Formatting.None);
}

However, this has the problem that the use of JSON to carry the request data gets exposed to the business layer.  Is there a better way to avoid the duplicate try-catch blocks than this invokeBusinessLogic idea?


texts:
I need to obtain all combinations of a String of length k from the given elements.

For example, for

char[] elements = {'a', 'b', 'c'}
k = 4

the output should be:

  aaaa, aaab, ..., cccc.

Now I have the following code which gives proper results BUT isn't fast enough. What can I improve in my code?

public static ArrayList<String> printAllKLength(char[] elements, int nrElements, int patternLength) {
    ArrayList<String> patternVariations = new ArrayList<String>();
    patternVariations = printAllKLengthRec(elements, "", nrElements, patternLength, patternVariations);

    return patternVariations;
}

public static ArrayList<String> printAllKLengthRec(char[] elements, String prefix, int nrElements, int patternLength, ArrayList<String> patternVariations) {

    if (patternLength == 0) {
        patternVariations.add(prefix);
        //System.out.println(prefix);
        return patternVariations;
    }

    for (int i = 0; i < nrElements; ++i) {
        String newPrefix = prefix + elements[i];
        printAllKLengthRec(elements, newPrefix, nrElements, patternLength - 1, patternVariations);
    }
    return patternVariations;
}


texts:
I been trying to implement a text processor in JavaScript that can handle 4 different types of operations: append, backspace, undo, redo.
The input for this text processor is an array of arraries of a single element or tuples. For example:
  const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!']]
  textProcessor.process(input)
  textProcessor.text // Hey there!

  const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['UNDO'], ['UNDO']]
  textProcessor.process(input)
  textProcessor.text // Hey

  const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['UNDO'], ['UNDO'], ['REDO'], ['REDO']]
  textProcessor.process(input)
  textProcessor.text // Hey there!

  const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['BACKSPACE']]
  textProcessor.process(input)
  textProcessor.text // Hey there

Here is my implementation
class TextProcessor {
    constructor() {
      this.undos = []
      this.redos = []
      this.text = ''
      this.operations = {
        APPEND: (text) => {
          this.undos.push(this.text)
          this.redos.length = 0
          return this.text + text
        },
        BACKSPACE: () => {
          this.undos.push(this.text)
          this.redos.length = 0
          return this.text.slice(0, -1)
        },
        UNDO: () => {
          const undo = this.undos.pop() ?? ''
          this.redos.push(this.text)
          return undo
        },
        REDO: () => {
          this.undos.push(this.text)
          return this.redos.pop() ?? this.text
        },
      }
    }

    process(input) {
      input.forEach(([operation, text]) => {
        this.text = this.operations[operation](text) ?? this.text
      })
    }
  }

I used an object to map the various operation names to their corresponding functions. Not sure if this is better than switch-case statements.


texts: Expression tree in Haskell with support for differentiation

texts:
A simple binary expression tree in Haskell without operator precedence and without parentheses.

Any comments would be much appreciated.

data Tree a= Const a
       | X
       | Plus (Tree a) (Tree a)
       | Mult (Tree a) (Tree a)
       | Minus (Tree a) (Tree a)
       | Div (Tree a) (Tree a)
       | Power (Tree a) (Tree a)
       | Cos (Tree a)
       | Sin (Tree a)
deriving Show

eval :: ( Eq t, Floating t) => Tree t-> t -> Maybe t
eval (Const a) x =  Just  (a)
eval X x =  Just x
eval (Plus a b) x = (+) <$> eval a x <*> eval b x
eval (Mult a b) x =  (*) <$> eval a x <*> eval b x
eval (Minus a b) x =  (-) <$> eval a x <*> eval b x
eval (Power a b) x =  (**) <$> eval a x <*> eval b x
eval (Div a b) x =  if (eval b x) == (Just 0) then Nothing else (/) <$> eval a x <*> eval b x
eval (Cos a) x =(cos) <$> eval a x
eval (Sin a) x = (cos) <$> eval a x

dif :: ( Eq t, Floating t) => Tree t->Tree t
dif (Const a)  = Const 0
dif X  =  Const 1
dif (Plus a b)  =Plus (dif a) (dif b )
dif (Mult a b)  =  Plus (Mult (dif a) b) (Mult  a (dif b))
dif (Minus a b)  =  Minus (dif a) (dif b)
dif (Div a b) =  Div (Minus (Mult (dif a) b) (Mult  a (dif b))) (Mult b b)
dif (Power (Const a) (Const b)) = Const 0
dif (Power a (Const b)) = Mult (Const b) (Power X (Minus (Const b) (Const 1)))
dif (Cos a) = Minus (Const 0) (Mult (dif a) (Sin a))
dif (Sin a) = (Mult (dif a) (Cos a))