texts: Simple Java calculator with two operands

texts:
I am taking a lynda dot com course online to start off. The course asks you to write a simple program:

  Ask the user to input 2 values
  Ask the user to input an operation
  Use the operation on the 2 values and print the result

This was very different from the solution given by the course. Could anyone take a quick look at it and tell me if there's something I'm doing fundamentally wrong or inefficient? My suspicion is that I'm using too much memory.

package com.example.java;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a numeric value: ");
        String input1 = scanner.nextLine();
        System.out.print("Enter a numeric value: ");
        String input2 = scanner.nextLine();

        double double1 = Double.parseDouble(input1);
        double double2 = Double.parseDouble(input2);

        System.out.print("Choose and operation (+ - * /): ");
        String input3 = scanner.nextLine();

        double resultAdd = double1 + double2;
        double resultSub = double1 - double2;
        double resultMul = double1 * double2;
        double resultDiv = double1 / double2;

        switch (input3) {
            case "+":
                System.out.println("The answer is " + resultAdd);
                break;
            case "-":
                System.out.println("The answer is " + resultSub);
                break;
            case "*":
                System.out.println("The answer is " + resultMul);
                break;
            case "/":
                System.out.println("The answer is " + resultDiv);
                break;
        }
    }
}

Here is what the instructor wrote, for the record:

package com.example.java;

import java.util.Scanner;

public class Calculator2 {

    public static void main(String[] args) {
        String s1 = getInput("Enter a numeric value: ");
        String s2 = getInput("Enter a numeric value: ");
        String op = getInput("Choose an operation (+ - * /):");

        double result = 0;

        try {
            switch (op) {
                case "+":
                    result = addValues(s1, s2);
                    break;
                case "-":
                    result = subtractValues(s1, s2);
                    break;
                case "*":
                    result = multiplyValues(s1, s2);
                    break;
                case "/":
                    result = divideValues(s1, s2);
                    break;
                default:
                    System.out.println("Unrecognized operation!");
                    return;
            }

            System.out.println("The answer is " + result);

        } catch (Exception e) {
            System.out.println("Number formatting exception " + e.getMessage());

        }
    }

    private static double addValues(String s1, String s2) {
        double d1 = Double.parseDouble(s1);
        double d2 = Double.parseDouble(s2);
        return d1 + d2;
    }

    private static double subtractValues(String s1, String s2) {
        double d1 = Double.parseDouble(s1);
        double d2 = Double.parseDouble(s2);
        return d1 - d2;
    }

    private static double multiplyValues(String s1, String s2) {
        double d1 = Double.parseDouble(s1);
        double d2 = Double.parseDouble(s2);
        return d1 * d2;
    }

    private static double divideValues(String s1, String s2) {
        double d1 = Double.parseDouble(s1);
        double d2 = Double.parseDouble(s2);
        return d1 / d2;
    }

    private static String getInput(String prompt) {
        System.out.print(prompt);
        Scanner sc = new Scanner(System.in);
        return sc.nextLine();
    }

}


texts:
Some of my tests require that I need to test the date time results (like time stamps etc.). In order to be able to test the date time string I created a simple DateTime abstraction that I'm going to use in other projects later. It should replace direct calls to DateTime.(Utc)Now. Or should I rather call it TestValue instead of ConstValue?

public abstract class DateTimeProvider
{
    public abstract DateTime Value { get; }

    public DateTime? ConstValue { get; set; }

    public static implicit operator DateTime(DateTimeProvider dateTimeProvider)
    {
        return dateTimeProvider.Value;
    }
}

public class NowDateTimeProvider : DateTimeProvider
{
    public override DateTime Value
    {
        get { return ConstValue ?? DateTime.Now; }
    }
}

public class UtcNowDateTimeProvider : DateTimeProvider
{
    public override DateTime Value
    {
        get { return ConstValue ?? DateTime.UtcNow; }
    }
}


texts: Fantasy Game Inventory - Automate the Boring Stuff with Python

texts:
Below is my code for the Fantasy Game Inventory problem from Chapter 5 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner or more efficient?
The code starts out with a dictionary "inv" that contains the player's current inventory as well as a list "dragon_loot" that contains the items from the dead dragon. The goal of the code is to combine the list with the dictionary while increasing the quantity of duplicate items.
As a note, I am  using the starting list from the previous question simply because it seems impossible to kill a dragon without possessing a weapon :)

You are creating a fantasy video game. The data structure to model the player’s inventory will be a dictionary where the keys are string values describing the item in the inventory and the value is an integer value detailing how many of that item the player has. For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so on.
List to Dictionary Function for Fantasy Game Inventory
Imagine that a vanquished dragon’s loot is represented as a list of strings like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this:

def addToInventory(inventory, addedItems):
    # your code goes here

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

The output of the following code is:

Inventory:
1 rope
6 torch
45 gold coin
2 dagger
12 arrow
1 ruby

Total number of items: 67

Thank you in advance. I have learned a lot from the comments I received for my previous questions!

from collections import Counter

# players current inventory before killing dragon
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

# items from the slain dragon
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# this function prints the players inventory in a list and reports the total items
def display_inventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + " " + str(k))
        item_total = item_total + int(v)
    print("\nTotal number of items: " + str(item_total))

# this function adds the dragon's stuff to the players inventory
def add_to_inventory(inventory, added_items):
        added_items_dict ={i:added_items.count(i) for i in added_items}
        inv = Counter(inventory) + Counter(added_items_dict)
        return inv

inv = add_to_inventory(inv, dragon_loot)
display_inventory(inv)


texts:
I'm calling a view into a view. Am I doing correctly, or is this a bad practice?

                 Nuevo Usuario

        <?php $this->load->view('modules/user/form_add_user'); ?>


texts: Calculating a page size to execute a subset of jobs at a time

texts:
We have to execute a bunch of jobs , each have an ID and they are passed on to the processor . Since the processor can only work on a limited number of jobs (denoted by deleteBatchSizeMax in the code snippet),we are using a paged approach so that only a subset is picked up by the processor.To implement this we have a functionality which calculates the Page Size. It takes in the total number of jobs, and the max page size. The code handles the situation where the page size may not be an exact multiple , example 22 items have a deleteBatchSizeMax of 10. This translates to 22/10  so it gives us a page size of 3 where the jobs are executed in chunks of 10,10,2.
Hence wrote the below described function!
    private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax)
=> totalNumberOfJobs % deleteBatchSizeMax != 0
            ? (totalNumberOfJobs / deleteBatchSizeMax) + 1
            : totalNumberOfJobs / deleteBatchSizeMax;

I am hearing complaints that apparently its not readable and I should do the if-else block.  I think that the variable names are well defined , code is well commented (omitted here) and self explanatory.
I wanted to know the feedback of the community.


texts: Simulation of Central Limiting Theorem (CLT)

texts:
The following is the simulation of Central Limiting Theorem from Statistics:

class MyRandom:
    m = 4294967296;# modulus
    a = 1664525; # multiplier
    c = 1013904223; # increment
    seed = 1; #initial seed
    def NextInt(self):
        self.seed = (((self.a * self.seed + self.c) % self.m));
        return self.seed;

    def NextIntMm(self, mins, maxs):
        temp = self.NextInt();
        ddd = float(temp) / float(self.m);
        returns =  int((maxs - mins) * ddd + mins);
        return returns;

    def NextDouble(self):
        temp = self.NextInt();
        return float(temp) / float(self.m);

    def NextDoubleMm(self, mins, maxs):
        temp = self.NextInt();
        fraction = float(temp) / float(self.m);
        return (maxs - mins) * fraction + mins;

#################################################################
N = 999999;
r = MyRandom();
population = [];
population_sum = 0;

for i in range(0, N):
    x = r.NextDouble();
    population.append(x);
    population_sum = population_sum + x;

population_mean = population_sum / len(population);

print("Population mean = ", population_mean);

##################################################################
rnd_num_count = 30;
sample_size = 12;
sample_means = [];
sum_of_sample_mean = 0;

for i in range(0, rnd_num_count):
    sums = 0;
    for j in range(0, sample_size):
        index = r.NextIntMm(0, N - 1);
        element = population[index];
        sums = sums + element;

sample_mean = sums / sample_size;
sum_of_sample_mean = sum_of_sample_mean + sample_mean;
sample_means.append(sample_mean);

print("Mean of sample mean = ", sum_of_sample_mean/ len(sample_means));

Here, Normal Distribution of population is used.

Can you review this and point out any possible improvement needed?

N.B. Defining a random number generator is part of the requirement.


texts: An array function that returns an array containing all elements appearing a certain number of times

texts:
Array.prototype.itemsWithQuantity = function(n) {
    var counts = {};
    var result = [];
    var i = this.length;
    while(i--){
        counts[this[i]] = counts[this[i]] == undefined ? 1 : counts[this[i]] + 1;
    }
    i = this.length;
    var alreadyPushed = {};
    while(i--){
        if(counts[this[i]] == n && !alreadyPushed[this[i]]){
            alreadyPushed[this[i]] = true;
            result.push(this[i]);
        }
    }
    return result;
};

Above is my function that returns all the items in an array with a certain quantity. E.g., [1,2,3,2,3,4].itemsWithQuantity(2) == [2,3].

Not only is the code kinda ugly, but I also have a feeling there's a more efficient way to do it that I'm not spotting.


texts: Simple SqlHelper which wraps ADO.NET methods

texts:
I am creating a simple SqlHelper which will simplify the ADO.NET method usage. Can someone please review this class for any issue or missing something?

public static class SqlHelper
{
    public static async Task<int> ExecuteNonQueryAsync(string connectionString, CommandType cmdType, string cmdText,
        params SqlParameter[] commandParameters)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand(cmdText, connection))
            {
                try
                {
                    command.CommandType = cmdType;
                    command.Parameters.AddRange(commandParameters);
                    connection.Open();
                    return await command.ExecuteNonQueryAsync();
                }
                finally
                {
                    connection.Close();
                }
            }
        }

    }

    public static async Task<SqlDataReader> ExecuteReaderAsync(string connectionString, CommandType cmdType,
        string cmdText, params SqlParameter[] commandParameters)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand(cmdText, connection))
            {
                try
                {
                    command.CommandType = cmdType;
                    command.Parameters.AddRange(commandParameters);
                    connection.Open();
                    return await command.ExecuteReaderAsync();
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }

    public static async Task<object> ExecuteScalarAsync(string connectionString, CommandType cmdType, string cmdText,
        params SqlParameter[] commandParameters)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand(cmdText, connection))
            {
                try
                {
                    command.CommandType = cmdType;
                    command.Parameters.AddRange(commandParameters);
                    connection.Open();
                    return await command.ExecuteScalarAsync();
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }

}


texts:
I would like to get you opinion on this class, which is used to send HTTP requests (at that moment only POST method).

It is working ok, but I would like to get response on maintainability, reusability, security, code formatting, etc...

Class HttpRequest{

    private $POST = 'POST';
    private $PUT = 'PUT';
    private $GET = 'GET';
    private $DELETE = 'DELETE';
    private $PATCH = 'PATCH';

    private $body;
    private $options;
    private $handle;
    private $httpCode;
    private $response;

    public function __construct(){}

    /**
     * send post request
     * @param url
     * @param header
     * @param options
     * @param body
     * @return json object
     */
    public function post($url, $header, $options, $body){
        if(!$this->handle || get_resource_type($this->handle) == "Unknown"){
            $this->handle = curl_init();
        }
        curl_setopt($this->handle, CURLOPT_URL, $url);
        curl_setopt($this->handle, CURLOPT_HTTPHEADER, $header);
        curl_setopt_array($this->handle, $options);
        // curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, true);
        // curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $this->POST);
        curl_setopt($this->handle, CURLOPT_POSTFIELDS, $body);
        $this->response = curl_exec($this->handle);
        $this->httpCode = curl_getinfo($this->handle, CURLINFO_HTTP_CODE);
        curl_close($this->handle);
        return $this->response;
    }

    public function getResponse(){
        return $this->response;
    }

    public function getHttpCode(){
        return $this->httpCode;
    }

    /**
     * send get request
     * @param url
     * @param header
     * @param options
     */
    public function get($url,$header=array(), $options=array()){
        /**
         * @todo
         * implemets this method
         */
    }

    /**
     * send patch request
     */
    public function patch(){
        /**
         * @todo
         * implemets this method
         */
    }
    /**
     * send delete request
     */
    public function delete(){
        /**
         * @todo
         * implemets this method
         */
    }
    /**
     * send put request
     */
    public function put(){
        /**
         * @todo
         * implemets this method
         */
    }
}

?>


texts: Project Euler - Problem No.5 - Smallest multiple

texts:
Here's the problem at hand:

  2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
  What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Here's the code Ive written to solve it:

from math import sqrt

def prime_factorization(n: int) -> dict:
    '''
    Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers
    and the values are the powers in the factorization for the appropriate prime number key.
    :param n: an integer we want to compute he's prime factorization
    '''
    prime_dict = {}

    # dealing with even prime numbers - e.g. 2
    while n % 2 == 0:
        if 2 not in prime_dict:
            prime_dict[2] = 0
        prime_dict[2] += 1
        n = n // 2

    # dealing with odd numbers
    upper_bound = int(sqrt(n))
    for i in range(3,upper_bound+1):
        while n % i == 0:
            if i not in prime_dict:
                prime_dict[i] = 0
            prime_dict[i] += 1
            n = n // i

    # In case n is prime by itself
    if n > 1:
        prime_dict[n] = 1

    return prime_dict

def smallest_dividable_num(n:int) -> int:
    '''
    Returns the smallest integer whose dividable by all the numbers from 1 to n.
    :param n: an integer upper bound which we want to compute the smallest divisable num from 1 to it.
    '''
    prime_dict = {}
    for i in range(1,n+1):
        tmp_dict = prime_factorization(i)
        for k,_ in tmp_dict.items():
            if k not in prime_dict or prime_dict[k] < tmp_dict[k]:
                prime_dict[k] = tmp_dict[k]
    res = 1
    for k,v in prime_dict.items():
        res = res*(k**v)
    return res

And here's a small test case Ive written for this code:

from ProjectEuler.problem5 import smallest_dividable_num

if __name__ == "__main__":
    # The prime factorization is {2**3,3**2,5,7} -> returns 2520
    print(smallest_dividable_num(10))
    # The prime factorization is {2**2,3,5} -> returns 60
    print(smallest_dividable_num(6))
    # The prime factorization is {2**4,3**2,5,7,11,13,17,19} -> returns 232792560
    print(smallest_dividable_num(20))

Let me know your thoughts about my solution. thanks :)


texts:
I'm not sure if a Markov Chain generator is the proper term for this, really all it does is create the chain, it doesn't generate any text from it. The code is below, and I'd appreciate any feedback: bad practices, code smells, poor naming, anything at all really.

module Main where
import Data.List(find, delete)

type Chain = [Node]
data Node = Node {nPrefix :: String, nSuffixes :: [String]} deriving (Show, Eq, Read)

generateChain :: Int -> [String] -> Chain
generateChain n = foldl (learnSample n) []

learnSample :: Int -> Chain -> String -> Chain
learnSample n chain sample = foldl learnGroup chain groups
    where groups = (groupings (n+1) . words) sample

learnGroup :: Chain -> [String] -> Chain
learnGroup chain group =
    case find (\node -> nPrefix node == prefix) chain of
        Just node -> delete node chain ++ [Node prefix (nSuffixes node ++ [suffix])]
        Nothing   -> chain ++ [Node prefix [suffix]]
    where
        prefix = unwords $ init group
        suffix = last group

groupings :: Int -> [a] -> [[a]]
groupings n list
    | length list >= n = take n list : groupings n (drop 1 list)
    | otherwise        = []

main :: IO ()
main = print $ generateChain 1 ["a b a b a c a d"]


texts: HashTable with separate chaining and struct

texts:
I'm pretty new to C and I'm trying to implement a hashtable with chaining for a struct I created:

HASH.h:

#ifndef HASH_H
#define HASH_H
#include <stdio.h>
#include <stdlib.h>
#define MAXNAME 8000

/* Utilizing separate chaining and hashtables to
 * save the informations about objectives
 */

typedef struct {
   unsigned long int id, duration;
   char name [MAXNAME];
   unsigned long int *dep;
}Objective

typedef struct node{
   Objective objective;
   struct node*next;
}*link

void hashInit(int m);
link insertBegin(link head, Objective obj);
void objInsert(Objective obj);

#endif

HASH.c:

#include "HASH.h"
#include <stdlib.h>
#include <stdio.h>

static link *heads;
static int M;

int hash(Key value, int m){
   return value%m;
}

void hashInit(int m){
   int i;
   M = m;
   heads = (link*)malloc(M*sizeof(link));
   for(i = 0; i < M; i++)
       heads[i] = NULL;
   }

link insertBegin(link head, Objective obj){
    link new = (link)malloc(sizeof(struct node));
    new->value = obj;
    new->next = head;
    return new;
}

void objInsert(Objective obj){
   int i = hash(key(obj), M);
   heads[i] = insertBegin(heads[i], obj);
}

I'm still in the very beginning and don't have much but I'm just looking for advice on how and if I can improve what I did here, what I might have done wrong, and if I'm on the right path.


texts: Random Distribution to fit an Average Python

texts:
This is from my own question on Stack Overflow.

I want to get average numbers from a range such that they fit an intended average.  I expect something bell-curve-like, but asymmetrical unless the average is the mean of the range.  The function should allow for any degree of deviation.  In my Overflow question, I wanted it to pick from a list, but that's an easy modification if my idea works.

This is what I've come up with: (imports: numpy and random)

def randlist(minn, maxn, goaln, countn):
    nlist = []
    for i in range(0, countn):
        if len(nlist) > 10:
            ave = numpy.mean(nlist)
            if ave > goaln:
                a = random.uniform(minn, goaln)
            else:
                a = random.uniform(goaln, maxn)
        else:
            a = random.uniform(minn, maxn)
        nlist.append(a)
    return nlist

Trying it out:

b = randlist(1, 10, 7, 1000)
print len(b)
>> 1000
print numpy.mean(b)
>> 6.99951157861

I'm no mathematician; is this as functional as it appears to me to be?


texts:
I made a class that will be used to get an image properties like width, height, and MIME type.

<?php
namespace Resizer;

class ImageResizer
{
    protected $imageOrig = null;
    protected $width = null;
    protected $height = null;
    protected $mime = null;

    public function loadImage($path = null)
    {
        $data = getimagesize($path);
        $this->imageOrig = $data;
        $this->width = $data[0];
        $this->height = $data[1];
        $this->mime = $data['mime'];
    }

    public function getOriginalImage()
    {
        return $this->imageOrig;
    }

    public function getWidth()
    {
        return $this->width;
    }

    public function getHeight()
    {
        return $this->height;
    }

    public function getMime()
    {
        return $this->mime;
    }
}

And then I created tests with PHPUnit

<?php
use Resizer\ImageResizer;

class ImageResizerTest extends PHPUnit_Framework_TestCase
{
    public function testLoadImageFromPathReturnsImage()
    {
        $expected = getimagesize('./assets/tingey.jpg');
        $resizer = new ImageResizer();
        $resizer->loadImage('./assets/tingey.jpg');

        $this->assertEquals($expected, $resizer->getOriginalImage());
    }

    public function testGetImageReturnsImageData()
    {
        $resizer = new ImageResizer();
        $resizer->loadImage('./assets/tingey.jpg');
        $expected = getimagesize('./assets/tingey.jpg');
        $imageOrig = $resizer->getOriginalImage();
        $this->assertEquals($expected, $imageOrig);
    }

    public function testGetWidthReturnsImageWidth()
    {
        $resizer = new ImageResizer();
        $resizer->loadImage('./assets/tingey.jpg');
        $expected = getimagesize('./assets/tingey.jpg');
        $this->assertEquals($expected[0], $resizer->getWidth());
    }

    public function testGetHeightReturnsImageHeight()
    {
        $resizer = new ImageResizer();
        $resizer->loadImage('./assets/tingey.jpg');
        $expected = getimagesize('./assets/tingey.jpg');
        $this->assertEquals($expected[1], $resizer->getHeight());
    }

    public function testGetMimeReturnsImageMime()
    {
        $resizer = new ImageResizer();
        $resizer->loadImage('./assets/tingey.jpg');
        $expected = getimagesize('./assets/tingey.jpg');
        $this->assertEquals($expected['mime'], $resizer->getMime());
    }
}

Am I doing anything wrong in my unit testing? What can I do better?


texts: Simplify definition of a dictionary with default return value

texts:
I need a constant (dictionary with values and default return value if there are no defined value for a key). Searching for any ways to simplify the code.

Without a default value I can simply define a dictionary like this:

REDUCE_VALUE = {
    "honda": 0.95,
    "suzuki": 0.85,
    "yamaha": 0.87
}

But with a default value it looks not so good:

from collections import defaultdict
REDUCE_VALUE = defaultdict(lambda: "0.9")
REDUCE_VALUE["honda"] = 0.95
REDUCE_VALUE["suzuki"] = 0.85
REDUCE_VALUE["yamaha"] = 0.87


texts:
I have a list of 32-bit signed numbers in range [-10e5, 10e5] in string form read from stdin, and I would like to compute and print their sum in the fastest way possible.

The bottleneck is in the fast_atoi function (checked using callgrind)

I thinking of two ways for improvement : cache misses seems to be an issue, and SIMD (ideally, only SSE and SSE2) instructions could come to help, however i don't really know how to use them...

The input is in this form (signed 32-bit integers between -10e5 and 10e5, separated by '\n') :

4
10
5
3
1

And the program should output :

19

Right now, my code is :

#include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>

#define likely(x)      __builtin_expect(!!(x), 1)
#define unlikely(x)    __builtin_expect(!!(x), 0)

char* data alignas(16) = nullptr;

inline void read_data()
{
    struct stat sb;
    int rc = fstat( STDIN_FILENO, &sb );
    data = (char*)malloc(sb.st_size + 1 );
    size_t totalRead = 0UL;
    while (totalRead  < sb.st_size)
    {
        ssize_t bytesRead = read(STDIN_FILENO, data + totalRead, sb.st_size - totalRead);
        if ( bytesRead <= 0 )
        {
            break;
        }
        totalRead += bytesRead;
    }
}

inline int fast_atoi(char ** str )
{
    int val = 0;
    char neg = 1;
    if (**str == '-')
    {
        neg = -1;
        (*str)++;
    }
    while(unlikely(**str != '\n'))
    {
        val = val*10 + (*(*str)++ - '0');
    }
    ++*str;
    return val*neg;
}
int32_t process()
{
    size_t count = fast_atoi(&data);
    int32_t sum = 0;
    for (unsigned ii = 0; unlikely(ii < count); ii++ )
    {
        sum += fast_atoi(&data);
    }
    return sum;
}
inline void write_ans(int32_t sum)
{
    printf("%d", sum);
}
int main()
{
    read_data();
    int32_t val = process();
    write_ans(val);
}

Callgrind report for this code : https://pastebin.com/Pnd0FzZb
Assembly output : https://godbolt.org/g/Ng3sVM


texts:
Task

Find the smallest number of cuts required to break a string into a set of valid palindromes.
For example:

ababbbabbababa becomes a|babbbab|b|ababa (cuts = 3)
partytrapb becomes partytrap|b (cuts = 1)

Note: all strings of length 1 are palindromes as a single character reads the same forward and backward

import re
def find_paritions(lst, word, running=[]):
    for (index,item) in enumerate(lst):
        if index > 0:
            running.pop()
        running = running + [item]
        if item[1] == len(word):
            complete_paths.append(running)
            return
        to_explore = []
        end = item[1]
        for item_next in list_parition_index:
            if item_next[0] == end:
                to_explore.append(item_next)
        if len(to_explore) == 0:
            return
        find_paritions(to_explore,word,running)

    return complete_paths

complete_paths=[]
word = "ababbbabbababa"
start = 0
end = 1
parition_count =0
list_parition_index = []
for start in range (len(word)):
    end=start+1
    while end < len(word) + 1:
        if word[start:end] == word[start:end][::-1]:
            list_parition_index.append([start,end])
            end +=1
        else:
            end +=1
list_zeroes = [x for x in list_parition_index if x[0] == 0]

x = find_paritions (list_zeroes,word)
print(f"The total number of divisions required is {len(min(x,key=len))-1}")
print(min(x,key=len))


texts: Statistical calculations with sets of genes

texts:
The following piece of code executes 20 million times each time the program is called, so I need a way to make this code as optimized as possible.

int WilcoxinRST::work(GeneSet originalGeneSet, vector<string> randomGenes) {
vector<string> geneIDs;
vector<bool> isOriginal;
vector<int> rank;
vector<double> value;
vector<int> score;
int genesPerSet = originalGeneSet.geneCount();
unsigned int totalGenes, tempScore;
/**
 * Fill the first half of the vectors with original gene set data
 */
totalGenes = genesPerSet * 2;
for (int i = 0; i < genesPerSet; i++) {
    geneIDs.push_back(originalGeneSet.getMemberGeneAt(i));
    isOriginal.push_back(true);
    value.push_back(fabs(expressionLevels.getValue(geneIDs[i], statType)));
}
/**
 * Fill the second half with random data
 */
for (unsigned int i = genesPerSet; i < totalGenes; i++) {
    geneIDs.push_back(randomGenes.at(i - genesPerSet));
    isOriginal.push_back(false);
    value.push_back(fabs(expressionLevels.getValue(geneIDs[i], statType)));
}
totalGenes = geneIDs.size();
/**
 * calculate the scores
 */
if (statType == Fold_Change || statType == T_Statistic
        || statType == Z_Statistic) {
    //      Higher value is a winner
    for (unsigned int i = 0; i < totalGenes; i++) {
        tempScore = 0;
        if (!isOriginal[i]) {
            for (int j = 0; j < genesPerSet; j++) {
                if (value.at(i) > value.at(j)) {
                    tempScore++;
                }
            }

        } else {
            for (unsigned int j = genesPerSet; j < totalGenes; j++) {
                if (value.at(i) > value.at(j)) {
                    tempScore++;
                }
            }

        }

        score.push_back(tempScore);
    }

} else if (statType == FDR_PValue || statType == PValue) {
    // Lower value is a winner
    for (unsigned int i = 0; i < totalGenes; i++) {
        tempScore = 0;
        if (!isOriginal[i]) {
            for (int j = 0; j < genesPerSet; j++) {
                if (value.at(i) < value.at(j)) {
                    tempScore++;
                }
            }

        } else {
            for (unsigned int j = genesPerSet; j < totalGenes; j++) {
                if (value.at(i) < value.at(j)) {
                    tempScore++;
                }
            }

        }

        score.push_back(tempScore);
    }

} else {
    cout << endl << "ERROR. Statistic type not defined." << endl;
}

/**
 * calculate Ua, Ub and U
 */
int U_Original = 0, U_Random = 0, U_Final;
for (int j = 0; j < genesPerSet; j++) {
    U_Original += score[j];
}
for (unsigned int j = genesPerSet; j < totalGenes; j++) {
    U_Random += score[j];
}
U_Final = (U_Original < U_Random) ? U_Original : U_Random;

/**
 * calculate z
 */
double Zn, Zd, Z;
Zn = U_Final - ((genesPerSet * genesPerSet) / 2);
Zd = sqrt(
        (double) (((genesPerSet * genesPerSet
                * (genesPerSet + genesPerSet + 1)))) / 12.0);
Z = Zn / Zd;

/**
 * Return 0/1/2
 * 2: p value < 0.01
 * 1: 0.01 < p value < 0.05
 * 0: p value > 0.05
 */
if (fabs(Z) > 2.303)
    return 2;
else if (fabs(Z) > 1.605)
    return 1;
else
    return 0;
}


texts: The best way to place callback definition

texts:
In JavaScript we can write callback definition in  many different ways:

Definition after usage:

var fs = require('fs')
fs.readFile('movie.mp4', finishedReading)

function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
}

Definition before usage:

var fs = require('fs')

function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
}

fs.readFile('movie.mp4', finishedReading)

In-line definition:

var fs = require('fs')

fs.readFile('movie.mp4', function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
})

Which way is the best for code readability and maintainability?


texts:
Okay code reviewers, I need you to make my FizzBuzz code even better. Any suggestions for improvement, optimizations, etc.

public final class FizzBuzz {

    private FizzBuzz() {};

    /**
     * comparisons for a multiple of 3 = 2
     * comparisons for a multiple of 5 = 2
     * comparisons for a multiple of 15 = 2
     *
     */
    public static void fizzBuzzBad() {
        // most common thought process
        for (int n = 1; n < 20; n++) {
            if (n % 3 == 0) {
                System.out.print("fizz");
            } else if (n % 5 == 0) {
                System.out.println("buzz");
            } else {
                System.out.println("\n" + n);
            }
        }
    }

    /**
     * comparisons for a multiple of 3 = 2
     * comparisons for a multiple of 5 = 2
     * comparisons for a multiple of 15 = 1 <--- here is the savings.
     *
     * This saves the number of comparison for 15's.
     */
    public static void fizzBuzzBetter() {
        // most common thought process
        for (int n = 1; n < 20; n++) {
            if (n % 15 == 0) {
                System.out.print("fizzbuzz");
            } else if (n % 3 == 0) {
                System.out.print("buzz");
            } else if (n % 5 == 0) {
                System.out.println("fizz");
            } else {
                System.out.println("\n" + n);
            }
        }
    }

    public static void main(String[] args) {
        fizzBuzzBad();
        System.out.println("--------------------------------------------");
        fizzBuzzBetter();
    }

}


texts: Turn a non-blocking concurrent queue into a blocking concurrent queue

texts:
Microsoft Visual Studio offers a non-blocking concurrent queue class, concurrency::concurrent_queue, based on Intel's TBB. I am using this as a base for a blocking single producer, single consumer concurrent queue.

I am overriding the push and try_pop methods:

#include <concurrent_queue.h>
/**
 * Single producer, single consumer blocking concurrent queue.
 */
template<typename T>
class SPSCBlockingQueue final : public concurrency::concurrent_queue<T>
{
  public:

    /**
     * Push an element to the back of the queue.
     */
    void push(const T& src)
    {
        _push(src);
    }

    /**
     * Push an element to the back of the queue.
     */
    void push(T&& src)
    {
        _push(std::move(src));
    }

    /**
     * Pop an element from the head of the queue. This method will wait
     * until there is an item in the queue that can be dequeued.
     *
     * @param dest a reference to a location to store the dequeued item
     * @return {@code true} if an item was successfully dequeued, otherwise {@code false}
     */
    bool try_pop(T& dest)
    {
        std::unique_lock<std::mutex> lock(_mtx);

        auto res = concurrency::concurrent_queue<T>::try_pop(dest);
        if (!res)
        {
            // The queue must be empty.
            hasData = false;

            // Wait until there is some data...
            _cv.wait(lock, [&] { return hasData; });

            // This should now work.
            res = concurrency::concurrent_queue<T>::try_pop(dest);
        }

        // res should be true.
        return res;
    }

    /**
     * Pop an element from the head of the queue. This method will wait
     * until there is an item in the queue that can be dequeued.
     *
     * @return the dequeued item.
     */
    T pop()
    {
        T dest;
        try_pop(dest);
        return dest;
    }

  private:

    std::mutex _mtx;
    std::condition_variable _cv;
    bool hasData = false;

    template<typename E>
    void _push(E&& src)
    {
        bool notify = false;

        std::unique_lock<std::mutex> lock(_mtx);
        if (!hasData)
        {
            notify = true;
            hasData = true;
        }

        concurrency::concurrent_queue<T>::push(std::forward<E>(src));

        lock.unlock();

        if (notify)
            _cv.notify_one();
    }
};

Here is some unit test code, using the Google test framework:

TEST(CheckTools, BlockingQueue)
{
    enum Data { D1, D2, D3, DataEnd };
    SPSCBlockingQueue<Data> q;

    auto dataElements = {
        D2, D1, D2, D3, D2, D1, D1, D3, D3, D1,
        D1, D2, D1, D3, D2, D2, D3, D2, D1
    };

    vector<Data> dataToPush = dataElements;
    vector<Data> result;

    // Consumer thread...
    auto t = thread([&]
    {
        while (true)
        {
            auto dataEle = q.pop();

            if (dataEle == DataEnd)
                break;

            result.push_back(dataEle);
        }
    });

    // Producer code...
    auto i=0;
    for (auto e : dataToPush)
    {
        if (i++ % 3 == 0)
            this_thread::sleep_for(chrono::milliseconds(250));

        q.push(e);
        i++;
    }

    q.push(DataEnd);
    t.join();

    ASSERT_EQ(result, vector<Data>{ dataElements });
}

I am interested in comments regarding efficiency and correctness.


texts: Find the largest continuous descending sum in a 2d matrix

texts:
Given a 2d array, the problem is to find the largest sum, where each subsequent is >= the previous digit but < all of the 'neighbour' digits. You can only move up, down, left and right.

My solution will run in \$O(N*M)\$ time with \$O(N*M)\$ space (please correct me if I'm wrong).

The solution is as follows: Start at an arbitrary point and look for the closest largest neighbor (as described above). Once found, append it to the path and mark as visited. Continue these steps until you have no where else to visit.

Code is below, with the the answer being [10, 9, 6, 4, 2]. Thank you

nums = [
  [10,8,4],
  [9,6,8],
  [2,4,3]
]

def get_largest_neighbour(i, j, previous, visited):
    max_location = -1, -1
    max_neighbour = -1

    # look up
    if i-1 >= 0 and nums[i-1][j] < previous and visited[i-1][j] == False:
        max_neighbour = nums[i-1][j]
        max_location = i-1, j

    # look down
    if i+1 < 3:
        if nums[i+1][j] > max_neighbour and nums[i+1][j] < previous and visited[i+1][j] == False:
            max_neighbour = nums[i+1][j]
            max_location = i+1, j

    # look left
    if j-1 >= 0:
        if nums[i][j-1] > max_neighbour and nums[i][j-1] < previous and visited[i][j-1] == False:
            max_neighbour = nums[i][j-1]
            max_location = i, j-1

    # look right
    if j+1 < 3:
        if nums[i][j+1] > max_neighbour and nums[i][j+1] < previous and visited[i][j+1] == False:
            max_neighbour = nums[i][j+1]
            max_location = i, j+1

    return max_location

def max_sum(i, j, path, visited):
    if i >= 3 or i < 0 or j >= 3 or j < 0:
        return

    if visited[i][j] == True:
        return

    # mark as visited and append to path
    visited[i][j] = True
    path.append(nums[i][j])

    # find the next largest path to search
    next_step_i, next_step_j = get_largest_neighbour(i, j, path[-1], visited)

    # there is no where to go, so stop iterating and backtrack
    if next_step_i == -1:
        return

    max_sum(next_step_i, next_step_j, path, visited)

    return path

def largest_continious_sum():
    if len(nums) <= 1:
        return 0

    visited = [[False for x in range(3)] for j in range(3)]
    path = []

    print max_sum(0, 0, path, visited)

largest_continious_sum()


texts:
Moved to Code Review as per comments received on https://stackoverflow.com/questions/20907502/can-this-while-loop-be-made-cleaner

Is there a way to make the following while loop a little more optimized? What bugs me in particular is the fact that I have to repeat code (closing buffers and returning a value) both inside and outside the if condition and I wanted to get opinions on whether there might be a better /more performance-oriented way to handle such code.

While I've posted the entire method, the part I'm more interested in comments on is how the while loop can be optimized. Ofcourse, comments on the remainder of the code are also welcome, but not essential.

    private String getRandomQuote(int lineToFetch)
        throws IOException {
    //1. get path
    AssetManager assets = getApplicationAssets();
    String path = null;
    path = getAssetPath(assets);

    //2. open assets
    InputStream stream = assets.open(path);
    InputStreamReader randomQuote = new InputStreamReader(stream);

    //3. Get BufferedReader object
    BufferedReader buf = new BufferedReader(randomQuote);

    String quote = null;
    String line = null;
    int currLine = 0;

    //4. Loop through using the new InputStreamReader until a match is found
    while ((line = buf.readLine()) != null) {
        // Get a random line number
        if (currLine == lineToFetch) {
            quote = line;
            Log.v("LINE", line);
            randomQuote.close();
            buf.close();
            return quote;
        } else
            currLine++;
    }
    randomQuote.close();
    buf.close();
    return quote;
}


texts: Removing by indices several elements from a vector

texts:
From a sorted vector of indices (toRemove), I would like to remove from another vector (v) the elements at these indices. Note that I need to preserve the order of the remaining elements in v. toRemove can be modified at will however.

An easy way to do it would be to start with the last element of toRemove and remove them sequentially. However, that would require copying elements at the end of the vector several times which is slow when the vector is large.

Here is an alternative using the erase-remove idiom:

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

template <typename INT, typename T> // INT could be int, unsigned int, char, size_t, etc...
void removeIndicesFromVector(std::vector<T>& v, std::vector<INT>& rm )
{
  // For speed, I am assuming that 'rm' is sorted
  size_t rm_index = 0;
  v.erase(
    std::remove_if(std::begin(v), std::end(v), [&](T& elem)
    {
        if (rm.size() != rm_index && &elem - &v[0] == rm[rm_index])
        {
           rm_index++;
           return true;
        }
        return false;
    }),
    std::end(v)
  );
}

template <typename T>
void print(std::vector<T> v)
{
    for (size_t i = 0 ; i < v.size();i++)
    {
        std::cout << v[i] << " ";
    }
    std::cout << std::endl;
}

int main()
{
    std::vector<std::string> v = {"Alice", "Smith", "is", "very", "clever", "and", "is", "very", "nice"};
    print(v);
    std::vector<int> toRemove = {1,6};
    removeIndicesFromVector(v,toRemove);
    print(v);

    return 0;
}

The code outputs as expected:

Alice Smith is very clever and is very nice
Alice is very clever and very nice

Is there a "better" alternative to my function removeIndicesFromVector?

By "better", I mean faster / better names / cleaner / more standard / one that is as fast but does not assume 'rm' is sorted. If it matters, note that the object that will need to be removed will rarely be any bigger than the std::strings considered here but the vector will be much longer.


texts: Optimizing Cassandra Schema to avoid deleting data

texts:
I come from MySQL type of mind frame but have worked with MongoDB and ElasticSearch type of NoSQL.

I'm using a small use case of Cassandra to able to scale a playlist format for users.

In C* Summit 2013 by Axel Liljencrantz, he states how deletions are messy - and that deletion in Cassandra are actually tombstones (hence you should not use null as a value).

Below is my keyspace / table in CQL 3.0 format - it's basic:

    CREATE TABLE music_service.my_music_song (
    member_id int,
    song_id int,
    title text,
    add_time timestamp,
    album_id int,
    PRIMARY KEY ((member_id, song_id), title)
) WITH CLUSTERING ORDER BY (title ASC)
    AND bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'min_threshold': '4', 'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';
CREATE INDEX my_music_song_member_id_idx ON jomedia.my_music_song (member_id);

Queries needed are:

Find song_id from a member_id sorted by song title
Update song title given song_id
Delete a song from member_id playlist
Delete an entire playlist by member_id

So far I can do both the write and the read - however I want to make sure that my delete and my schema is correct considering I am coming from a MySQL mindset.


texts:
This is meant to be a drop in replacement for getline as it's not crossplatform.
I am trying to do as minimal work as possible in here including only calling strlen once at the very end to calculate the size of the final block.
returns -1 for error, 0 for EOF, 1 for success
The way it works it by setting the last two bytes in the array as [0, 1] and if the buffer is filled it will look like [X,0], X being either LF where we are done, or something else meaning we need to realloc and loop again unless we are at eof.
int
fgets_line(char **line, size_t *capacity, size_t *length, FILE *stream) {
  if (!*line && !(*line = malloc(*capacity = 64)))
    return *capacity = 0, -1;
  (*line)[0] = 0;
  if (length)
    *length = 0;
  char *position = *line;
  while (1) {
    (*line)[*capacity - 1] = 1;
    (*line)[*capacity - 2] = 0;
    if (fgets(position, *line + *capacity - position, stream)) {
      if ((*line)[*capacity - 1] == 0
       && (*line)[*capacity - 2] != '\n') {
        size_t new_capacity = *capacity * 2;
        char *tmp = realloc(*line, new_capacity);
        if (tmp) {
          position = tmp + *capacity - 1;
          *line = tmp;
          *capacity = new_capacity;
        } else return -1;
      } else goto success;
    } else if (position != *line) {
      if (feof(stream))
        goto success;
      return -1;
    } else return 0;
  }
  success:
  if (length)
    *length = position - *line + strlen(position);
  return 1;
}

usage is similar to getline
int main() {
  char *line = NULL;
  size_t capacity = 0, length = 0;
  int result = 0;
  while ((result = fgets_line(&line, &capacity, &length, stdin)))
    printf("---Capacity: %-8zuLength: %-8zu---\n%s------\n", capacity, length, line);
}


texts:
I wanted to represent graphs in Python, and wrote the following class. I don't care about values associated with nodes or the weights of the connections between them, simply the connections between nodes.

Is this a good enough implementation? Or is there a significantly better way?

class Graph:
    def __init__(self, nodes):
        self.array_representation = [[] for _ in range(nodes)]

    def directly_connected(self, node_1, node_2):
        # Predicate, checks if the two nodes are connected by one edge
        return node_2 in self.array_representation[node_1]

    def connect(self, node_1, node_2):
        # Draws an edge between the node at node_1 and the node at node_2
        self.array_representation[node_1].append(node_2)
        self.array_representation[node_2].append(node_1)


texts:
I have a mixin function which is as follows -

function mixin(receiver, supplier) {
    for (var property in supplier) {
        if (supplier.hasOwnProperty(property)) {
            receiver[property] = supplier[property];
        }
    }
}

To test this function, I am using the ok method of Qunit -

test('Mixin Test Runner', function () {
    // using OK method
    ok(function () {
        var receiver = {
            name: 'Abul Moksud',
            age: '60'
        };

        var supplier = {
            hands: 2
        };

        mixin(receiver, supplier);

        return receiver.hasOwnProperty('hands') && (receiver.hands === 2);
    }(), "Abul Moksud now has two hands");
});

I am an absolute beginner in both unit testing and QUnit. Is my approach OK here, or is there any better option?


texts:
I'm using slim php and i have this simple paginated end point to get all clients, i feel like i could do some things here better, so i would appreciate all suggestions, if possible please give me code example with suggested improvements. Thank you in advance.

$app->get('/api/clients', function ($request, $response, $args) {
    require_once 'dbConnect.php';
    require_once 'shared/securityService.php';
    $queryParams = $request->getQueryParams();

    $total = getTotalCount($mysqli, $queryParams["group"]);
    $pageSize = $queryParams["pageSize"];

    $totalPages = ceil($total / $pageSize);
    $offset = ($queryParams["page"] - 1)  * $pageSize;

    if(is_numeric($queryParams["group"])) {
        $stmt = $mysqli->prepare("SELECT id, firstName, lastName, birthDate, phoneNumber, address,
            contactPerson, contactPersonPhoneNumber FROM client WHERE groupId = ? ORDER BY
            id LIMIT $pageSize OFFSET $offset");

        $stmt->bind_param("i", $queryParams["group"]);
    } else {
        $stmt = $mysqli->prepare("SELECT id, firstName, lastName, birthDate, phoneNumber, address,
            contactPerson, contactPersonPhoneNumber FROM client
            ORDER BY id LIMIT $pageSize OFFSET $offset");
    }

    $stmt->execute();
    $stmt->bind_result($id, $firstName, $lastName, $birthDate, $phoneNumber,
        $address, $contactPerson, $contactPersonPhoneNumber);

    $data = null;

    while ($stmt->fetch()) {
        $data['items'][] = array(
            'id' => $id,
            'firstName' => $firstName,
            'lastName' => $lastName,
            'birthDate' => $birthDate,
            'phoneNumber' => $phoneNumber,
            'address' => $address,
            'contactPerson' => $contactPerson,
            'contactPersonPhoneNumber' => $contactPersonPhoneNumber
        );
    }

    $data['totalItems'] = $total;

    $stmt->close();
    $mysqli->close();
    echo json_encode($data);
});

function getTotalCount($mysqli, $groupId) {
    if(is_numeric($groupId)) {
        $totalStmt = $mysqli->prepare("SELECT COUNT(id) FROM client WHERE groupId = ?");
        $totalStmt->bind_param("i", $groupId);
    } else {
        $totalStmt = $mysqli->prepare("SELECT COUNT(id) FROM client");
    }

    $totalStmt->execute();
    $totalStmt->bind_result($total);
    $totalStmt->fetch();
    $totalStmt->close();
    return $total;
}


texts:
Here is a recursive implementation of the Subset sum problem:

using System;

namespace Exercise
{
  class SubsetSum
  {
    static void Main(string[] args)
    {
         set = new int[] { 2, 3, 1, -1};
         PrintSet(set, "Initial Set.");

            sum = 4;
            Console.WriteLine("Wanted sum = {0}", sum);

            FindSubsetSum();
        }
        //-------------------------------------------------------------

        static int[] set;
        static int[] subSetIndexes;
        static int sum;
        static int numberOfSubsetSums;

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

        /*
            Method: FindSubsetSum()
        */
        private static void FindSubsetSum()
        {
            numberOfSubsetSums = 0;
            int numberOfElements = set.Length;
            FindPowerSet(numberOfElements);
        }
        //-------------------------------------------------------------

        /*
            Method: FindPowerSet(int n, int k)

        */
        private static void FindPowerSet(int n)
        {
            // Super set - all sets with size: 0, 1, ..., n - 1
            for (int k = 0; k <= n - 1; k++)
            {
                subSetIndexes = new int[k];
                CombinationsNoRepetition(k, 0, n - 1);
            }

            if (numberOfSubsetSums == 0)
            {
                Console.WriteLine("No subsets with wanted sum exist.");
            }
        }
        //-------------------------------------------------------------

        /*
            Method: CombinationsNoRepetition(int k, int iBegin, int iEnd);

        */
        private static void CombinationsNoRepetition(int k, int iBegin, int iEnd)
        {
            if (k == 0)
            {
                PrintSubSet();
                return;
            }

            for (int i = iBegin; i <= iEnd; i++)
            {
                subSetIndexes[k - 1] = i;
                ++iBegin;
                CombinationsNoRepetition(k - 1, iBegin, iEnd);
            }
        }

    }
}

Input:

  -

Output:

  Initial Set.
   {2 ,3 ,1 ,-1}
   Wanted sum = 4
   (1 ,3)
   (-1 ,3 ,2)

The algorithm is based on finding the Power setexcept the trivial empty set of indexes, which is in turn based on finding all the combinationswithout repetition of indexes with size 1, 2,..., n. Then the sets of indexes corresponding to array elements with the wanted sum are printed.

Any comments regarding the style and implementation will be appreciated.

Is the complexity of this algorithm 2n, where n - number of elements in the array?

Is there more efficient approach to that problem, probably iteration instead of recursion?

Here are the helper functions:

    private static void PrintSubSet()
    {
        int currentSubsetSum = 0;

        // accumulate sum of current subset
        for (int i = 0; i < subSetIndexes.Length; i++)
        {
            currentSubsetSum += set[subSetIndexes[i]];
        }

        // if wanted sum: print current subset elements
        if (currentSubsetSum == sum)
        {
            ++numberOfSubsetSums;

            Console.Write("(");
            for (int i = 0; i < subSetIndexes.Length; i++)
            {
                Console.Write(set[subSetIndexes[i]]);

                if (i < subSetIndexes.Length - 1)
                {
                    Console.Write(" ,");
                }
            }
            Console.WriteLine(")");
        }
    }
    //-------------------------------------------------------------

    private static void PrintSet(int[] arr, string label = "")
    {
        Console.WriteLine(label);

        Console.Write("{");
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write(arr[i]);

            if (i < arr.Length - 1)
            {
                Console.Write(" ,");
            }
        }
        Console.WriteLine("}");
    }


texts:
I've implemented constant sized circular buffer. It provides push and pop operations, along with modern emplace. It is also optimized for destruction of trivially destructible types.

I didn't include iterators since it would be strange to have one pair of begin and end for input iterators and other for output iterators. Allocator support will come in the next version.

I'd like the review to focus on performance of push (emplace) and pop operations. Also, there is a code duplication in those functions. Should I leave just emplace?

#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H

#include <cstddef>
#include <utility>

template <typename T, std::size_t mcapacity>
class circular_buffer
{
    T* data;
    T* begin;
    T* end;
    std::size_t msize;
    bool is_empty;

    template <bool trivially_destructible>
    struct destructor
    {
        void destroy(T* object)
        {
            object->~T();
        }

        void destroy_n(T* objects, std::size_t sz)
        {
            for (std::size_t i = 0; i < sz; ++i)
            {
                objects->~T();
                ++objects;
            }

            ::operator delete(objects);
        }
    };

    template <>
    struct destructor<true>
    {
        void destroy(T* object)
        {
            //empty, since trivially destroyable
        }

        void destroy_n(T* objects, std::size_t sz)
        {
            ::operator delete(objects);
        }
    };

    destructor<std::is_trivially_destructible<T>::value> destroyer;

public:
    using container = circular_buffer<T, mcapacity>;
    using value_type = T;
    using reference = value_type&;
    using pointer = T*;
    using const_reference = const reference;
    using size_type = std::size_t;

    circular_buffer():
        data((pointer)::operator new(sizeof(value_type) * mcapacity)),
        msize(0),
        begin(data),
        end(data)
    {}

    template <typename ... ArgTypes>
    void emplace(ArgTypes ... args)
    {
        end = new (end) T(args...);
        ++end;
        if (end == data + mcapacity)
        {
            end = data;
        }

        if (msize != mcapacity)
        {
            ++msize;
        }
    }

    void push(const T& value)
    {
        end = new (end) T(value);
        ++end;
        if (end == data + mcapacity)
        {
            end = data;
        }

        if (msize != mcapacity)
        {
            ++msize;
        }
    }

    void push(T&& value)
    {
        end->T(value);
        ++end;
        if (end == data + mcapacity)
        {
            end = data;
        }

        if (msize != mcapacity)
        {
            ++msize;
        }
    }

    const_reference front()
    {
        return *begin;
    }

    void pop()
    {
        destroyer.destroy(begin);
        ++begin;
        if (begin == data + mcapacity)
        {
            begin = data;
        }

        if (msize != 0)
        {
            --msize;
        }
    }

    size_type size()
    {
        return msize;
    }

    constexpr size_type capacity()
    {
        return mcapacity;
    }

    bool full()
    {
        return msize == mcapacity;
    }

    bool empty()
    {
        return msize == 0;
    }

    ~circular_buffer()
    {
        destroyer.destroy_n(data, mcapacity);
    }
};

#endif

Sample usage:

#include "circular_buffer.h"
#include <vector>
#include <iostream>

int main()
{
    circular_buffer<int, 10> buffer;

    for (int i = 0; i < 30; ++i)
    {
        buffer.push(i);
    }

    std::cout << buffer.full() << '\n'
        << buffer.empty() << '\n';

    for (int i = 0; i < 20; ++i)
    {
        std::cout << buffer.front() << ' ';
        buffer.pop();
    }

    std::cout << buffer.full() << '\n'
        << buffer.empty() << '\n';
}


texts:
Is there a better way to pass variables into a class?

public class Truck
{
    private int _wheels;
    private string _color;
    private bool _loaded;
    public int wheels { get { return _wheels; } }
    public string color { get { return _color; } }
    public bool loaded { get { return _loaded; } }

    public Truck(int wheels, string color, bool loaded)
    {
        this._wheels = wheels;
        this._color = color;
        this._loaded = loaded;
    }
}

Truck dumpTruck = new Truck(6, "yellow", false);

I have learned C# by error code and there has got to be a better way to do this. I am stuck on Framework 2.0.


texts: Selecting indices of a cell array that strcmpi-match the contents of another cell array

texts:
I have a Matlab structure with several fields, 3 of which are interesting here:

elec.label %Nx1 cell-array of strings
elec.chanpos %Nx3 matrix of doubles
elec.elecpos %Nx3 matrix of doubles

The label contains unique names of channels, while the chanpos and elecpos contain coordinates, in such a way that elec.label(1) has the name of the channel one, and elec.chanpos(1,:) and elec.elecpos(1,:) have the coordinates of channel one.

What I need is to create a similar structure, which is a subset of elec and contains labels and the two coordinate fields, and is based on a list of labels that I have. The labels I have do not necessarily match capitalization used in the elec.label array.

Here's how I implemented this:

list46={'fpz';'afz';};%Real list is really long, so I truncated it.
INDX46=[];
for i=1:length(elec.label)
    for j=1:length(list46)
        if(strcmpi(list46(j),elec.label(i)))
            INDX46=[INDX46; i;];
        end
    end
end

elec46.chanpos=elec.chanpos(INDX46,:);
elec46.elecpos=elec.elecpos(INDX46,:);
elec46.label=elec.label(INDX46,:);

The implementation I did, to me, feels as if I'm trying to program C using Matlab. I'm looking for a more efficient or at least more Matlabesque way to do this.


texts: Converting an already-uploaded file and saving it to a model's FileField

texts:
Please review this:

from os import path, remove

try:
    video = Video.objects.get(id=original_video_id)
except ObjectDoesNotExist:
    return False

convert_command = ['ffmpeg', '-i', input_file, '-acodec',
       'libmp3lame', '-y', '-ac', '2', '-ar',
       '44100', '-aq', '5', '-qscale', '10',
       '%s.flv' % output_file]

convert_system_call = subprocess.Popen(
    convert_command,
    stderr=subprocess.STDOUT,
    stdout=subprocess.PIPE
)

logger.debug(convert_system_call.stdout.read())

try:

    f = open('%s.flv' % output_file, 'r')
    filecontent = ContentFile(f.read())
    video.converted_video.save('%s.flv' % output_file,
                     filecontent,
                     save=True)
    f.close()

    remove('%s.flv' % output_file)

    video.save()

    return True
except:
    return False


texts: Calculate sum, mean, sum of squares, and standard deviation of array elements

texts:
Also, I've commented out a function I was trying to do to count the elements of an array; I realized that is not possible due to the fact that I won't be be able to return a NULL on an array.

Although this part of a beginner to C exercise, I'd like to know if there is anything I can do to improve my coding.

#include <stdio.h>
#include <math.h>

#define MAX_ITEM 1000

double x[MAX_ITEM];
int arr_count(double x[]);
double sum(double x[], int arr_count);
double mean(double sum, int arr_count);
double sum_sqr(double x[], int arr_count);
double st_dev(double sum_sqr, double mean, int arr_count);

/*
int arr_count(double x[]) {
  int i = 0;
  int count = 0;

  for (i = 0; i < MAX_ITEM; i++) {
    if (x[i] != NULL){
      count++;
    }
  }
  return count;
}
*/

double sum(double x[], int arr_count){
  int i = 0;
  double my_sum = 0;

  for (i = 0; i < arr_count; i++){
    my_sum += x[i];
  }
  return my_sum;
}

double mean(double sum, int arr_count) {
  return sum / arr_count;
}

double sum_sqr(double x[], int arr_count){
  int i = 0;
  double my_sum = 0;

  for (i = 0; i < arr_count; i++){
    my_sum += x[i] * x[i];
  }
  return my_sum;
}

double st_dev(double sum_sqr, double mean, int arr_count) {
  return sqrt(sum_sqr/ arr_count - mean * mean);
}

int main(void){
  int i;
  int num;
  int my_arr_count = 0;
  double my_sum = 0;
  double my_mean = 0;
  double my_st_dev = 0;

  printf("Enter the number of elements you want in the array between 0 and 1,000\n");
  scanf("%d", &num);

  //generate elements
  for (i = 0; i < num; i++) {
    x[i] = rand(time(NULL));
  }

  // print the generated elements
  printf("The elements are:\n");
  for (i = 0; i < num; i++){
    printf("[%d] %lf\n", i+ 1, x[i]);
  }

  // my_arr_count = arr_count(x);
  my_arr_count = num;
  my_sum = sum(x, my_arr_count);
  my_mean = mean(my_sum, my_arr_count);
  my_st_dev = st_dev(sum_sqr(x,my_arr_count), my_mean, my_arr_count);

  printf("There are %d elements in the random array", my_arr_count);
  printf("the Sum is %lf", my_sum);
  printf("The Mean is %lf", my_mean);
  printf("The Standard Deviation is %lf", my_st_dev);

}


texts: Better way to count the number of occurrences of a maximum number in the array in Ruby

texts:
I am trying to write a program to get the count of the maximum number in an array of integers. The below code is what I have written. Is there any better way to write this code in Ruby?
def max_number_count(my_array)
    max_num, max_num_count = my_array.inject([0, 0]) {
                               |arr, age| age > arr[0] ?
                               [arr[0] = age, arr[1] = 1] : age == arr[0] ?
                               arr[1] += 1 : arr[1] = arr[1];
                               arr
                             }
    max_num_count
end

max_number_count([1,2,3,3,3])
#3
```


texts: Optimizing quicksort partition method/function for duplicate elements

texts:
I'm a newbie and interested in learning different data structures and algorithms. While implementing quicksort, I found this code works pretty well for partitioning.

int partition(int ar[], int lft, int rgt) {

int left = lft;
int right = rgt;
/*median of three is the best pivot value to accomplish in nlogn time*/
int pivotVal = ar[(left+right)/2];
printf("pivot: %d\n", pivotVal);

/*
-this while loop holds the left and right portion of the
-splitted array together to accomplish partitioning.
*/
while (left < right) {

    /*loop for left half array*/
    while (ar[left] < pivotVal) { left += 1; };

    /*loop for right half array*/
    while (ar[right] > pivotVal) { right -= 1; };

    /*
    -if the above conditions are not met the sub arrays are unsorted
    -we need to sort or exchange the values.
    */
    if (left < right) {
      int cache = ar[left];
      ar[left] = ar[right];
      ar[right] = cache;
    }

}

int pivotIndex = left; /*updated left or right is the pivot index*/
return pivotIndex;

}

Notice the code will get stuck in an infinite loop if there are any duplicate values in the given input array. So I hacked the problem just adding an additional line just after the swapping portion that looks like this:

int partition(int ar[], int lft, int rgt) {
int left = lft;
int right = rgt;
/*median of three is the best pivot value to accomplish in nlogn time*/
int pivotVal = ar[(left+right)/2];
printf("pivot: %d\n", pivotVal);

/*
-this while loop holds the left and right portion of the
-splitted array together to accomplish partitioning.
*/
while (left < right) {

    /*loop for left half array*/
    while (ar[left] < pivotVal) { left += 1; };

    /*loop for right half array*/
    while (ar[right] > pivotVal) { right -= 1; };

    /*
    -if the above conditions are not met the sub arrays are unsorted
    -we need to sort or exchange the values.
    */
    if (left < right) {
      int cache = ar[left];
      ar[left] = ar[right];
      ar[right] = cache;
    }

    /*if there are any duplicate value
    the above conditions would not met
    and the algo will go into an infinite loop.
    this if condition checks if there are any
    duplicate value if exixts... increase
    left or decrease right one to break the loop
    */
    if (ar[left] == ar[right]) {
      right--; /*if we increase left then pivot index will be the right one*/
    }

}

int pivotIndex = left; /*updated left or right is the pivot index*/
return pivotIndex;

}

How do you veterans handle the duplicate values ?


texts:
I've been working on a function which allows me to validate a table recieved through my REST API:

public function isTableComplete($table, $requiredKeys){
    if(!isset($table)){
        return false;
    }

    foreach ($requiredKeys as $field) {
        if(!isset($table[$field["name"]]) AND $field["required"]){
            return false;
        }
        if(!isset($table[$field["name"]]) AND !$field["required"]){
            continue;
        }
        switch ($field["type"]) {
            case "integer":
                if(!is_numeric($table[$field["name"]])){
                    return false;
                }
                if($table[$field["name"]] > $field["max"] or $table[$field["name"]] < $field["min"]){
                    return false;
                }
            break;
            case "string":
                if(!is_string($table[$field["name"]])){
                    return false;
                }
                if(strlen($table[$field["name"]]) > $field["max"] or strlen($table[$field["name"]]) < $field["min"]){
                    return false;
                }
            break;
            case "date":
                if(!$this->validateDate($table[$field["name"]], $field["layout"])){
                    return false;
                }
            break;
        }

    }
    return true;
}

And to use it you simply do:

$requiredKeys = [
    ["name"=>"username", "type"=>"string", "max"=>50, "min"=>3, "disp_name"=>"Username", "required"=>true],
    ["name"=>"password", "type"=>"string", "max"=>120, "min"=>6, "disp_name"=>"Password", "required"=>true],
];

if(!CommonTasks::isTableComplete($data, $requiredKeys)){
    Reply::error(["detail"=>"Please assure that you have a username of atleast 3 characters and a password of atleast 6."], "alert");
    return;
}

Im struggling with how I should handle errors though... Should I move this into its own class and make a function for fetching errors? Or should I throw exceptions and catch them later on?

Im also thinking I should rename the $requiredKeys variable as this function now accepts both required and optional keys...

Why would there be a user defined table for? There wont be... This is for validating form data parsed into a table. So if a user leaves out a field or if someone is developing a frontend for the app, there will be errors suitable for each scenario.


texts: RPN-Stack-Based Recursive Calculator Needs Tuneup

texts:
This function takes an array of strings and numbers and recursively processes it as a kind of "calculating program".  The structure is based on Reverse Polish Notation, so the top object in the stack (last in the array) determines what to do with the next one (or two) items in the program.  For example, if the array was [1, 2, "+"], the solution would be 3.

In the case of errors, it should return an NSString describing the
error that happened.
If more than one error occurs in processing, it is not clear which
error should receive priority, so I've chosen to prioritize the first
error found and ignore any further errors.

I think that this code could be made much more simple, but I'm not sure how best to do that in Objective C.  What suggestions do you have to improve this code?

 + (id)popOperandOffProgramStack:(NSMutableArray *)stack
    {
        id result;
        double dResult;

        id topOfStack = [stack lastObject];
        if (topOfStack) [stack removeLastObject];

        if ([topOfStack isKindOfClass:[NSNumber class]])
        {
            result = topOfStack;
        }
        else if ([topOfStack isKindOfClass:[NSString class]])
        {
            id rightSide = [self popOperandOffProgramStack:stack];
            if (![rightSide isKindOfClass:[NSNumber class]]) {
                return rightSide;
            }
            double r = [(NSNumber *)rightSide doubleValue];

            NSString *operation = topOfStack;
            if ([[self class] isBinaryOperation:operation]) {
                id leftSide = [self popOperandOffProgramStack:stack];
                if (![leftSide isKindOfClass:[NSNumber class]]) {
                    return leftSide;
                }
                double l = [(NSNumber *)leftSide doubleValue];
                if([operation isEqualToString:@"+"]) {
                    dResult =  l + r;
                } else if([operation isEqualToString:@"-"]) {
                    dResult = l - r;
                } else if([operation isEqualToString:@"*"]) {
                    dResult = l * r;
                } else if([operation isEqualToString:@"/"]) {
                    if(r == 0.0) {
                        return @"Error: Tried to divide by zero";
                    } else {
                        dResult = l / r;
                    }
            }
            } else if ([operation isEqualToString:@"+/-"]) {
                dResult = -r;
            } else if([operation isEqualToString:@"sin"]) {
                dResult = sin(r);
            } else if([operation isEqualToString:@"cos"]) {
                dResult = cos(r);
            } else if([operation isEqualToString:@"sqrt"]) {
                if(r < 0) {
                    return @"Error: tried to sqrt a negative number";
                }
                dResult = sqrt(r);
            } else if([operation isEqualToString:@"π"]) {
                dResult = 3.141592654;
            } else {
                /* unknown operations and unset variables will return 0 */
                dResult = 0.0;
            }
            result = [NSNumber numberWithDouble:dResult];
        }
        return result;
    }


texts: Standard deviation of hourly temperatures of 2 days

texts:
It seems that when I program in Lisp my brain goes on auto pilot and I end up solving the problem somehow. I don't even think I just do and it works out.

That said, this is some horrible Lisp code that was hacked together in about 20 mins, just to see if I could do it.

The C++ program that this is based off was about 150 lines long, so doing it in about 59 lines of terrible code is neat.

The date is 50 lines and is structured like 2 dates and 48 doubles 1 for each hour:

3/14/2015
3/15/2015
32.12
12.23
34.12
.
.
56.12

(defun read-nth-line (file n &aux (line-number 0))
  "Read the nth line from a text file. The first line has the number 1"
  (assert (> n 0) (n))
  (with-open-file (stream file)
    (loop for line = (read-line stream nil nil)
          if (and (null line) (< line-number n))
            do (error "file ~a is too short, just ~a, not ~a lines long"
                      file line-number n)
          do (incf line-number)
          if (and line (= line-number n))
       do (return line))))

(defun arithmetic-average (samples)
  (/ (reduce #'+ samples)
     (length samples)))

(defun get-file (filename)
  (with-open-file (stream filename)
    (loop for line = (read-line stream nil)
          while line
       collect line)))

   ;; compute sDev
(defun standard-dev (colc)
  (let ((mean (arithmetic-average colc)))
    (sqrt (* (/ 1.0d0 (length colc))
         (reduce #'+ colc
             :key (lambda (x)
                (expt (- x mean) 2)))))))

(defun split-in-half (sequence)
  (let ((mid (ceiling (length sequence) 2)))
    (list (subseq sequence 0 mid)
            (subseq sequence mid nil))))

(defun parse-string-to-float (line)
  (with-input-from-string (s line)
    (loop
      :for num := (read s nil nil)
      :while num
      :collect num)))

(defun extract-float (line)
  "doc"
 (first (parse-string-to-float line)))

(defun process-file ()
  "print mean and standard deviation to terminal"
  (let* ((l1 (get-file "~/ClionProjects/project5withTemplates/twoday.txt"))
     (date1 (first l1))
     (date2 (second l1))
     (day1temps (mapcar #'extract-float (first (split-in-half (rest (rest l1))))))
     (day2temps (mapcar #'extract-float (second (split-in-half (rest (rest l1))))))
     (s-dev-day-1 (standard-dev day1temps))
     (s-dev-day-2 (standard-dev day2temps)))
    (print "date:")(print date1) (print "standard deviation:") (print s-dev-day-1)
    (print "date:")(print date2) (print "standard deviation:") (print s-dev-day-2)) nil)


texts:
Given a file containing adjacent IDs:

i1, i2, i5
i3, i4
i2, i6, i7
i4, i8
i9, i3

I would like to print each of the connected components:

i1, i2, i5, i6, i7
i3, i4, i8, i9

I decided to accomplish this using a BFS on a Map datastructure:

/* Input, can be read from file easily by splitting on ", " */
val lines = List(List("i1", "i2", "i5"),
    List("i3", "i4"),
    List("i2", "i6", "i7"),
    List("i4", "i8"),
    List("i9", "i3"))
/* finds all sequential pairs */
val pairs =  lines.flatMap(x => x.dropRight(1).zip(x.drop(1)))

/* each pair should be symmetric (we are in an undirected graph) */
val pSym = pairs.flatMap(x => List(x, x.swap))

/* create an empty adjacency map: id -> (List of adjacent edges) */
val vertices = lines.flatten.distinct
val defMap = vertices.map(_ -> List[String]()).toMap

/* populate the default map with the actual adjacencies */
val adjMap = pSym.foldLeft{defMap}(
    (acc, x) => acc + (x._1 -> (acc(x._1) :+ x._2))
)

/* BFS algo on map representation of graph */
def mapBFS(adjMap: Map[String, List[String]]): List[List[String]] =
{
    val v = adjMap.keys
    var globalVisits = List[String]()
    def BFS_r(elems: List[String], visited: List[List[String]]): Option[List[List[String]]] =
    {
        val newNeighbors = elems.flatMap(adjMap(_)).filterNot(visited.flatten.contains).distinct
        if (newNeighbors.isEmpty)
            Some(visited)
        else
            BFS_r(newNeighbors, newNeighbors :: visited)
    }
    v.flatMap(x =>{
        if (globalVisits.contains(x))
            None
        else
        {
            val vi: List[String] = BFS_r(List(x), List(List(x))).get.flatten
            globalVisits = globalVisits ++ vi
            Some(vi)
        }
    }).toList
}

mapBFS(adjMap).foreach{println}

This gives me the desired result:

List(i7, i1, i6, i2, i5)
List(i8, i4, i3, i9)

However I feel that this code is not very functional (esp. with the side-effects of updating globalVisits in mapBFS) and I feel like some the data manipulation at the beginning is pretty inefficient. Any thoughts on improvements?


texts:
I'm working to get some practice with SQL functions which are often used in a financial setting, and I created this simple table with products, prices and tax rates basically.

I then wrote a query to simulate a purchase invoice type of result set (I realize things like that are most often done at application level, or as a separate DB transaction).

After I wrote this query, I found myself using so many parentheses for operations, and repeating the same formulas over and over, and I thought; there's got to be a better way to do this! So here I am seeking peer review.

You can try it using SEDE.

Here is the table:

CREATE TABLE #Sales (
    Id INT NOT NULL IDENTITY PRIMARY KEY
  , Product NVARCHAR(MAX)
  , Price DECIMAL(6,2)
  , Qty INT
  , Import BIT
  , SalesTaxRate DECIMAL(6,2)
  , ImportTaxRate DECIMAL(6,2)
);
GO

INSERT INTO #Sales (Product, Price, Qty, Import, SalesTaxRate, ImportTaxRate)
VALUES
  ('Apple Pie',          3.99,  10, 0, 7.50, NULL)
, ('Swiss Chocolate',    6.99,  5,  1, NULL, 5.50)
, ('French Wine',        12.99, 3,  1, 7.50, 5.50)
, ('Complimentary Gift', NULL,  1,  0, NULL, NULL)
;
GO

And here is the query which results in this table being returned:

SELECT
  Id
, Product
, [Price] = COALESCE(Price, 0)
, Qty
, [Subtotal] = (ISNULL(Price,0) * Qty)
, [Sales Tax] = CAST((ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2))
, [Import Tax] = CAST((ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2))
, [Total Tax] = COALESCE(
    CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
    , 0)
, [Line Total] = (
    ISNULL(Price,0) * Qty -- Subtotal
    + COALESCE(
    CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
    , 0)) -- Total Tax
FROM #Sales

UNION

SELECT
  NULL
, 'Totals'
, NULL
, NULL
, SUM((ISNULL(Price,0) * Qty)) -- Subtotal
, SUM(CAST((ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2)))
, SUM(CAST((ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2)))
, SUM(COALESCE(
    CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
    , 0))
, SUM(
    ISNULL(Price,0) * Qty -- Subtotal
    + COALESCE(
      CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
      , 0)) -- Total Tax
FROM #Sales


texts: Summation and multiplication of digits of a number

texts:
This program takes digits of a number and calculate summation and multiplication of its digits .How can I make this code more OOP ?

//Calculate Sum and multiplication of digits of a number .

#include "stdafx.h"
#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main()
{
    int number , sum = 0 , multp = 0 ;
    vector<int> digits;

    cout << "Calculate Sum and multiplication of digits of a number ." << "\n" << "\n";
    cout << "------------------------------------" << "\n";
    cout << "Enter a whole number : ";

    cin >> number;

    if (number > 0)         //Condition for inputed number
    {

        while (number)
        {
            digits.push_back(number % 10);
            number /= 10;
        }

        for (int i = 0; i < digits.size(); i++) // summation
        {
            sum += digits[i];
        }
        cout << "sum of digits = " << sum << "\n";

        for (int j = 0; j < digits.size(); j++) //multiplication
        {
            multp *= digits[j];
        }

        cout << "Multiplication of digits = " << multp << "\n";
    }

    else
    {
        cout << "Pleas enter a positive number ." << "\n";
    }

    cout << "\n" << "\n" << "------------------------------------" << "\n";
    system("pause");
    return 0;
}

Thanks in advance.


texts:
As a beginner Python programmer, I wrote a simple program that counts how many times each letter appears in a text file. It works fine, but I'd like to know if it's possible to improve it.

def count_letters(filename, case_sensitive=False):
    alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    with open(filename, 'r') as f:
        text = f.read()

    if not case_sensitive:
        alphabet = alphabet[:26]
        text = text.lower()

    letter_count = {ltr: 0 for ltr in alphabet}

    for char in text:
        if char in alphabet:
            letter_count[char] += 1

    for key in sorted(letter_count):
        print(key, letter_count[key])

    print("total:", sum(letter_count.values()))


texts: Choosing names for "logic" and "implementation" traits in Stackable trait pattern

texts:
I have a trait that is to be mixed-in with existing types of Actor classes in Akka and offer a certain functionality.

To offer better maintenance, I am using the stackable trait pattern. The integration with different kinds of actor(say PersistentActor or PersistentFSM) happens at a Impl level. Now all these Impl trait have a base impl trait. This base trait in turn, depends on some fields which are defined in a Logic trait:

trait QueryViewLogic {

def viewId: String

def queryId: String

  ...

}

//This needs to be mixed in to create and enable the pipelines to be assembled.
trait QueryViewLogicImpl extends Snapshotter
with ActorLogging with QueryViewLogic with ReadJournalQuerySupport {

def bookKeeping(): Unit = {...}

def performSnapshot: Receive = {...}
...

}

The actual implementation for say a persistentActor will be defined as below:

//The view Persistent-Actors can mix this trait in to specify the building blocks of QueryView.
abstract class QueryViewBase[D](implicit val snapshotData: ClassTag[D])
extends PersistentActor with QueryViewLogic {

type SnapshotData = D

def persistenceId: String = viewId

def receiveRecover: Receive = Map.empty

def receiveCommand: Receive = receiveReads orElse receiveJournalEvents

def receiveJournalEvents: Receive

def receiveReads: Receive
}

and then:

//The view Persistent-Actors extending QueryViewBase need to mix this in to get the QueryView machinery working.
trait QueryViewImpl extends PersistentActor with QueryViewLogicImpl {

override def receiveRecover: Receive = receiveQueryViewSnapshot

abstract override def receiveCommand: Receive = {
  performSnapshot orElse
    (queryViewCommandPipeline andThen (super.receiveCommand orElse unhandledCommand))
    }

}

So the client, would mix in the Logic trait to provide the fields of interest, and then the impl class mixes in the class providing the information above and mixes in the trait that actually puts together the pipelines introduced above according to the stackable trait pattern. see an example here.

Firstly, I would like to have feedback on the names of the four traits mentioned above.
secondly, taking the demo as an example, the point of having an AccountView and a separate AccountViewImpl was to separate the functionality of responding to events and that of the mechanism for fetching the events, for better maintenance, so that the users of this functionality, only concerns themselves with the former. Is this benefit shadowed by the added complexity in the code?
I'd be interested in suggestions for better names for the client users of these traits, namely AccountView and AccountViewImpl.


texts: An attempt to extend an enum to prevent branching without violating the Open-Closed principle

texts:
I love making utility State enums, and giving them methods that do useful things based on which instance of the enum is provided. This works when the enum is very specific to the class I'm working on, but can often make no sense when I need to switch on the enum type but I don't want the enum itself to know anything about that functionality. Further, I don't want to violate the open-closed principle in my main enum. I would prefer to avoid doing switch...case on the enum if possible.

Here's my solution that attempts to get the best of both worlds. It works (which is why I'm on CodeReview and not Programmers or SO), but it's clunky. Notice that I never have to change MyEnum again, all I do is create a new helper class each time I have a new behavior that I "wish" MyEnum had. Is there a better way?

public class EnumExample {
  public static interface OneEnumVisitor<R, A> {
    R visitFoo(A args);
    R visitBar(A args);
  }

  public static interface TwoEnumVisitor<R, A, B> {
    R visitFoo(A argOne, B argTwo);
    R visitBar(A argOne, B argTwo);
  }

  public static enum MyEnum {
    FOO {
      public <R, A> R visit(OneEnumVisitor<R, A> visitor, A args) {
        return visitor.visitFoo(args);
      }
      public <R, A, B> R visit(TwoEnumVisitor<R, A, B> visitor, A argOne, B argTwo) {
        return visitor.visitFoo(argOne, argTwo);
      }
    },
    BAR {
      public <R, A> R visit(OneEnumVisitor<R, A> visitor, A args) {
        return visitor.visitBar(args);
      }
      public <R, A, B> R visit(TwoEnumVisitor<R, A, B> visitor, A argOne, B argTwo) {
        return visitor.visitBar(argOne, argTwo);
      }
    };

    public abstract <R, A> R visit(OneEnumVisitor<R, A> visitor, A args);
    public abstract <R, A, B> R visit(TwoEnumVisitor<R, A, B> visitor, A argOne, B argTwo);
  }

  public static enum NewMethod implements TwoEnumVisitor<Integer, Integer, Integer> {
    INSTANCE;

    @Override
    public Integer visitFoo(Integer argOne, Integer argTwo) {
      return argOne.intValue() - argTwo.intValue();
    }

    @Override
    public Integer visitBar(Integer argOne, Integer argTwo) {
      return argTwo.intValue() + argOne.intValue();
    }
  }

  public static class SomeObject {
    private final MyEnum type;
    private final int param;

    public SomeObject(MyEnum type, int param) {
      this.type = type;
      this.param = param;
    }

    public int doMath(int value) {
      return type.visit(NewMethod.INSTANCE, value, param);
    }
  }

  public static void main(String... args) {
    SomeObject myObject = new SomeObject(MyEnum.FOO, 5);
    SomeObject myOtherObject = new SomeObject(MyEnum.BAR, 5);

    System.out.println(myObject.doMath(10));
    System.out.println(myOtherObject.doMath(10));
  }
}


texts: Theory-based quiz grader using similarity

texts:
I wrote a fairly simple program that grades theory-based quizzes. It is fairly straightforward. I would love to get insights and ideas on how it might be improved.
consine_similarity.py
"""This module uses consine distance to check the similarity between two sentences"""

from nltk.corpus import stopwords
from nltk.cluster.util import cosine_distance
from nltk.tokenize import word_tokenize

def consine_similarity(sent1: str, sent2: str) -> float:
    """Consine similarity between two sentences

        sent1: str
        sent2: str
    """

    sent1_list = word_tokenize(sent1)
    sent2_list = word_tokenize(sent2)
    stop_words = stopwords.words('english')
    all_words = list(set(sent1_list + sent2_list))

    vector1 = [0] * len(all_words)
    vector2 = [0] * len(all_words)

    for word in sent1_list:
        if word in stop_words:
            continue
        vector1[all_words.index(word)] += 1

    for word in sent2_list:
        if word in stop_words:
            continue
        vector2[all_words.index(word)] += 1

    return 1 - cosine_distance(vector1, vector2)

quiz.py
"""Theory-based quiz application"""

from dataclasses import dataclass
from random import shuffle
from consine_similarity import consine_similarity

@dataclass
class Quiz:
    """Quiz data"""

    quiz: str
    answer: str

    def __str__(self):
        return '{}'.format(self.quiz)

def start_quiz(quiz_list: list) -> None:
    """Start the quiz application"""

    shuffle(quiz_list)
    consine_list = []

    for quiz in quiz_list:
        print(quiz)
        answer = input('> ')
        consine_list.append(consine_similarity(quiz.answer, answer))
        print()

    grade = sum(consine_list) / len(consine_list) * 100

    print('Your grade is {:.2f}%'.format(grade))

if __name__ == "__main__":
    QUIZ_LIST = [
        Quiz(quiz='What is a computer?',
             answer='An electronic device for storing and processing data, \
                 typically in binary form, according to instructions given to it'),
        Quiz(quiz='What are logic gates?',
             answer='These are the basic building blocks of any digital system. It is an \
                  electronic circuit having one or more than one input and only one output'),
        Quiz(quiz='What is BIOS',
             answer='This is firmware used to perform hardware initialization during the booting \
                 process and to provide runtime services for operating systems and programs'),
    ]
    start_quiz(QUIZ_LIST)


texts: Checking whether a graph is bipartite using BFS

texts:
I am solving a simple problem that checks whether a graph is two-colourable (bipartite graph). I am using BFS for this approach using C++ STL. I've replaced cin and cout with scanf and printf as suggested by fellow programmers but still the judge reports TLE.

#include<iostream>
#include<list>
#include<cstring>
#include<cstdio>
using namespace std;
int flag = 1;

class Graph
{
    int V;
    list<int> *adj;

    public:
        Graph(int V);
        void addEdge(int v, int w);
        void BFS(int s);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[1000001];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w);
    adj[w].push_back(v);
}

void Graph::BFS(int s)
{
    bool *visited = new bool[V];
    string *color = new string[1000001];
    for(int i=0;i<V;i++)
        visited[i] = false;
    list<int> queue;
    queue.push_back(s);
    visited[s] = true;
    color[s] = "red";
    list<int>::iterator i;
    flag = 1;
    while(!queue.empty())
    {
        s = queue.front();
        queue.pop_front();

        for(i = adj[s].begin(); i != adj[s].end(); i++)
        {
            if(!visited[*i])
            {
                visited[*i] = true;
                if(color[s] == "red")
                    color[*i] = "blue";
                if(color[s] == "blue")
                    color[*i] = "red";
                queue.push_back(*i);
            }
            else
            {
                if(color[s] == color[*i])
                    flag = 0;
            }
        }
    }
}

int main()
{
    int T, bugs, edges, from, to;
    scanf("%d", &T);
    int p = T;
    while(T--)
    {
        scanf("%d%d", &bugs, &edges);
        Graph g(bugs+1);
        for(int i=0; i<edges; i++)
        {
            scanf("%d%d", &from, &to);
            g.addEdge(from, to);
        }

        g.BFS(from);

        if(!flag)
            printf("Scenario #%d:\nSuspicious bugs found!\n", p-T);
        else
            printf("Scenario #%d:\nNo suspicious bugs found!\n", p-T);

    }

    return 0;
}


texts:
https://leetcode.com/problems/sum-of-two-integers/

  Calculate the sum of two integers a and b, but you are not allowed to
  use the operator + and -.

  Example 1:

  Input: a = 1, b = 2 Output: 3 Example 2:

  Input: a = -2, b = 3 Output: 1

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MathQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/sum-of-two-integers/
    /// </summary>
    [TestClass]
    public class SumOfTwoIntegersTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            int a = 1;
            int b = 2;
            int expected = 3;
            Assert.AreEqual(expected, GetSum(a,b));
        }

        [TestMethod]
        public void ExampleTest2()
        {
            int a = 5;
            int b = 7;
            int expected = 12;
            Assert.AreEqual(expected, GetSum(a, b));
        }

        public int GetSum(int a, int b)
        {
            if (a == 0) return b;
            if (b == 0) return a;

            while (b != 0)
            {
                int carry = a & b;
                a = a ^ b;
                b = carry << 1;
            }

            return a;

        }
    }
}

Please review for performance


texts:
I've just started with Java. The code below calculates Body Mass Index (BMI).
Could someone look for my code and assess it? Maybe I should write something more? All advice will be very helpful.
import java.util.Scanner;

public class BMI {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double weight = 0;
        double height = 0;
        double bmi = 0;

        System.out.println("Please enter your details to calculate your Body Mass Index.");

        System.out.println("Enter your weight in kilograms:");
        weight = scanner.nextDouble();
        System.out.println("Enter your height in metres:");
        height = scanner.nextDouble();
        bmi = (weight / (height * height));
        System.out.println("Your BMI is: " + bmi);

        if (bmi >= 40) {
            System.out.println("Serious obesity");
        } else if (bmi >= 30) {
            System.out.println("Obesity");
        } else if (bmi >= 25) {
            System.out.println("Overweight");
        } else if (bmi >= 18) {
            System.out.println("Standard");
        } else {
            System.out.println("Underweight");
        }

        scanner.close();

    }

}


texts: Simple python scheduled tasks script that runs once daily

texts:
I want to execute a python script daily and thereby want to schedules task as follows.

The idea is that the script will run once daily, and the script will then decide what tasks to be done today.

The reason is that I can't use cron or windows scheduled task on my environment.

The question is that, is there any better idea?

from datetime import datetime
import os

from sheduled_tasks import daily_task1, daily_task2, weekly_task, monthly_tasks

tasks = {} # or open from saved pickel file

schedule = {
    1: [daily_task1, daily_task2],
    7: [weekly_task],
    30: [monthly_tasks],
}

for delta, stasks in schedule.items():
    for task in stasks:
        name = task.__name__
        if ((task not in tasks) or
            (datetime.now() - tasks[name]).days >= delta):
            task()
            tasks[task.name] = datetime.now().replace(hour=6)

# pickle tasks


texts:
I recently added this ConfigLoader class to my project : it loads information (in this example for a window) from an XML config file, using boost. I would like to ask your advice if this is a good implementation of a ConfigLoader using type_traits, or if I could improve it; here is my code:

ConfigLoader.h:

#pragma once

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/log/trivial.hpp>
#include <exception>
#include <type_traits>

namespace Spiky {
namespace Tags {

#define SPIKY_CONFIG_DEF_TYPES(ID, TYPE) \
struct TYPE : std::integral_constant<int, ID> { \
};

SPIKY_CONFIG_DEF_TYPES(1, DisplayConfig)
SPIKY_CONFIG_DEF_TYPES(2, GLSpecConfig)
#undef SPIKY_CONFIG_DEF_TYPES
} //namespace Tags

template <typename T>
class ConfigLoader {};
} //namespace Spiky

GraphicsDisplayConfig.h:

#pragma once

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/log/trivial.hpp>
#include <exception>

#include "ConfigLoader.h"

namespace Spiky {

struct GraphicsDisplayConfig;
template<>
class ConfigLoader<Tags::DisplayConfig> {
public:
  static GraphicsDisplayConfig LoadConfig(const char* path) {
    GraphicsDisplayConfig config;
    try {
      boost::property_tree::ptree pt;
      boost::property_tree::read_xml(path, pt);

      title = pt.get<std::string>("display.title");
      config.x = pt.get<unsigned>("display.position.<xmlattr>.x");
      config.y = pt.get<unsigned>("display.position.<xmlattr>.y");
      config.w = pt.get<unsigned>("display.resolution.<xmlattr>.w");
      config.h = pt.get<unsigned>("display.resolution.<xmlattr>.h");
    }
    catch (std::exception& e) {
      BOOST_LOG_TRIVIAL(error) << e.what();
    }
    return config;
  }
};

struct GraphicsDisplayConfig {
  unsigned x = 0;
  unsigned y = 0;
  unsigned w = 0;
  unsigned h = 0;
  std::string title = "";
  bool resizable = false;
  bool fullScreen = false;

  int LoadConfig(const char* path) {
    try {
      boost::property_tree::ptree pt;
      boost::property_tree::read_xml(path, pt);

      title = pt.get<std::string>("display.title");
      x = pt.get<unsigned>("display.position.<xmlattr>.x");
      y = pt.get<unsigned>("display.position.<xmlattr>.y");
      w = pt.get<unsigned>("display.resolution.<xmlattr>.w");
      h = pt.get<unsigned>("display.resolution.<xmlattr>.h");
    }
    catch (std::exception& e) {
      BOOST_LOG_TRIVIAL(error) << e.what();
      return -1;
    }
    return 0;
  }
};
}