texts: overloaded const and non-const class methods returning references in C++

texts:
I have a data-structure class in C++ with an accessor to some object (may be large) and I have const and non-const methods using this accessor so I need to overload it. I am looking for a critique of the code below - maybe there is a way to accomplish the same thing that is cleaner?

The way I understand it, there are two ways to achieve this without duplicating the code in the accessor in the following case, the method get(). I am not sure if there are serious issues with either of these two methods and I would like some guidance here.

I like method A because:

only one const_cast
const-version of the method get() returns a copy
the non-const method gets the non-const reference directly

I don't like method A because:

the non-const method get() is const only by contract, (not checked by compiler)
harder to get a const-reference, though not impossible

I like method B because:

the const-ness of the const method get() is checked by compiler
copy of the returned object is controlled by the user

I don't like method B because:

requires two const_casts which is hard to read

here is the (minimal) example code of the two cases.

/**
 * summary:
 * Two classes with an overloaded method which is
 * guaranteed (by contract) not to change any
 * internal part of the class. However, there is a
 * version of this method that will return a non-const
 * reference to an internal object, allowing the user
 * to modify it. Don't worry about why I would ever
 * want to do this, though if you want a real-world
 * example, think about std::vector<>::front()
 *
 * The difference between A and B can be summarized
 * as follows. In both cases, the second method merely
 * calls the first, wrapped with the needed
 * const_cast's
 *
 * struct A {
 *     int& get();
 *     int  get() const;
 * };
 *
 * struct B {
 *     const int& get() const;
 *           int& get();
 * };
 *
 **/

struct A
{
    int _val;

    A() : _val(7) {};

    // non-const reference returned here
    // by a non-const method
    int& get()
    {
        // maybe lots of calculations that you do not
        // wish to be duplicated in the const version
        // of this method...
        return _val;
    }

    // const version of get() this time returning
    // a copy of the object returned
    int get() const
    {
        // CONST-CAST!!?? SURE.
        return const_cast<A*>(this)->get();
    }

    // example of const method calling the
    // overloaded get() method
    int deep_get() const
    {
        // gets a copy and makes
        // a copy when returned
        // probably optimized away by compiler
        return this->get();
    }
};

struct B
{
    int _val;

    B() : _val(7) {};

    // const reference returned here
    // by a const method
    const int& get() const
    {
        // maybe lots of calculations that you do not
        // wish to be duplicated in the non-const
        // version of this method...
        return _val;
    }

    // non-const version of get() this time returning
    // a copy of the object returned
    int& get()
    {
        // CONST-CAST!? TWO OF THEM!!?? WHY NOT...
        return const_cast<int&>(const_cast<const B*>(this)->get());
    }

    // example of const method calling the
    // overloaded get() method
    int deep_get() const
    {
        // gets reference and makes
        // a copy when returned
        return this->get();
    }
};

int main()
{
    A a;
    a.get() = 8;  // call non-const method
    a.deep_get(); // indirectly call const method

    B b;
    b.get() = 8;  // call non-const method
    b.deep_get(); // indirectly call const method
}


texts: smallest number divisible by all numbers from 1 to 20? Project Euler question 5

texts:
I'm currently working my way through the questions on Project Euler and I am on question 5. Is this the best possible solution? Any suggestions welcomed!

        List<int> divisors = new List<int>{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

        int n = 1;

        while (true)
        {
            n++;
            foreach (int d in divisors)
            {
                if (n % d != 0) { break; }
                if (d==20)
                {
                    Console.Write(n);
                    Console.ReadLine();
                }
            }
        }


texts: Binary multiplication on elliptic curves in C++

texts:
I wrote a function in C++ which uses binary multiplication (a form of binary exponentation):

public: Point mul(Point p, unsigned int n)
{
    // actually these Points shouldn't have negative coordinates, I use Point(-1, -1) as neutral element on addition (like 0)
    Point r = Point(-1, -1);
    n = mod(n, m);  // the %-operator doesn't return a non-negative integer in every case so I wrote a function
    unsigned int mask = 1 << (sizeof (n) - 1);  // more flexible and platform independent than 1 << 31
    for (; mask; mask >>= 1)
    {
        r = add(r, r);
        if (mask & n)
            r = add(r, p);
    }
    return r;
}

Notes:

The function calculates points on elliptic curves over a finite field GF(m)
Point is a class I wrote for this. It doesn't do much beside holding two coordinates x and y
I just wondered if there is an easier / cleaner solution for binary multiplcation in C++ than I implemented
The algorithm is like 'double and add' instead of 'square and multiply'

EDITS:

This is my Point class:

class Point
{
    public:
        long long int x, y;

    public: Point(long long int _x, long long int _y)
    {
        x = _x;
        y = _y;
    }

    public: void print()
    {
        cout << "(";
        cout << x;
        cout << ", ";
        cout << y;
        cout ")";
    }
};

The mul function is part of the class EllipticCurve:

class EllipticCurve
{
    public:
        int a;
        int b;
        unsigned int m;

    public: EllipticCurve(int _a, int_b, unsigned int modul)
    {
        a = _a;
        b = _b;
        m = modul;
    }

    public: Point generate(unsigned long long int x)
    {
        // looks for Points on the curve with the given x coordinate
        // returns the first matching point
    }

    public: Point add(Point p, Point q)
    {
        // complex addition function with if-else trees
        // the function code is not needed for this question
    }

    public: Point mul(Point p, unsigned int n)
    {
        // see above
    }
};

Please remember that this question is about the mul function, not the rest of the code. I inserted it only for a better understanding.


texts: Find the minimum path sum in a binary tree

texts:
I am working on the problem of finding the minimum path sum in a binary tree, and printing the path. The path can be from the root node to any leaf node.

Here is my code in Python 2.7. I am looking for advice for bugs, performance improvement ideas or general code style advice.

One specific question is: I am using a list result to track minimal sum so far, because a simple integer in Python 2.7 is not reference type (I mean change the value of an integer in one function call, does not impact the value of same variable in another function). Are there any more elegant ways to track the minimal sum so far?

class TreeNode:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
    def min_path(self, sum_so_far, prefix, result, result_path):
        if self.left:
            prefix.append(self.value)
            self.left.min_path(sum_so_far + self.value, prefix, result, result_path)
            prefix.pop(-1)
        if self.right:
            prefix.append(self.value)
            self.right.min_path(sum_so_far + self.value, prefix, result, result_path)
            prefix.pop(-1)
        if not self.left and not self.right: # leaf node
            prefix.append(self.value)
            if sum_so_far + self.value < result[0]:
                result[0] = sum_so_far + self.value
                if len(result_path) > 0:
                    result_path.pop(0)
                result_path.append(prefix[:])
            prefix.pop(-1)
if __name__ == "__main__":
    root = TreeNode(1, TreeNode(2, TreeNode(-4, None, None), TreeNode(5, None, None)), TreeNode(3, TreeNode(6, None, None), TreeNode(-7, None, None)))
    result = [float('inf')]
    result_path = []
    root.min_path(0, [], result, result_path)
    print result, result_path


texts:
I'd like to know if I can improve the performance of my recent bot, and maybe some design patterns too.

So far, it's warning a user if it's using some bad words (which are parsed from bad_words.txt) and it's entertaining the users by posting jokes from jokes.txt.

from selenium import webdriver
import time
import random

def login_to_rst(base_url, username, password):
    xpaths = {
        'usernameTxtField': "//input[@name='auth']",
        'passwordTxtField': "//input[@name='password']",
        'submitButton': "//*[@id='ipsLayout_mainArea']/div/div[2]/div/form/li[5]/div/button"
    }
    FIREFOX_DRIVER.get(base_url)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['usernameTxtField']).clear()
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['usernameTxtField']).send_keys(username)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['passwordTxtField']).clear()
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['passwordTxtField']).send_keys(password)
    FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitButton']).click()
    FIREFOX_DRIVER.get(base_url)

def write_to_chat(chat_url):
    FIREFOX_DRIVER.get(chat_url)

    bad_words = [line.rstrip('\n') for line in open('bad_words.txt')]

    time.sleep(5)
    message = "Please use a decent language !"
    xpaths = {
        'textArea': "//*[@id='ipsTabs_elChatTabs_chatroom_panel']/div[1]/div[1]/textarea",
        'submitMessage': "//*[@id='ipsTabs_elChatTabs_chatroom_panel']/div[1]/div[1]/div[3]/button"
    }

    parsed_messages, rst_messages_list = [], []
    keep_running = True
    while keep_running:
        divs = FIREFOX_DRIVER.find_elements_by_xpath('//ul[@class="ipsList_reset cChatContainer"]/li/div')
        for div in divs:
            rst_messages_list = []
            if div.id not in parsed_messages:
                rst_messages_list.append(div.text)
                print(rst_messages_list)
                parsed_messages.append(div.id)

                for unique_message in rst_messages_list:
                    for word in bad_words:
                        if word in unique_message:
                            FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                            FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(message)
                            FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

                    if '/message1' in unique_message or '/Message1' in unique_message:
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys("text to be sent")
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()
                    if '/message2' in unique_message or '/Message2' in unique_message:
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys("2016 © me")
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()
                    if '/message3' in unique_message:
                        line = random.choice(open('jokes.txt').readlines())
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).clear()
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['textArea']).send_keys(line)
                        FIREFOX_DRIVER.find_element_by_xpath(xpaths['submitMessage']).click()

if __name__ == "__main__":
    FIREFOX_DRIVER = webdriver.Firefox()

    login_to_rst('https://link-login', 'user', 'pass')
    write_to_chat('https://link-final-url')

I accept any constructive critiques as long as they are followed by a rational explanation.


texts:
I am building a web-application in NodeJS (using TypeScript) and MongoDB (using Mongoose).

In my application I have 6 types of permissions.  For the simplicity, let's use P1, P2, ..., P6 to represent my permissions. In addition, the application has several organizations.

Each user in the application belongs to one organization and can have several permissions (P1-P6) for each organization (not necessarily the one he belongs to).

For example:
 - User U1 belongs to O1 organization, has permissions P1, P3 in organization O1 and permissions P2, P6 in organization O2.
- User U2 belongs to O2 organization, has permission P1 in organization O2.
- User U3 belongs to O1 organization, has no permissions.

I am trying to implement this structure in the user schema (using Mongoose schema) and need some opinions about my implementations.

This is my user schema:

var userSchema: mongoose.Schema = new mongoose.Schema({
    _id: {
        type: String
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    mail: {
        type: String,
        required: true,
        unique: true
    },
    organization: { // User's organization
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Organization'
    },
    permissions: [{
        organization: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Organization'
        },
        permissions: [{
            type: String,
            enum: [
                Permission.P1,
                Permission.P2,
                Permission.P3,
                Permission.P4,
                Permission.P5,
                Permission.P6,
            ]
        }]
    }]
});

For the permissions enum I use:

export enum Permission {
    P1 = <any>'P1',
    P2 = <any>'P2',
    P3 = <any>'P3',
    P4 = <any>'P4',
    P5 = <any>'P5',
    P6 = <any>'P6',
}

I use this enum as string values because I think it's better to have the string value of the permission and not just the enum number values (1-6). Of course, the permission names (P1-P6) are replaced with the real permission name - for example, P1 is Administrator.

I am not sure about my current implementation and would like to get some opinions whether I am doing good or should I change something.


texts:
The shuffle method in ShuffleMethods.java takes an array of ints and shuffles them by chunks of ints in another array. So for example, if we had an array of ints called nums comprising of 0,1,2,3,4,5 and a chunks of ints of 2,1,3. The method reads the first element of the chunks array which is 2. The shuffle method then gets the first two elements of the nums array 0 & 1 and puts them at the end of the array to give this result: 2,3,4,5,0,1, Then for the next chunks of 1 the number is 2 is selected and put on top of the 0,1 giving this result 3,4,5,2,0,1. And then finally the last chunks of 3 selects 3, 4, 5 and puts them on top of the 2 giving this result 3,4,5,2,0,1.

The shuffle method algorithm complexity is currently \$O(n^3)\$. I am looking to get it down to \$O(n)\$. Also, I am hoping to improve the pairs method which finds the number of consecutive numbers from the original deck that are still together in the shuffled deck.

ShuffleApp.java

package Shuffle;

import java.util.Arrays;
public class ShuffleApp{

public static void main(String[] args){
      ShuffleMethods test = new ShuffleMethods();
      int[] test1 = {2, 1, 3};

     test.makeNew(6);
     test.shuffle(test1);
     test.pairs();
     test.print();
   }

}

Shuffle.java

package Shuffle;
public interface Shuffle{
    public void makeNew(int size);
    public int[] getCurrent();
    public void shuffle(int[] chunks);
    public int pairs();
}

ShuffleMethods.java

package Shuffle;
import java.util.*;

public class ShuffleMethods implements Shuffle{

    private int[] nums;
    private int[] numsCopy;

    /**Fills nums with ints based on user parameter from 0 to size-1**/
    public void makeNew(int size){
        nums = new int[size];
        for(int i = 0; i < size; i++){
            nums[i] = i;
        }
        numsCopy = nums.clone();
    }

    public int[] getCurrent(){
        return nums;
    }

    /**Shuffles the ints**/
    public void shuffle(int[] chunks){

        int temp = 0;
        int count = 0;
        int endIndex = nums.length;

            count = 0;
            while(chunks[i] > count) {

                temp = nums[0];

                for(int k = 1; k < endIndex; k++) {

                    //Move all the elements back
                    nums[k-1] = nums[k];

                }

                nums[endIndex-1] = temp;

                count++;

            }
            endIndex -= chunks[i];

        }
    }

    /**Returns the number of pairs of consecutive numbers in the shuffled deck that were together in the original**/
    public int pairs(){

       ArrayList<Integer> pairList = new ArrayList<Integer>();
        int pairs = 0;

        for(int i = 1; i < numsCopy.length; i++) {

            if (numsCopy[i-1] == numsCopy[i] - 1  && !pairList.contains(numsCopy[i-1]) && !pairList.contains(numsCopy[i])) {
                pairList.add(numsCopy[i-1]);
                pairList.add(numsCopy[i]);
            }
        }

         for(int i = 1; i < nums.length; i++) {

           if (nums[i-1] == nums[i] - 1 && pairList.contains(nums[i-1]) && pairList.contains(nums[i])) {
             pairList.remove(Integer.valueOf(nums[i-1]));
             pairList.remove(Integer.valueOf(nums[i]));
                pairs++;
            }

         }
       System.out.println("Number of pairs " + pairs);
        return pairs;

}


texts: Project Euler Problem #102 in F#: counting triangles that contain the origin

texts:
I've recently decided to get into functional programming with F#, and decided to learn the language through Project Euler. The following is my implementation of problem 102:

Problem:

  Three distinct points are plotted at random on a Cartesian plane, for
  which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.

  Consider the following two triangles:

  A(-340,495), B(-153,-910), C(835,-947)

  X(-175,41), Y(-421,-714), Z(574,-645)

  It can be verified that triangle ABC contains the origin, whereas
  triangle XYZ does not.

  Using triangles.txt (right click and 'Save Link/Target As...'), a 27K
  text file containing the co-ordinates of one thousand "random"
  triangles, find the number of triangles for which the interior
  contains the origin.

  NOTE: The first two examples in the file represent the triangles in
  the example given above.

Implementation:

type Coord = { x: int; y: int }

let origin = { x = 0; y = 0 }

let intToCoord [x; y] = { x = x; y = y }

let twiceTriangleArea a b c =
    abs (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y))

let containsOrigin [a; b; c] =
    twiceTriangleArea a b c = twiceTriangleArea origin a b +
        twiceTriangleArea origin b c +
        twiceTriangleArea origin a c

let solution =
    System.IO.File.ReadLines "triangles.txt"
    |> Seq.map (fun line ->
        line.Split ',' |> Array.map int |> List.ofArray |> List.chunkBySize 2 |> List.map intToCoord
    )
    |> Seq.filter containsOrigin
    |> Seq.length

printfn "%i" solution

Explanation:

This code iterates through each line of triangles.txt.
It then splits each line (by comma), takes elements in groups of 2, and converts them to coordinates.
For each of these three coordinates, it checks if they make a triangle containing the origin by checking if the sum of the areas of all triangles made from two of the passed points and the origin is equal to the total triangle area (with all three points). Note that the area isn't divided by 2 in order to prevent floating point errors. All triangles that do not meet this criteria are filtered out.
The number of remaining triangles are summed and printed to the user.

While making this, I tried to maintain a functional style as much as possible.

Here is what mainly I want to get from a review:

Is my code idiomatic and functional? Where can it be improved in this regard?
Are there any areas where I am unnecessarily doing extra computation and the code can be simplified?


texts:
My script, which is a web scraping script, is very slow, I even needed to put set_time_limit(0);

This is the whole http://phpfiddle.org/main/code/9qt-78n

I think the problem is here:

foreach ($array_with_links as $url_job) {

$info=Array(getTitle($url_job, getID($url_job)), getTitle_Short($url_job, getID($url_job)), getCity($url_job),
 getDepartment($url_job), getSalary($url_job), getJobNumber($url_job), getPositionStartDate($url_job), getFullTimeEquivalent($url_job),
  getPermTermCasual($url_job), getLocation($url_job), getQualifications($url_job), getDuties($url_job),
  getClosingDate($url_job), getContact($url_job), getEmail($url_job), getCreated_On($url_job), getID($url_job) );

array_push($data, $info);}

Example of some of those functions:

function getCity($url)
    {
    $url = curl_get_contents($url);
    $html_object = str_get_html($url);
    return $ret = $html_object->find('td', 86)->plaintext;
    }

function getDepartment($url)
    {
    $url = curl_get_contents($url);
    $html_object = str_get_html($url);
    return $ret = $html_object->find('td', 90)->plaintext;
    }

And this is my cURL funtion:

function curl_get_contents($url)
{
  $curl_moteur = curl_init();
  curl_setopt($curl_moteur, CURLOPT_URL, $url);
  curl_setopt($curl_moteur, CURLOPT_RETURNTRANSFER, 1);

  curl_setopt($curl_moteur,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

  curl_setopt($curl_moteur, CURLOPT_FOLLOWLOCATION, 1);
  $web = curl_exec($curl_moteur);
  curl_close($curl_moteur);
  return $web;
}

Those getX come from an URL one by one.  Maybe is there any method to make multiple simultaneous insertions in that array?

I really don't know what to do and what's my mistake.


texts: Python Decimal to Binary converter (without using bin() or output formatting)

texts:
There is no input validation for this, but that aside, I would appreciate it if anyone could help me improve the logic of this script.

import math
#Input
num = input("Enter a whole number: ")

#Floors input in case of a non whole number
decimal = math.floor(float(num))

#Variables
exp = 0
divTwo = 1
zeros = 0
total = ""
if decimal < 0:
    total += str('-')
    decimal = -decimal
if decimal == 0:
    total = str('0')
else:
    #Loops while remainder is > 0.
    while int(decimal) > 0:

        #Increases exponent by one if 2^exp is less than or equal to the remainder.
        if 2 ** exp <= int(decimal):
                exp += 1

        else: #Multiplies 2 by the exponent and places zeros in between 1s. Also subtracts from the exponent.
                exp -= 1

                #Determines whether or not to subtract from the remainder and add a '1' to the binary translation or just add a '0' to the binary translation.
                if 2 ** exp <= int(decimal):

                        #Counts how many zeros need to be added to the end of the binary translation.
                        if 2 ** exp == int(decimal):
                                divTwo = int(decimal)

                                #Loops until all remaining zeros have been accounted for.
                                while divTwo > 1:
                                        divTwo = divTwo / 2
                                        zeros += 1

                        decimal = int(decimal)
                        decimal -= 2 ** exp
                        total += str('1')

                else:
                        total += str('0')

#Places remaining zeros.
while zeros > 0:
        total += str('0')
        zeros -= 1

#Displays answer.
print ('Binary: ' + total)
input()

#
#
#Or 'bin(decimal)' works too, but this was for fun
#
#

Here is a working version of the script.


texts: x86-64 Assembly - Sum of multiples of 3 or 5

texts:
I'm trying to learn some basic x86 assembly and so I've begun solving Project Euler problems. I was hoping for some critique of my code that, hopefully, includes either the efficiency of the operations or the readability / style of the code itself. I will provide the Makefile for Linux 64 bit.
The purpose of the code is to sum all numbers from [0, 1000) that are divisible by 3 or 5.
The code can be run using make RUN=euler_1.
NB:
I am aware that most compilers replace modulos of known numbers with some combination of mov and shr to avoid the integer division. For example, see this thread.
Makefile
.PHONY: clean

all:    $(RUN).elf
    ./$^

%.elf:  %.o
    ld $^ -o $@ -lc -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2

%.o:    %.asm
    nasm -f elf64 $^

clean:
    rm -f *.o *.elf

euler_1.asm
extern printf
global main

section .data
fmt: db "%d", 0x0a, 0

section .text

;; main - Calculate the sum of all numbers between [0, 1000) that are divisible
;; by 3 or 5.
;;  sum : R8
main:
    ; sum = 0
    mov r8, 0
    ; for i in [0, 1000) {
    mov rcx, 0
for0:
    ; if i % 3 == 0 or i % 5 == 0 {

    ; i % 3 == 0
    mov rax, rcx
    mov rdx, 0
    mov r9, 3
    div r9
    test rdx, rdx
    jne if01
    ; sum = sum + i
    add r8, rcx
    jmp if0

if01:
    ; i % 5 == 0
    mov rax, rcx
    mov rdx, 0
    mov r9, 5
    div r9
    test rdx, rdx
    jne if0
    ; sum = sum + i
    add r8, rcx
    jmp if0
    ; }
if0:
    inc rcx
    cmp rcx, 1000
    jl  for0
    ; }

    ; printf("%d", sum)
    lea rdi, [rel fmt]
    mov rsi, r8
    mov rax, 0
    call printf

    ; sys_exit(0)
    mov rdi, 0
    mov rax, 60
    syscall


texts: Basic python dice simulator with log function

texts:
I had created a dice simulator using nothing but functions, but I wanted to attempt one using a class for the dice just to help get a better understanding of classes.  I'm still a little in the dark on OOP and I feel like it was poorly implemented here, but I achieved what I was going for and I feel like that's at least something.  Any tips on improvement would be appreciated.

#!/usr/bin/env python
import time
from sys import exit
from random import randint

class Die(object):
    """
    Creates a die class for use with a dice rolling utility

    """
    d_sides = None
    def __init__(self, sides = 6):
        self._sides = sides
        self._value = None
        self.roll()

    def roll(self):
        """
        Generate a random integer based off the number of sides
        """
        self._value = randint(1, self._sides)
        return self._value

    def __str__(self):
        """
        Return string containing dice sides and result
        """
        return "Die with {} sides.  Result : {}".format(self._sides, self._value)

def banner():
    """
    Print out in console upon running script
    """
    print "-" * 10
    print "Snake Eyes"
    print "-" * 10

def dice_cup():
    """
    Takes user input for number of sides and number of dice then creates
    dice objects respectively
    """
    global d_sides

    # Asks for a number of dice and verifies that it's a number
    while True:
        try:
            number = int(raw_input("How many dice?\n>"))
            break
        except(TypeError, ValueError):
            print "Please enter a number\n"

    # Asks for a number of sides and verifies that it's a number
    while True:
        try:
            sides = int(raw_input("How many sides?\n>"))
            d_sides = sides
            break
        except (TypeError, ValueError):
            print "Please enter a number\n"
    # Generates dice objects

    dice_roll = [Die(sides).roll() for _ in range(int(number))]
    return dice_roll

def print_dice(d):
    """
    Converts list of dice results into string and prints results and total
    """

    # Converts list of dice results into a string
    dice_str = ','.join(map(str, d))
    # Adds total from dice roll
    total = sum(d)
    print "You rolled: {}\nTotal: {}".format(dice_str, total)

def dice_log(sides, number, roll):
    dash = '-' * 4
    f = open("dice_log.txt","a")
    f.write('\n')
    f.write(time.strftime('%I:%M:%S'))
    f.write('\n')
    f.write(dash)
    f.write('\n{}d{}\n'.format(number, sides))
    f.write(dash)
    f.write('\n{}\n'.format(','.join(map(str, roll))))
    f.write(dash)
    f.write('\nTotal\n')
    f.write(dash)
    f.write('\n{}\n'.format(sum(roll)))
    f.close

def engine():
    global d_sides
    banner()
    raw_input("Press enter to begin.")
    while True:
        roll = dice_cup()
        print_dice(roll)
        dice_log(d_sides, len(roll) , roll)
        cont = raw_input("Return to roll again or quit to exit\n>")
        if cont.lower() == "quit":
            print "\nGoodbye."
            exit(0)

def main():
    engine()

if __name__ == "__main__":
    main()


texts:
This is my python solution to the first problem on Project Euler:

n = 1
rn = 0
while n < 1000:
    if n%3 == 0 or n%5 == 0:
        rn += n
    n = n + 1
print(rn)

I would like to find a way to keep everything in this python code to as little number of lines as possible (maybe even a one liner??), and possibly improve the speed (it's currently around 12 ms). By the way, this is the problem: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.Suggestions?Thanks.


texts: Dependency Injected StackExchange.Redis Client

texts:
I am currently building cache for my application, and I would like to have my redis cache client work the same way you would dependency inject a DbContext.

I am using StackExchange.Redis to manage my redis cache:
https://github.com/StackExchange/StackExchange.Redis

I have made it work, but I am not very confident in the way I implemented it.

In my services I have added:

        services.AddSingleton<IConnectionMultiplexer(ConnectionMultiplexer
            .Connect("localhost:6379,allowAdmin=true"));

        services.AddScoped<ICacheClient, CacheClient>();

I could not figure out how to add IDatabase to services.

My CacheClient looks like this:

    public class CacheClient : ICacheClient
    {
        private readonly IConnectionMultiplexer _connectionMultiplexer;
        private readonly IDatabase _redisCache;
        private readonly ISerializer _serializer;

        public CacheClient(IConnectionMultiplexer connectionMultiplexer, ISerializer serializer)
        {
            _connectionMultiplexer = connectionMultiplexer;
            _serializer = serializer;
            _redisCache = connectionMultiplexer.GetDatabase();
        }

        //add/set cache methods removed for the sake of brevity.

    }

From here I can use _redisCache to access the database and do operations such as _redisCache.StringSetAsync etc...

Now ICacheClient can be injected into my application and I can use my cache logic in any class. Which is very nice.

Is there anything wrong with this way of implementing my cache client?


texts: Javascript module for sorting and searching

texts:
Here is a vanilla JS module that I wrote for sorting and searching an array.

I would appreciate feedback on the design of the module as I'm new to writing javascript in modules and don't know if I'm missing the point.

"use strict";

/**
* Find is an outer function
* @param  {int}    needle      Value received from the user
* @param  {array}  haystack    An array returned by the user up to 100
* @return {obj}                returns an object that contains the sort and search functions
*/

function find(needle, haystack) {

//keeps track of the array length
var haystackLength = haystack.length;

 //Sort the array using Counting Sort O(n), so we can search the array faster
 function sort() {

 //INIt sorted array
 var sorted = [];

 //Create a counting array filled with zeros
 var maxLength = 1000;
 var countArray = (function buildCountArray(length) {
   var array = [];
   for( let i = 0; i < length; i++  ) {
     array[i] = 0;
   }
   return array;
 })(maxLength);

 //run through the haystack and add a count to the corresponding index in the couting array
 for( let i = 0, n = haystackLength; i < n; i++ ) {
   countArray[ haystack[i] ]++;
 }

 //At each index in the counting array add the summation of previous indexes
 for( let i = 0, n = countArray.length; i < n; i++ ) {
   countArray[ i + 1 ] =  countArray[i] + countArray[ i + 1 ];
 }

 //run through the haystack and match it up with the counting array and store it in the sorted array
 for( let i = 0, n = haystackLength; i < n; i++ ) {
   sorted[countArray[haystack[i]] - 1] = haystack[i];
   countArray[haystack[i]]--;
 }

 //sucess
 haystack = sorted;
 console.log("Here is your awesome sorted array:\n" + haystack);
 }

 //Uses Binary Search O(log n), to find the needle in the haystack
 function search() {

 //Track the index of the start of the haystack and the end of the haystack
 var left = 0;
 var right = haystackLength - 1;

 //A recursive IIFE that uses the left and right to determine the middle and then cuts the array
 //in half depending on where the needle lies compared to the middle
 return ( function binarySearch( left, right ) {

   //Once we search the haystack and we can't find the needle
   if( right < left) {
     console.log("Nope, Go fish!");
     return false;
 }

   //track the middle of the haystack
   var mid = Math.trunc( left + ( right - left ) / 2 );
   console.log("Chopping your array in half, chop....chop..:\n" + haystack[mid]);

   //Compare the middle of the haystack to the needle
   //Then move the start or end of the haystack to depend on the needle value
   if( needle === haystack[mid] ) {

     console.log("We found it!");
     return true;

   } else if ( needle < haystack[mid] ) {
     right = mid - 1;
   } else {
     left = mid + 1;
   }

   return binarySearch( left, right );

 })(left, right);

 }

 //Functions that will be available to use
 var publicAPI = {
   sort: sort,
 search: search
 }

 return publicAPI;
 }


texts: IsDatabaseUp returns true or throws exception

texts:
I want to write an ASP.NET Web API endpoint that allows clients to check if database is running.

The method below is check if database is up by establishing a connection and running a dummy sql statement. If exception is thrown, the database is down. Thus, it always return true when it is up.

public interface IDatabaseHealthStatus {
  bool IsDatabaseUp();
}

public class DatabaseHealthStatus :IDatabaseHealthStatus {

    public bool IsDatabaseUp(){

      using(var con = new SqlConnection(connectionString)
      using(var cmd= new SqlCommand("SELECT 1", con)
      {
          con.Open();
         cmd.ExecuteReader();
         return true;  //always returns true, unless exception throws
      }
    }

}

The calling method looks like below.

API controller action method:

[HttpGet]
public IHttpActionResult IsDatabaseUp(){

  databaseHealthStatus.IsDatabaseUp(); //return value is ignored. Exception is handled by global exception handler, if any
  return OK();

}

Questions:

1: IsDatabaseUp() returns boolean type, but it always returns true (not false), unless it throws exception, which might be confusing (that is, bool, only returns true, and exception). I don't want to catch exception within the method, and return false. Because I want global exception handler to handle it and log the exception. This way it makes the code cleaner by reducing try/catch block. But in this case, unless comment is put for the method, it might be confusing.

Is this the best way to return the result? What do you think?


texts: AngularJS directive for common form fields

texts:
I have created a directive for common form fields shared across all the forms in a large AngularJS app I am re-factoring.

The app has lots of forms for various data models (user, owners, victims, suppliers, etc). A lot of the forms for these data models contain an address section which is the same format throughout the app.

Address Line 1
Address Line 2
Town / City
County
Postcode
Country

Here is the markup for the directive:

 <address-dir
     address-line-one="user.address_line_1"
     address-line-two="user.address_line_2"
     address-town-city="user.address_town_city"
     address-county="user.county"
     address-postcode="user.postcode"
     address-country="user.address_country"
 >
 </address-dir>

The actual angular directive code is:

(function () {
    var app = angular.module('userDirectives', []);

    app.directive('addressDir', function () {
        return {
            restrict: "AE",
            require: '^form',
            scope: {
                addressLineOne: '=',
                addressLineTwo: '=',
                addressTownCity: '=',
                addressCounty: '=',
                addressPostcode: '=',
                addressCountry: '='
            },
            templateUrl: 'address.html',
            link: function (scope, element, attributes, form) {
                scope.addressForm = form;
            }
        };
    });
}());

Here is my address.html template which is the template used in the directive (I have removed all but the first field to simplify the example):

        Address Line 1

    <input
        type="text"
        id="address_1"
        name="address_1"
        ng-model="addressLineOne"
        required
        placeholder="address line 1"
    >

You did not enter first line of address

Here's a simple controller:

(function () {
    var app = angular.module('userControllers', []);

    app.controller('UserController', ['$scope', function ($scope) {

        $scope.user = {};

        // This is called when the form is sumitted

        $scope.continue = function () {

            console.log($scope.user);

            // save here

        };

        // get user
        User.get().then(function (user) {
            $scope.user = user;
        });

    }]);

}());

I'm working on the project solo for a while and I couldn't find any other directives that do something like this on the net (or at least for common fields in forms).

The reason I have made this a directive instead of a basic include is because I next want to add some custom DOM manipulations to the address section on some of the forms. Probably some third-party address lookup / validation integration.

It is quite basic at moment but I am looking for some external feedback on what I have so far and the direction I'm going in.


texts: Can I improve my jquery dialog code, critisicm welcome

texts:
Fairly new to jquery, can i improve this code please?

HTML

login

Javascript

function Dialog() {

    // Event handler for a dialog click.
    $('a.dialog').click(function () {

        var dialog = $("#" + this.id + "_dialog");

        // Bind the hide functions here, as the elements have now been loaded into the DOM.
        $("#overlay, #close").click(function () {
            HideDialog(dialog)
        });
        window.onresize = function () {
            CentreBoxInViewport(dialog);
        };

        SetupDialog(dialog);
        return false;
    });

    // Event handler for an image click.
    $('div.status > a').click(function () {

        // Get the object for the lightbox.
        var dialog = $("#lightbox");

        // Get the path to the image.
        var path = this.getAttribute("href");

        // Bind the hide functions here, as the elements have now been loaded into the DOM.
        $("#overlay, #close").click(function () {
            HideDialog(dialog)
        });
        window.onresize = function () {
            CentreBoxInViewport(dialog);
        };

        SetupLightBox(path, dialog);
        return false;
    });
}

function SetupLightBox(path, dialog) {

    // Create a new image.
    var image = new Image();

    // The onload function must come before we set the image's src, see link for explanation.
    // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.

    // Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
    image.onload = function () {
        $('#image').attr('src', path)
        CentreBoxInViewport(dialog);
        ShowOverlay(dialog);
    };

    // Set the src, and show the image.
    image.src = path;
}

function SetupDialog(dialog) {
    CentreBoxInViewport(dialog);
    ShowOverlay(dialog);
}

function ShowDialog(dialog) {
    dialog.fadeTo(200, 1);
}

function HideDialog(dialog) {
    dialog.fadeTo(200, 0, function () {
        dialog.hide();
        HideOverlay();
    });
}

function ShowOverlay(dialog) {
    $('#overlay').fadeTo(200, 0.5, function () {
        ShowDialog(dialog)
    });
}

function HideOverlay() {
    $('#overlay').fadeTo(200, 0, function () {
        $('#overlay').hide();
    });
}

function CentreBoxInViewport(dialog) {

    // Get the dimensions of the viewport.
    var height = $(window).height()
    var width = $(window).width();

    // Calculate the position of the lightbox.
    var boxtop = (height / 2) - dialog.height() / 2;
    var boxleft = (width / 2) - dialog.width() / 2;

    // Position the box.
    dialog.css({
        top: boxtop,
        left: boxleft
    });
}


texts:
I have a parser for CNF formulas in Dimacs format, which is very slow. Any suggestion on how to improve its speed? I did some profiling and I might have to replace Scanner. Is there anything faster?

A possible input for the parser is:

c A sample .cnf file.
p cnf 3 2
1 -3 0
2 3 -1 0

The code:

/**
 * Parses a stream for a CNF instance.
 *
 * @param source input stream
 * @return read skeleton
 * @throws ParseException if stream contains an invalid instance
 */
private static Skeleton parseStream(final InputStream source)
    throws IOException, ParseException {
  Scanner scanner = new Scanner(source);

  // Skip comments
  try {
    String token = scanner.next();
    while (token.equals("c")) {
      scanner.nextLine();
      token = scanner.next();
    }
    if (!token.equals("p")) {
      throw new ParseException(
          "Excepted 'p', but '" + token + "' was found");
    }
  } catch (NoSuchElementException e) {
    throw new ParseException("Header not found");
  }

  // Reads header
  int numVariables, numClauses;
  try {
    String cnf = scanner.next();
    if (!cnf.equals("cnf")) {
      throw new ParseException(
          "Expected 'cnf', but '" + cnf + "' was found");
    }
    numVariables = scanner.nextInt();
    numClauses = scanner.nextInt();
  } catch (NoSuchElementException e) {
    throw new ParseException("Incomplete header");
  }
  logger.debug("p cnf " + numVariables + " " + numClauses);

  // Reads clauses
  Skeleton skeleton = new Skeleton(numVariables);
  try {
    while (numClauses > 0) {
      int literal = scanner.nextInt();
      skeleton.cnf.add(literal);
      if (literal == 0) {
        numClauses--;
      }
    }
  } catch (NoSuchElementException e) {
    throw new ParseException(
        "Incomplete problem: " + numClauses + " clauses are missing");
  }

  return skeleton;
}


texts: Algorithm for finding inversions in Merge Sort

texts:
Please help in code reviews for readability, optimizing it, functionality etc.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;

public class Merge {

    static BigInteger cntInv = new BigInteger("0");

    static void mergeSort(int[] array){

        if(array.length > 1){

            int[] left = leftArray(array);
            int[] right = rightArray(array);

            mergeSort(left);
            mergeSort(right);

            merge(array,left,right);
        }
    }

    static int[] leftArray(int[] array){

        int size = array.length/2;
        int[] left = new int[size];
        for(int i =0 ; i<size;i++){
            left[i] = array[i];
        }
        return left;
    }

    static int[] rightArray(int[] array){

        int mid = array.length/2;
        int size = array.length - mid ;
        int[] right = new int[size];

        for(int i = 0 ; i<size;i++){
            right[i] = array[i + mid];
        }
        return right;
    }

    static void merge(int[] array, int[] left, int[] right){

    int iLeft = 0;
    int iRight = 0;

    /** Traverse through the array */
    for(int i=0;i<array.length;i++){
        if(iRight >= right.length || (iLeft<left.length && left[iLeft]<= right[iRight]) ){

            array[i] = left[iLeft];
            iLeft++;

        }else{

            if(left.length > 0 && iLeft < left.length) {

                cntInv = cntInv.add(BigInteger.valueOf(left.length - iLeft));

            }

            array[i] = right[iRight];
            iRight++;
        }
    }

}

static void display(int[] array){

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

    //System.out.println("Index of " + i + " : " + array[i]);

    }

}

private static int[] buildIntArray(ArrayList<Integer> integers) {
    int[] ints = new int[integers.size()];
    int i = 0;
    for (Integer n : integers) {
        ints[i++] = n;
    }
    return ints;
}

public static void main(String args[]) throws NumberFormatException, IOException{

    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    BufferedReader reader = new BufferedReader(new FileReader("./num_list.txt"));
    String line = null;
    while ((line = reader.readLine()) != null) {
        arrayList.add(Integer.parseInt(line));
    }

    int[] array = buildIntArray(arrayList);   // new int[10];

    System.out.println("List of number in the array befor sort");

    display(array);

    mergeSort(array);

    System.out.println("List of number in the array after sort");

    display(array);

    System.out.println("Done" + cntInv);

    }

}


texts: Drawing multiple polygons in Google Maps in the same style

texts:
To multiple Polygon objects in Google maps, I have to set same strokeWeight, fillColor and fillOpacity attributes. Is there a way how to add these only once or do it in a better way?

var hospitalPath = new google.maps.Polygon({
    path: hospitalPathCoords,
    strokeWeight: 0,
    fillColor: '#add78b',
    fillOpacity: 0.8
});
hospitalPath.setMap(map);

var airportPath = new google.maps.Polygon({
    path: airportPathCoords,
    strokeWeight: 0,
    fillColor: '#add78b',
    fillOpacity: 0.8
});
airportPath.setMap(map);

var restaurantPath = new google.maps.Polygon({
    path: restaurantPathCoords,
    strokeWeight: 0,
    fillColor: '#add78b',
    fillOpacity: 0.8
});
restaurantPath.setMap(map);


texts:
import java.util.Scanner;
import java.lang.Comparable;

class InsertionSort {
    private InsertionSort() {}

    private static boolean less(Comparable v, Comparable w) {
        return (v.compareTo(w) < 0);
    }

    private static void exch(Object[] a, int i, int j) {
        Object swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    private static void sort(Comparable[] a) {
        int length = a.length;
        for (int i = 0; i < length; i++) {
            // Maintain Invariant
            for (int j = i; j > 0; j--) {
                if (less(a[j], a[j - 1])) { // Invariant broken, fix it.
                    exch(a, j, j - 1);
                }
            }
        }
        // Postcondition: assert isSorted(a)
    }

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

    private static Integer[] readAllInts() {
        Scanner scanner = new Scanner(System.in);

        int numberOfItems;
        Integer[] items;
        if (scanner.hasNext()) {
            numberOfItems = scanner.nextInt();
            items = new Integer[numberOfItems];
        } else {
            // mybe throw an error?
            return new Integer[0];
        }

        int i = 0;
        while(scanner.hasNext() && i < numberOfItems) {
            items[i] = scanner.nextInt();
            i++;
        }
        return items;
    }

    public static void main(String[] args) {
        Integer[] items = InsertionSort.readAllInts();
        InsertionSort.sort(items);
        InsertionSort.show(items);
    }
}

Above is the implementation of the insertion sort algorithm. I want learn how to write algorithms as well Clean Code. Now below are the points which I have taken care of or am concerned about.

Kept meaningful names.
Declared variables near their usage.
Suppose, this code needs to consumed by many clients then where and what exception I should handle and throw.
Kept variable scopes to as local as possible for easy GC.
Most of the methods are static because I don't think they belong to a particular object.

That's it for now, I will keep updating the list if something comes to me later.

Ref: Algorithms


texts: Is my error handling feasible when dealing items not found in an array?

texts:
internal void ShiftSwapInstrument(SwapCurve shiftedCurve, string swapToShift)
 {
    if (SwapExists(shiftedCurve, swapToShift))
    {
       var rateToShift = shiftedCurve.Swaps.Single(r => r.Description() == swapToShift);
       rateToShift.Rate = rateToShift.Rate + 1 / 10000.0;
       return;
    }
    throw new PdhSwapRateNotFoundException(swapToShift);
 }

 private bool SwapExists(SwapCurve shiftedCurve, string swapToShift)
 {
    var swap = Array.Find(shiftedCurve.Swaps, r => r.Description() == swapToShift);
    return swap == null ? false : true;
 }

The above code is what I've written to handle processing when an item is not found in an array. The exception should 'never' be thrown - it's truly exceptional if it does happen - thus I can use Single without reservation within the if-block.

My question is whether my exception handling is correct/feasible when items are not found in my array and is it correct for me to return; when I do?

Secondary question

I noted the following about Array.Find on MSDN

  Return Value

  Type: T The first element that matches the conditions defined by the
  specified predicate, if found; otherwise, the default value for type
  T.

Am I correct in my understanding, that since SwapCurve & Swaps are reference types the default value will be null?


texts: SE Data Explorer Query: Average score for questions and answers, by tag

texts:
Being curious to see which tags on this site get the most attention, I developed a Stack Exchange Data Explorer query:

WITH CanonicalTags AS (
    SELECT Id, TagName, Id AS AliasId, TagName AS Alias
        FROM Tags
        WHERE NOT EXISTS (
            SELECT Id
                FROM TagSynonyms
                WHERE SourceTagName=TagName AND ApprovedByUserId IS NOT NULL
        )
        UNION
    SELECT Tags.Id, Tags.TagName, Alias.Id AS AliasId, Alias.TagName
        FROM Tags
            INNER JOIN TagSynonyms
                ON TargetTagName=TagName
            INNER JOIN Tags AS Alias
                ON Alias.TagName=SourceTagName
        WHERE ApprovedByUserId IS NOT NULL
), TagQuestionStats AS (
    SELECT Tags.Id AS Id
         , Tags.TagName AS TagName
         , AVG(CAST(Questions.Score AS DECIMAL)) AS AvgScore
         , STDEV(Questions.Score) AS StdDevScore
         , COUNT(Questions.Id) AS N
        FROM CanonicalTags AS Tags
            INNER JOIN PostTags
                ON PostTags.TagId=Tags.AliasId
            INNER JOIN Posts AS Questions
                ON Questions.Id=PostTags.PostId
        GROUP BY Tags.Id, Tags.TagName
), TagAnswerStats AS (
    SELECT Tags.Id AS Id
         , Tags.TagName AS TagName
         , AVG(CAST(Answers.Score AS DECIMAL)) AS AvgScore
         , STDEV(Answers.Score) AS StdDevScore
         , COUNT(Answers.Id) AS N
        FROM CanonicalTags AS Tags
            INNER JOIN PostTags
                ON PostTags.TagId=Tags.AliasId
            INNER JOIN Posts AS Questions
                ON Questions.Id=PostTags.PostId
        INNER JOIN Posts AS Answers
            ON Answers.ParentId=Questions.Id
        WHERE
            Answers.PostTypeId=2
        GROUP BY Tags.Id, Tags.TagName
)
SELECT '<' + QStats.TagName + '>' AS [TagName]
     , ROUND(QStats.AvgScore, 2) AS [Avg Qst Score]
     , ROUND(QStats.StdDevScore, 2) AS [Qst Score Std Dev]
     , QStats.N AS [# Qst]
     , ROUND(AStats.AvgScore, 2) AS [Avg Ans Score]
     , ROUND(AStats.StdDevScore, 2) AS [Ans Score Std Dev]
     , AStats.N AS [# Ans]
     , ROUND(CAST(AStats.N AS DECIMAL) / CAST(QStats.N AS DECIMAL), 2) AS [Avg # Ans/Qst]
    FROM
        TagQuestionStats AS QStats
            LEFT OUTER JOIN TagAnswerStats AS AStats
                ON AStats.Id=QStats.Id
    ORDER BY 5 DESC, 2 DESC, 7, 4, 1;

I'd like to ask:

Some of the numbers don't round to two decimal places very well.  Is that due to a bug in SQL Server, or am I using inappropriate rounding techniques?  (The exact numbers don't matter; I'd much rather have a compact presentation.)
Is there an easier way to canonicalize the tags?
Any comments about my SQL formulation in general?
Any suggestions for making the query itself more meaningful?


texts:
A class Array which contains two data members: a pointer on array of complex numbers and the length of the array. Implement a function for reading the array. The class should have a constructor, destructor and copy constructor. In the main program, enter the array of complex numbers.

main.cpp

#include <iostream>
#include "complex.h"

using namespace std;

class Array{
private:
complex *n;
int length;
public:
Array(void);
Array(int,complex *);
~Array();
Array(const Array &);
void print_array(void);
};

Array::Array(void){
}

Array::Array(int _length, complex *_n){
length=_length;
n=new complex[length];
for(int i=0;i<length;i++){
n[i]=_n[i];
}
}

Array::~Array(){
delete [] n;
n=0;
}

 Array::Array(const Array & _n){
 length=_n.length;
 n=new complex[length];
 for(int i=0;i<length;i++){
 n[i]=_n.n[i];
 }
 }

 void Array::print_array(void){
 for(int i=0;i<length;i++){
 cout<<""<<(n[i]).return_real()<<"+("<<(n[i]).return_imaginary()<<")j"    <<endl;
 }
 }

 int main()
 {
 complex *numbers;
 int length;
 float a,b;
 cout<<"How many complex numbers you will enter? "<<endl;
 cin>>length;
 numbers=new complex[length];
 cout<<"Enter real and imaginary parts of "<<length<<" complex numbers"   <<endl;
 for(int i=0;i<length;i++){
 cin>>a>>b;
 numbers[i]=complex(a,b);
 }
 Array n1(length, numbers);
 n1.print_array();
 Array n2(n1);
 }

complex.cpp

#include "complex.h"

complex::complex(void){
}

complex::complex(float a,float b){
real=a;
imaginary=b;
}

complex::~complex(){
}

float complex::return_real(void){
return real;
}

float complex::return_imaginary(void){
return imaginary;
}

complex.h

#ifndef COMPLEX_H_INCLUDED
#define COMPLEX_H_INCLUDED

class complex{
private:
float real;
float imaginary;
public:
complex(void);
complex(float,float);
~complex();
float return_real(void);
float return_imaginary(void);
};

#endif // COMPLEX_H_INCLUDED

I tested it and it works. I want to know if there is something I can do to improve it.


texts: SICP exercise 1.3 - sum of squares of two largest of three numbers

texts:
From SICP

Exercise 1.3: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

Square is:

(define (square x) (* x x))

I know the code could be written using language features like lambda or let, but first to remain true to the exercise, I wouldn't use features that are not discussed yet.

I took advantage of the fact that we only have three numbers that's why I am able to reduce my code into two if statements. All of the tests I've done produced correct output.

Please review my code.

(define (sum-of-squares a b c)
    (if (> a b)
        (+ (square a)
            (square (if (> b c)
                b
                c)))
        (+ (square b)
            (square (if (> a c)
                a
                c)))))

Here's an implementation with let. If possible I would like this reviewed as well.

(define (sum-of-squares a b c)
    (let ((bc (if (> b c) b c))
    (ac (if (> a c) a c)))
    (if (> a b)
        (+ (square a) (square bc))
        (+ (square b) (square ac)))))

Now, I find this second implementation not shorter than the first, but I think it's easier to read because it can be difficult to read expressions with more expressions nested inside as with the first implementation. On the other hand I realized it's worthless to do this because the variables aren't used more than once. For expressions more complicated than expressions contained in this procedure, would it be a good idea to put them inside let even if they are only used once?

How can I improve these codes and make them faster?


texts:
I've thrown together a utility for my programs to log to a database, but the code looks like a mess and I don't know how to clean it up. This library is going to be used from all of my other programs and it is therefore important to keep the code clean and secure.

#include <log_entry.h>

#include <my_global.h>
#include <mysql.h>

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

#define STR_BUFFER_SIZE 256

#define NELEMS(x)  (sizeof(x) / sizeof(x[0]))

void finish_with_error (MYSQL *);

int ltdb (LOG_ENTRY *ent)
{
    MYSQL *con = NULL;
    char time[16], date[16];
    char query[STR_BUFFER_SIZE];
    int len;

    con = mysql_init(NULL);
    if(NULL == con){
        fprintf(stderr, "%s\n", mysql_error(con));
        return 1;
    }

    if(NULL == mysql_real_connect(con, "localhost", "user", "password", "database", 0, NULL, 0)){
        finish_with_error(con);
        return 1;
    }

    strftime(time, NELEMS(time), "%H:%M:%S", ent->tm_info);
    strftime(date, NELEMS(date), "%Y-%m-%d", ent->tm_info);

    len = snprintf(query, STR_BUFFER_SIZE,
    "INSERT INTO `logg` ("
    "   severity,event,source,time,date"
    ") VALUES ("
    "   '%d', '%s', '%s', '%s', '%s'"
    ")",    ent->severity,
            ent->event,
            ent->source,
            time,
            date);

    if(len >= STR_BUFFER_SIZE){
        fprintf(stderr, "MySQL query too long! (> %d)\n", STR_BUFFER_SIZE);
        return 1;
    }

    if(mysql_query(con, query)){
        finish_with_error(con);
        return 1;
    }
    mysql_close(con);

    return 0;
}

void finish_with_error(MYSQL *con)
{
    fprintf(stderr, "%s\n", mysql_error(con));
    mysql_close(con);
}

I'm trying to achieve a fast and simple way to process my log entries, but I'm not really happy with the code structure in general. Any suggestions for improvements would be much appreciated.

Here is the table structure of logg

CREATE TABLE IF NOT EXISTS `logg` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `severity` tinyint(4) NOT NULL,
  `event` varchar(128) NOT NULL,
  `source` varchar(32) NOT NULL,
  `time` time NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;

I limit the length to avoid any potential security risk, and save storage in my database. I don't really need any longer log messages.

Here is also the definition of my LOG_ENTRY struct:

typedef struct {
    int severity;
    char *event ;
    char *source;
    struct tm *tm_info;
} LOG_ENTRY;


texts:
Is this a good approach for a BayeuxClient class?

Reading cometd reference book, Chapter 6 Java Libraries, I created this BayeuxClient class.

As a newbie to cometd, I would like to know if this class has any flaws:

import java.util.*;
import java.net.URL;
import org.cometd.client.BayeuxClient;
import org.eclipse.jetty.client.HttpClient;

public class CometD_Client extends BayeuxClient
{
    private URL BayeuxServer_URL;

    private HttpClient JettyHttpClient;

    private Map<String, Object> TransportOptions;

    private ClientTransport C_Transport;

    private ClientSession C_Session;

    private boolean HandIsShaken£ = false;

    private final ClientSessionChannel.MessageListener MyChannelListener;

    public CometD_Client(URL BayeuxServer_URL)
    {
        this.BayeuxServer_URL = BayeuxServer_URL;

        // Create (and eventually set up) Jetty's HttpClient;
        JettyHttpClient = new HttpClient();
        JettyHttpClient.start();

        // Prepare the transport;
        TransportOptions = new HashMap<String, Object>();

        ClientTransport C_Transport =
            LongPollingTransport.create(TransportOptions,
                                        JettyHttpClient  );

        C_Session = new BayeuxClient(URL, C_Transport);

        C_Session.handshake();

        HandIsShaken£ =
            C_Session.waitFor(1000, BayeuxClient.State.CONNECTED);

        if(HandIsShaken£)
        {
            // TO DO: Output that the handshake had succeed;
        }
        else
        {
            // TO DO: Output that the handshake had failed;
        }

        MyChannelListener = new AChannelListener();

        C_Session.getChannel(Channel.META_HANDSHAKE).addListener
        (
         new ClientSessionChannel.MessageListener()
         {
            @Override
            public void onMessage(ClientSessionChannel ThisMetaChanel,
                                  Message msg)
            {
                // TO DO: Output msg to check it out;

                C_Session.getChannel("/myBroadcast/myChannel").subscribe
                (
                 new ClientSessionChannel.MessageListener()
                 {
                    @Override
                    public void onMessage(ClientSessionChannel ThisMetaChanel,
                                          Message msg)
                    {
                        // TO DO: Handle the received messages to this chaned;
                    }
                 }
                );
            }
         }
        );
    }

    public boolean GetIfHandIsShaken£()
    {
        return HandIsShaken£;
    }
}


texts: Finding combination of coins that can produce a given sum

texts:
This function is checking, whether it has enough money in a list called self.deviceMoney to make change.

It works exactly the way I want, but only in case where not many coins are in self.deviceMoney. The algorithm is checking, if the list has enough coins to create some number, if yes remove that many coins from list.

Example

Number = 8
self.deviceMoney=[1,3,4,5,2]

Now, we can create this number from [3,4,1] or [5,3] etc.

List after operation self.deviceMoney == [5,2]

When I put into this list for example 200 coins, my program stops responding. I think, because a large amount of itertools.combinations. How can I optimize this function or resolve this problem to make the algorithm much better?

def changeOperation(self):
    self.deviceMoney.sort()
    tmpChange=int(self.change*100)
    tmp=set()
   # print(self.change)
    print(self.deviceMoney)

    if self.change > 0:
        for i in range(1,len(self.deviceMoney)):
            for j in itertools.combinations(self.deviceMoney,i):
                if sum(j) == tmpChange:
                    tmp.add(tuple(j))
                    print("tmp.append(list(j)): " +str(tmp))

        if tmp:
            a = next(iter(tmp))
            print("a: " + str(a))
            print("a[0]= ",a[0])
            for k in range(len(a)):
                self.deviceMoney.remove(a[k])

            print("deviceMoney: "+str(self.deviceMoney))

            self.errorMessageBox("some string"))
        else:
            self.errorMessageBox("some string")
            self.deviceMoney=[]

    elif self.change == 0:
        self.errorMessageBox("some string")

    else:
        pass

 #prints for tests


texts: MATLAB / vs Python np.linalg.solve, heat diffusion, Why Python is slow?

texts:
I am solving a simple 1D steady heat question using spectral method. I am a long time MATLAB and Mathematica user and trying to learn Python. I compare only linear solving times and Python is way slower than MATLAB which doesn't feel right. Can you please tell me why Python is an order of magnitude slower for only even linear solve?

MATLAB code

  N=5000;
% HERE I AM JUST CREATING THE MATRIX FOR d/dx
 Dhat=zeros(N+1,N+1);

 for j=1:N;
 for i=mod(j-1,2):2:j;
 Dhat(i+1,j+1)=2*j;
 end
 end
 Dhat(1,:)=Dhat(1,:)/2;
 cbar=[2; ones(N-1,1); 2];
 p=0:1:N;
 pn=cos((pi/N)*kron(p',p));
 I=ones(N+1,1);
 II=(-1).^(0:N);
 G=kron(I,II);
 x=-cos(pi*(0:N)/N)';
 T=G.*pn;
 Tinv=(2/N)*(G'./kron(cbar,cbar')).*pn;

 D=T*Dhat*Tinv;     % derivative matrix
 % We have d/dx matrix

 D2=D*D;            % d2/dx2 to solve d^2T/dx^2 = F

 T0= 0;             % Temp at left boundary
 Tn= 10;            % Temp at right boundary
 F= zeros(N+1,1);   % source term
 F(1)=0;            % Boundary condition
  F(end)=10;         % Boundary condition

 D2(1,:)=zeros;
 D2(end,:)=zeros;
 D2(1,1)=1;          % At the left boundary T = 0
 D2(end,end)=1;      % At the right boundary T = 10
 tic
 T=D2/F';
 toc

Python code

def chebgl(N):
    import numpy as np
    cbar = np.array([1] * (N - 1))
    cbar = np.insert(cbar, 0, 2)
    cbar = np.insert(cbar, N, 2)

    p = np.array(range(N + 1))
    pkp = np.kron(p, p)
    pkp = pkp.reshape(N + 1, N + 1)
    pn = np.cos((np.pi / N) * pkp)

    I = np.ones(N + 1)
    Ia = -1 * np.ones(N + 1)
    II = np.power(Ia, range(N + 1))
    G = np.kron(I, II)
    G = G.reshape(N + 1, N + 1)

    T = np.multiply(G, pn)
    GTrans = np.transpose(G)

    cbarK = np.kron(cbar, cbar)
    cbarK = cbarK.reshape(N + 1, N + 1)

    Tinv = (2 / N) * np.multiply((np.divide(GTrans, cbarK)), pn)

    dhat = np.zeros((N + 1, N + 1))

    for j in range(1, N + 1, 1):

         for i in range((j - 1) % 2, j, 2):
             dhat[i, j] = 2 * j

    dhat[0] = dhat[0] / 2
     # This is the operator for d/dx

     D = np.matmul(np.matmul(T, dhat), Tinv)
     # predefined x-locations
     x = -np.cos(np.pi * (p / N))

     return D, x

Main code

import numpy as np
import chebGL
import matplotlib.pyplot as plt
from time import process_time

# Because I want to see all double precision digits
np.set_printoptions(precision=15)
# Number of points (d^2/dx^2) T = F(x) is going to be solved
N=5000

D, x = chebGL.chebgl(N)

T0 = 0        # Left boundary condition
Tend = 10     # Right boundary condition
F = 0 * np.ones(N + 1)  # Source Term
F[0] = T0     # inputting the boundary condition
F[N] = Tend  # inputting the boundary condition

D2T = np.matmul(D,D)     # Creating d^2/dx^2 operator
D2T[0] = abs(0 * D2T[0])
D2T[N] = abs(0 * D2T[0])

D2T[0,0] = 1     # inputting the left boundary condition
D2T[N,N] = 1    # inputting the right boundary condition

t1_start = process_time()

T = np.linalg.solve(D2T, F)
t1_stop = process_time()

print("Elapsed time during the whole program in seconds:", t1_stop-
t1_start)


texts:
Please evaluate this function. It takes a list [a] and an Int, i.e. the index, and returns a new list with the selected item at the top of the list. Note that it returns Maybe [a] to account for bad indexes.

pushToTop :: [a] -> Int -> Maybe [a]
pushToTop [] _   = Just []
pushToTop xs i
  | i >= length xs || i < 0 = Nothing
  | i == 0                  = Just xs
  | otherwise               = Just $ newTop : rest
                              where zipped = zip [0..] xs
                                    newTop = xs !! i
                                    rest   = (map (\x -> snd x) . filter (\x -> fst x /= i)) zipped

I'm also curious if my usage of !! is OK given the 2 guards on i.


texts:
I have JSON with references to other parts in that JSON file.

// the function I would like to be reviewed
function referenceToObject(json, reference){
    return (new Function(
            'json', 'return json' + reference
    ))(json);
}

// json
var example = {
    "target": "['first']['second']",
    "first": {
        second: 'hi'
    }
};

// execution
console.log(referenceToObject(example, example.target));

That function basically executes like this:

return json['one']['two'];

Is there a better way to extract the JSON reference? I'm able to change every bit of this code, as well as the JSON because we are reworking the front- and the backend. So, if you have ideas to improve the JSON instead of the Javascript that would also be great.


texts: Manipulating a .csv file to look for two common values to create a key, then summing up values

texts:
My code reads a .csv file, looks for a couple values to create its key, and then wraps up the data based on a few business rules I have. I'm trying to learn "the right way", so I'd really appreciate some tips and hints.

import csv
import sys

# add DictReader
with open(sys.argv[1], 'rbU') as csvinfile:
    myreader = csv.reader(csvinfile, delimiter=',', quotechar='"')

    # initialize variables and dictionaries
    line_cntr = 0
    dict = {}
    cntr = {}

    for row in myreader:
        # constant values
        nd_amt = row[14]
        deduct_amt = row[15]
        nondeduct_ytd = row[16]
        deduct_ytd = row[17]
        pid = row[18]
        don_date = row[19]
        amount = row[23]
        anon = row[25]
        int_0003 = row[38]
        int_0006 = row[39]
        int_0028 = row[40]

        # create a composite key for our dictionary
        key = pid + ":" + don_date
        # check to see if key exists in dictionary, if not then add
        # as per BR-0010 every group of up to 6 entries with same P_ID and Don_Date should print on their own line (i.e. different entry in Dict).
        if key in dict:
            if cntr[key] % 6 != 0:
                dict[key][14] += row[14]
                dict[key][15] += row[15]
                dict[key][16] += row[16]
                dict[key][17] += row[17]
                dict[key][23] += row[23]
                cntr[key] += 1
            else:
                key = pid + ":" + don_date + ":" + str(cntr[key]//6)
                dict[key] = row
        else:
            dict[key] = row
            cntr[key] = 1

        # debugging
        for key in cntr:
            if cntr[key] > 6:
                print(key, cntr[key])

        # keep track of lines processed for recon
        line_cntr += 1

# add DictWriter
with open(sys.argv[2], 'wb') as csvoutfile:
    mywriter = csv.writer(csvoutfile, delimiter=',', quotechar='"')

    for key in dict:
        outline = (key, dict[key])
        mywriter.writerow(outline)

    # print recon totals at bottom
    csvoutfile.write("Total lines processed: " + str(line_cntr))

I have some comments in there about wanting to try out DictReader/DictWriter in my next draft of code, so if anyone has tips on that it would be much appreciated as well.


texts: Find array index with element equality in Python

texts:
I was given this question during an interview. It is similar to binary search and I would like to ask for feedback for my solution.

  Array Index & Element Equality

  Given a sorted array arr of distinct integers, write a function
  indexEqualsValueSearch that returns the lowest index i for which
  arr[i] == i. Return -1 if there is no such index. Analyze the time and
  space complexities of your solution and explain its correctness.

  Examples:

  input: arr = [-8,0,2,5]
  output: 2 # since arr[2] == 2

  input: arr = [-1,0,3,6]
  output: -1 # since no index in arr satisfies
  arr[i] == i.

def index_equals_value_search(arr):
  left = 0
  right = len(arr) -1

  ind = 0
  output = -1

  while left <= right:
    ind = (left + right) // 2
    if arr[ind] - ind < 0:
      left = ind + 1
    elif arr[ind] == ind:
      output = ind
      break
    else:
      right = ind -1
  return output

Passing all of the basic tests

arr = [-8,0,2,5]
test1 = index_equals_value_search(arr)
arr2 = [-1,0,3,6]
test2 = index_equals_value_search(arr2)
print(test2) # return -1
arr3 = [0,1,2,3]
test3 = index_equals_value_search(arr3)
print(test3) # return 0
arr4 = [-6,-5,-4,-1,1,3,5,7]
test4 = index_equals_value_search(arr4)
print(test4) #return 7


texts:
I am an absolute newcomer in R. For my bachelor thesis I worked with spatial data. I did many plots with the normal "points"-function. I already have my results, but would like to improve my code.

This is the first example: (leg and colours were defined previously. WLPoi is a SpatialPointsDataFrame, german_reich_polyline_new is a SpatialLinesDataFrame and GEPolnew is a SpatialPolygonDataFrame. All of them have the same projection.)

SelNegativbelege <- (WLPoi$lfp_bra < 1) & (WLPoi$lfp_ack_se < 1) & (WLPoi$lfp_ack_na < 1) & (WLPoi$lfp_bau < 1) & (WLPoi$lfp_fel < 1) & (WLPoi$lfp_pfl_zu < 1) & (WLPoi$lfp_zu_na < 1) & (WLPoi$lfp_grab < 1) & (WLPoi$lfp_hack < 1) & (WLPoi$lfp_pfl_na < 1) & (WLPoi$lfp_pfl < 1)
SelHack <- (WLPoi$lfp_hack > 0)
SelGrab <- (WLPoi$lfp_grab > 0)
...

plot(GEPolnew, fill= NA)
points(WLPoi[SelNegativbelege,], col=colormint, cex=.3, pch=16)
points(WLPoi[SelHack,], col=colorolive, pch=16, cex=1)
points(WLPoi[SelGrab,], col=colorgold, pch=16, cex=1) …
lines(german_reich_polyline_new, lwd=2) legend("bottomright", leg, cex=0.55, bty="n",pch=19, col=c(colormint,colormaroon, colorolive, colorgold, colorred, c7, colortomato))

Maybe someone has also an advice how I can shorten:

EUnew_merge$lfp_bra100 <- ((EUnew_merge$lfp_bra)*100)
EUnew_merge$lfp_ack_se100 <- ((EUnew_merge$lfp_ack_se)*100)
EUnew_merge$lfp_ack_na100 <- ((EUnew_merge$lfp_ack_na)*100)
EUnew_merge$lfp_bau100 <- ((EUnew_merge$lfp_bau)*100)
EUnew_merge$lfp_fel100 <- ((EUnew_merge$lfp_fel)*100)
EUnew_merge$lfp_pfl_zu100 <- ((EUnew_merge$lfp_pfl_zu)*100)
EUnew_merge$lfp_zu_na100 <- ((EUnew_merge$lfp_zu_na)*100)
EUnew_merge$lfp_grab100 <- ((EUnew_merge$lfp_grab)*100)
EUnew_merge$lfp_hack100 <- ((EUnew_merge$lfp_hack)*100)
EUnew_merge$lfp_pfl_na100 <- ((EUnew_merge$lfp_pfl_na)*100)
EUnew_merge$lfp_pfl100 <- ((EUnew_merge$lfp_pfl)*100)
EUnew_merge$Pflug100 <- ((EUnew_merge$Pflug)*100)

Or

selac0 <- (GEPolnew_merge$PFLUGNF4AC == 0)
selac1 <- (GEPolnew_merge$PFLUGNF4AC > 0)
selac2 <- (GEPolnew_merge$PFLUGNF4AC > 0.02)
selac3 <- (GEPolnew_merge$PFLUGNF4AC > 0.05)
selac4 <- (GEPolnew_merge$PFLUGNF4AC > 0.1)
selac5 <- (GEPolnew_merge$PFLUGNF4AC > 0.2)
selac6 <- (GEPolnew_merge$PFLUGNF4AC > 0.5)
selac7 <- (GEPolnew_merge$PFLUGNF4AC > 0.8)
selac8 <- (GEPolnew_merge$PFLUGNF4AC == 1)

or

plot(GEPolnew_merge, fill=NA) plot(GEPolnew_merge[selac0,], col=c1, add= TRUE) plot(GEPolnew_merge[selac1,], col=c2, add= TRUE)
plot(GEPolnew_merge[selac2,], col=c3, add= TRUE)
plot(GEPolnew_merge[selac3,], col=c4, add= TRUE)
plot(GEPolnew_merge[selac4,], col=c5, add= TRUE)
plot(GEPolnew_merge[selac5,], col=c6, add= TRUE)
plot(GEPolnew_merge[selac6,], col=c7, add= TRUE)
plot(GEPolnew_merge[selac7,], col=c8, add= TRUE)
plot(GEPolnew_merge[selac8,], col=c9, add= TRUE)
lines(german_reich_polyline_new, lwd=3)
legend("bottomright", legc3, cex=1.15, bty="n",pch=c(1,19,19,19,19,19,19,19,19,19), col=c(rgb(0,0,0),c1,c2,c3,c4,c5,c6,c7,c8,c9))


texts: Finding the max error of a set of training data

texts:
I wrote a neural net, and a Trainer class that automates training the net using a training set; a set of input, and the expected output value.

Originally, I was just returning currentError from train to be the highest error so far in the training routine. Obviously though, currentError isn't actually the worst error, and returning it lead to partially trained nets being marked as "trained" due to a single input giving a very good result.

To fix this, I realized that I needed to keep track of the worst error for all of the inputs; the net shouldn't be considered trained just because 1 input has a low error. To achieve this, I included in the class a Map between an input set, and its current error.

The problem with this approach is to find the worst error of all of the input sets, I need to iterate the entire set of values (the errors). I'm only training logic gates right now, so the training sets are very small, but doing a complete iteration of the errors would get very costly with higher numbers of training sets (the training routine currently does ~30,000 training passes per second).

Is there a better way of achieving this?

I'm only going to include the Training class, so it won't be runnable. The entire project is huge (for my standards; 14 classes), so it would be impractical to include it all here. It should also be fairly easy to infer the contents of the Trainer interface.

RandomOrderTrainer.java:

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.UnaryOperator;

import neuralNet.NeuralNet.BackpropAlgorithm;

public class RandomOrderTrainer
        implements Trainer<Double> {

    final private NeuralNet net;
    final private BackpropAlgorithm backProp;
    final private Map<List<Double>, List<Double>> answerMap = new HashMap<List<Double>, List<Double>>();
    final private Map<List<Double>, Double> errorsMap = new HashMap<List<Double>, Double>();
    final private Random randGen;
    final private UnaryOperator<Double> actF;
    final private UnaryOperator<Double> actDeriv;

    public RandomOrderTrainer(NeuralNet net, Random randGen, UnaryOperator<Double> actF, UnaryOperator<Double> actDeriv) {
        this.net = net;
        this.backProp = net.getBackpropagator();
        this.randGen = randGen;
        this.actF = actF;
        this.actDeriv = actDeriv;
    }

    @Override
    public void addPair(List<Double> input, List<Double> expectedOutput) {
        answerMap.put(input, expectedOutput);
    }

    private double sumErrors(Collection<Double> errors) {
        double sum = 0;
        for (Double error : errors) {
            sum += Math.abs(error);
        }

        return sum;
    }

    @Override
    public void train() {
        List<Double> randInput = randInputSet();
        List<Double> expectedOutput = answerMap.get(randInput);

        net.fireNet(randInput, actF);
        backProp.backpropagateError(expectedOutput, actDeriv);

        double currentError = sumErrors( backProp.calcOutputError(expectedOutput, actDeriv).values() );

        Double previousError = errorsMap.get(randInput);

        if (previousError == null || currentError < previousError) {
            errorsMap.put(randInput, currentError);
        }
    }

    @Override
    public Double getHighestError() {
        Double highestError = 0.0;

        for (Double error : errorsMap.values()) {
            if (error > highestError) {
                highestError = error;
            }
        }

        return highestError;
    }

    private List<Double> randInputSet() {
        ArrayList<List<Double>> keyList = new ArrayList<List<Double>>(answerMap.keySet());

        return Util.randomElement(keyList, randGen);
    }

}


texts: I want to clean up this console app calculator (VB.net)

texts:
Getting started in VB.net I've written this console calculator based heavily off Nicholas Dingle youtube channel (in case it looks familiar). What I want to do is have a separate sub called Operation(parameter) and take the if statements out of CollectNumbers() since it doesn't make sense to have them in that sub. To make this happen I think what i'll end up needing to do is use Enum for the different operations, but don't know how to implement it. I think also the calling of CollectNumbers() will have to be reworked as well. I'm not looking for anyone to write it out, but a nudge in the right direction or tips would be very helpful.
Imports System.Runtime.Remoting.Services
Imports System.Threading

Module Module1

Sub Main()

    Menu()

End Sub

'Enum operations

'    Add = 1
'    Subtract = 2
'    Multiply = 3
'    Divide = 4

'End Enum

Sub Menu()

    Dim selection As String

    Console.Clear()

    Console.WriteLine("Say Hello To My Little Calculator!")
    Console.WriteLine() 'print blank line
    Console.WriteLine("Please press...")
    Console.WriteLine() 'print blank line
    Console.WriteLine("(A) to Add")
    Console.WriteLine("(S) to Subtract")
    Console.WriteLine("(M) to Multiply")
    Console.WriteLine("(D) to Divide")
    Console.WriteLine("(Q) to Quit")

    selection = Console.ReadLine

    If selection.ToUpper = "Q" Then
        Console.WriteLine("Exiting...")
        Thread.Sleep(2000)
        Environment.Exit(0)
    ElseIf selection.ToUpper = "A" Then
        CollectNumbers("add")
    ElseIf selection.ToUpper() = "S" Then
        CollectNumbers("subtract")
    ElseIf selection.ToUpper() = "M" Then
        CollectNumbers("multiply")
    ElseIf selection.ToUpper() = "D" Then
        CollectNumbers("divide")
    Else
        Console.WriteLine("Please choose a valid option from the list...")
        Thread.Sleep(2000)
        Menu()
    End If

End Sub

Sub CollectNumbers(operation As String)

    Dim num1 As Integer
    Dim num2 As Integer

    Console.WriteLine("Please enter the first number...")
    num1 = CInt(Console.ReadLine)
    Console.WriteLine("Please enter the second number...")
    num2 = CInt(Console.ReadLine)

    If operation = "add" Then
        Console.WriteLine(Add(num1, num2))
    ElseIf operation = "subtract" Then
        Console.WriteLine(Subtract(num1, num2))
    ElseIf operation = "divide" Then
        Console.WriteLine(Divide(num1, num2))
    ElseIf operation = "multiply" Then
        Console.WriteLine(Multiply(num1, num2))
    End If

    Console.ReadLine()
    Menu()

End Sub

Function Add(a As Integer, b As Integer) As Double

    Return a + b

End Function

Function Subtract(a As Integer, b As Integer) As Double

    Return a - b

End Function

Function Multiply(a As Integer, b As Integer) As Double

    Return a * b

End Function

Function Divide(a As Integer, b As Integer) As Double

    Return a / b

End Function

End Module


texts:
I've finally got a solution for a "weekly streak" bucketing system I've been working on but unfortunately it's resulted in a very large switch statement.

I'm running through a handful of dates and determining by a range of seconds (the length of a week) which bucket that date belongs to.

It's obvious to me that this could be refactored in a programmatic way because of the amount of repetition but I'm not sure where to start. Dictionary? Some kind of sorting algorithm? Recursion?

open func weeklyStreakCount(weeklyGoal target: Int) -> Int {
    let endDate = Date()
    let startDate = endDate.startOfWeek!
    let startDateInterval = Double(startDate.timeIntervalSinceNow)

    var workoutsPerWeek = [Int: Int]()
    let userWorkouts: [UserWorkoutEntity] = self.userWorkouts(completed: true)

    var numberOfGoodBuckets = 0

    for i in 0...100 {
        workoutsPerWeek.updateValue(0, forKey: i)
    }

    // calculate the time from now to seconds in a week and round to the nearest hundreths to create a bucket for that week
    for userWorkout in userWorkouts {
        let workoutTimeInterval = Double((userWorkout.completionDate?.timeIntervalSinceNow)!)
        let rawBucket = (startDateInterval - workoutTimeInterval) / numberOfSecondsInAWeek

        let bucket = Int(rawBucket * 1000)
        let abbrNumberOfSecondsInAWeek = 604

        switch bucket {
        case 0 ... abbrNumberOfSecondsInAWeek:
            workoutsPerWeek[0]! += 1
        case abbrNumberOfSecondsInAWeek ... (abbrNumberOfSecondsInAWeek * 2):
            workoutsPerWeek[1]! += 1
        case abbrNumberOfSecondsInAWeek * 2 ... (abbrNumberOfSecondsInAWeek * 3):
            workoutsPerWeek[2]! += 1
        case abbrNumberOfSecondsInAWeek * 3 ... (abbrNumberOfSecondsInAWeek * 4):
            workoutsPerWeek[3]! += 1
        case abbrNumberOfSecondsInAWeek * 4 ... (abbrNumberOfSecondsInAWeek * 5):
            workoutsPerWeek[4]! += 1
        case abbrNumberOfSecondsInAWeek * 5 ... (abbrNumberOfSecondsInAWeek * 6):
            workoutsPerWeek[5]! += 1
        case abbrNumberOfSecondsInAWeek * 6 ... (abbrNumberOfSecondsInAWeek * 7):
            workoutsPerWeek[6]! += 1
        case abbrNumberOfSecondsInAWeek * 7 ... (abbrNumberOfSecondsInAWeek * 8):
            workoutsPerWeek[7]! += 1
        case abbrNumberOfSecondsInAWeek * 8 ... (abbrNumberOfSecondsInAWeek * 9):
            workoutsPerWeek[8]! += 1
        case abbrNumberOfSecondsInAWeek * 9 ... (abbrNumberOfSecondsInAWeek * 10):
            workoutsPerWeek[9]! += 1
        default:
            break
        }
    }

    // Run through each bucket and see how many times the user hit their goal
    for i in 0...10 {
        if(workoutsPerWeek[i]! > target) {
            numberOfGoodBuckets += 1
        } else {
            break
        }
    }
    return numberOfGoodBuckets
}


texts: Simple todo list VanillaJS - repository pattern

texts:
I'm new in JavaScript, so I was looking for some reviews and advice for better code quality.

import Todo from './Todo.js';

export default class Repository {
  constructor(todos = []) {
    this.todos = todos;
    this.storage = localStorage;
  }

  addTodo(todo, save=true) {
    this.todos = [...this.todos.filter(item => item.uuid !== todo.uuid), todo];
    if (save) {
      this.saveTodos();
    }
  }

  removeTodo(todo) {
    this.todos = [...this.todos.filter(item => item.uuid !== todo.uuid)];
    this.saveTodos();
  }

  saveTodos() {
    this.storage.setItem('todos', JSON.stringify(this.todos));
  }

  loadTodos() {
    const storageTodos = JSON.parse(this.storage.getItem('todos'));
    if (storageTodos !== null) {
      storageTodos.map(todo => this.addTodo(Object.assign(new Todo(), todo)), false);
    }

    return this.todos;
  }
}

https://github.com/adbo/todo_list


texts: Is this code for getting the dependency tree of a file correct?

texts:
function dep_tree(graph,node,prev_deps){
    return uniq(flatten(graph[node].map(function(child_node){
        if (contains(prev_deps,child_node))
            throw "Circular reference between "+child_node+" and "+node;
        return dep_tree(graph,child_node,prev_deps ? prev_deps.concat(node) : [node])
    })).concat(node));
};

graph is an object such as {a:[],b:["a"],c:[],d:["b","c"]}, that links a file, ex: "d" to it's dependencies "b" "c".
file is the the node to search.
prev_deps is internal, to keep track of visited nodes

The function returns the full dependency tree of that node. For example, dep_tree(that_obj_above,"d") = ["b","c","a"]. Is this code correct, overall? Is it correctly checking for circular dependencies? Is there a name for what I'm doing?


texts: Reading, processing and counting an array setting limits

texts:
Last weekend my teacher asked me to create code to solve a problem:

  Giving a dynamic array, we want to pass the array elements from a file. The first number in the file N gives us the array length. They follow N numbers, the actual elements of the array.

    Three brothers are going to work in the shop of their father for a time. The shop is doing well and every day generates profit which the three brothers may provide. The brothers agreed that they would divide the total time in three successive parts, not necessarily equal duration, and that each one will be working in the shop during one of these parts and collects the corresponding profit on his behalf. But they want to make a deal fairly, so that one received from three more profit someone else. Specifically, they want to minimize the profit the most favored of the three will receive.

  Now assume that we have the following array elements:

5 6 1 4 9 3 1 2

  The procedure we should make appears in the following diagram:

  We want every time to keep the lowest value of weight and in the end to generate a result.

I created the code and it works for all inputs. Is there any way to reduce the complexity from \$\mathcal{O}(n^3)\$ to  \$\mathcal{O}(N)\$ if we can keep in mind that this isn't tidied up and probably needs to be.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int sum_array(int* array, int cnt)
{
    int res = 0;
    int i;
    for ( i = 0; i < cnt ; ++i)
        res += array[i];
    return res;
}

int main()
{
    FILE* input = fopen("share.in","r");

    int N = 0;
    fscanf(input,"%d",&N);

    int *array = (int*)malloc(N * sizeof(int));

    for (int i = 0; i < N; i++)
        fscanf(input,"%d",&array[i]);

    fclose(input);

    int Min = 0;
    int bestA = 0, bestB = 0, bestMin = INT_MAX;
    int A, B;
    int i;
    for ( A = 0; A < N - 2; ++A)
    {
        for ( B = A + 1; B < N - 1; ++B)
        {
            int ProfitA = sum_array(array, A + 1);
            int ProfitB = sum_array(array + A + 1, B - A );
            int ProfitC = sum_array(array + B + 1, N - 1 - B );

            //here the values are "current" - valid
            Min = (ProfitA > ProfitB) ? ProfitA : ProfitB;
            Min = (ProfitC > Min) ? ProfitC : Min;

            if( Min < bestMin )
                bestA = A, bestB = B, bestMin = Min;

        }
    }
    printf("%d\n", bestMin);
    free(array);
    return 0;
}


texts:
I have made a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.

#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <array>
#include <map>
#include <limits>

namespace
{
    enum Winner { Tie, Player, Computer, WinnerCount };
    enum Items { Rock, Paper, Scissors, ItemsCount };

    template<typename T, std::size_t N>
    using Matrix = std::array<std::array<T, N>, N>;
}

std::string ask_guess(const std::array<std::string, Items::ItemsCount>& data)
{
    std::string result;
    auto comp = [&result](const std::string& str){ return str == result;};
    bool is_good = false;

    while (!is_good)
    {
        std::cout << "Enter your choice, rock, paper, or scissors: ";
        std::getline(std::cin, result);

        if (std::cin.fail() || std::none_of(data.begin(), data.end(), comp))
        {
            std::cout << "Not valid input.\n";
            if (!result.empty()) result.clear();
            is_good = false;
        }
        else
        {
            is_good = true;
        }

        std::cin.clear();
        std::cin.ignore(std::cin.rdbuf()->in_avail());
    };

    return result;
}

bool play_again()
{
    char result;
    bool is_good = false;

    while (!is_good)
    {
        std::cout << "Do you want to play again? [y/n]: ";
        std::cin >> result;
        result = std::toupper(result);

        if (std::cin.fail() || (result != 'Y' && result != 'N'))
        {
            std::cout << "Not valid input.\n";;
            is_good = false;
        }
        else
        {
            is_good = true;
        }

        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    };

    return result == 'Y';
}

int main()
{
    // Set up game
    const Matrix<Winner, Winner::WinnerCount> table
    {
        {  // Rock      Paper      Scissors
            { Tie,      Computer,  Player   }, // Rock
            { Player,   Tie,       Computer }, // Paper
            { Computer, Player,    Tie      }, // Scissors
        }
    };

    const std::array<std::string, Items::ItemsCount> data
    {
        "rock",
        "paper",
        "scissors"
    };

    std::map<std::string, Items> bindingItems
    {
       { data[Items::Rock],      Items::Rock     },
       { data[Items::Paper],     Items::Paper    },
       { data[Items::Scissors],  Items::Scissors },
    };

    std::map<Winner, std::string> winnerResult
    {
       { Winner::Tie,        "It's a tie!\n\n"  },
       { Winner::Player,     "You win!\n\n"     },
       { Winner::Computer,   "You lose!\n\n"    },
    };

    std::mt19937 engine{ std::random_device()() };
    auto dist = std::uniform_int_distribution<>(0, Items::ItemsCount - 1);

    // Game loop
    do
    {
        std::cout << "\n\n\tRock Paper Scissors Game\n\n";

        const auto userChoice = ask_guess(data);
        const Items player = bindingItems[userChoice];

        const Items computer = static_cast<Items>(dist(engine));
        const auto computerChoice = data[computer];

        std::cout << "\n\nYou entered: " << userChoice << '\n';
        std::cout << "Computer chose: " << computerChoice << '\n';

        std::cout << winnerResult[table[player][computer]];
    }
    while(play_again());
}


texts: Improvements to simple Hangman Game in Python

texts:
I created this hangman game today as my first stand alone project. It is a quite basic and simplified approach. How could I improve the game to make it more interesting?
    import random
    words = ["abductions", "abridgment", "admixtures"
    ,"backfields", "blueprints", "chivalrous", "complexity", "cyberpunks", "desolating",
    "duplicator","earthlings",
    "fluoridate","flustering","fornicates","godfathers","humanizers","ideographs","journalism",
    "languished","logarithms","mendacious","neighborly","outlandish","palindrome","philanders"
    ,"proclaimed","randomizes","shrinkable","sublimated",
     "truckloads","upholstery","vanquished","vulcanizes","wanderlust","womanizers" ]

      i = random.randint(0, len(words) - 1)

      word = words[i]
      guesses = "_"*len(word)
      print(guesses)
      lives = 0
      while lives < 5:
         character_check = input("")
           if character_check in word and character_check != word:
               a = word.index(character_check)
               guesses = guesses[:a] + word[a] + guesses[a+1:]
               print(guesses)
           if guesses == word or character_check == word:
               print("Winner!")
               break
           elif character_check not in word:
               print(lives)
               lives += 1
    if lives == 5:
      print("You lose! It was {}".format(word))


texts:
My answer to Project Euler problem 3 (largest prime factor of 600851475143) is below.
Please suggest improvements, style changes, indentation, commenting, naming of "objects", ...
(defun factors (n)
    "return a list with prime factors of n"
    (let ((result))
        (loop while (zerop (rem n 2))           ; do 2
              do (loop while (zerop (rem n 2))
                       do (setf n (/ n 2))
                       do (setf result (cons 2 result))))
        (loop for i from 3 by 2                 ; do 3, 5, 7, 9, ...
              while (>= n (* i i))              ; until square root of what's left of n
              do (loop while (zerop (rem n i))
                       do (setf n (/ n i))
                       do (setf result (cons i result))))
        (if (= n 1) result (cons n result))))   ; if n is not 1 it is also a factor

Questions:

Is the (let ((result)) #| ... (setf result ...) ... |# result) construction acceptable?
I like the result as it is, in reverse; but, other than (reverse result) is there a way to collect factors into result? My attempts with collect i (or collect i into result) would not compile.


texts: Finding the 20th percentile pixel of an image using a histogram instead of std::sort

texts:
I have a 2-dimensional matrix (an image) in which I need to find the 20th percentile value.  My first attempt was to sort the values and then index using std::floor(0.2*(srcSor.size())/100).

My code was originally straightforward like this:

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

int main(int argc, char* argv[])
{
   //Read the image .jpeg
   cv::Mat src=cv::imread(argv[1], CV_8UC1);
   std::vector<double> srcSor = src.reshape(0, 1);
   std::sort (srcSor.begin(), srcSor.end(), std::greater<double>());
   float A = srcSor[std::floor(0.2*(srcSor.size())/100)];
   //Then later I use A value..
   .
   .

   return 0;
}

I found that std::sort took a long time to sort a vector of 1.3m unsigned values.
So now I'm using an histogram to do the same thing; this takes less time to find that value of that certain index. The idea comes from the fact that the values of the matrix are unsigned int in the range 0-255:

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <iostream>

int main(int argc, char* argv[])
{
   //Read the image .jpeg
   cv::Mat src=cv::imread(argv[1], CV_8UC1);

   std::vector<unsigned> histo(256,0.0);
   for(unsigned j=0;j<src.rows;j++)
      for(unsigned i=0;i<src.cols;i++)
          histo[(int)src.at<uchar>(j,i)]++;

   std::vector<unsigned> sumHH(256,0.0);
   sumHH[255]=histo[255];
   for(unsigned i=254;i>=1;i--)
        sumHH[i]=sumHH[i+1]+histo[i];

   int A=0;
   int indx=std::floor(0.2*(src.rows*src.cols)/100);
   for(unsigned i=1;i<255;i++)
     if(indx<sumHH[255-i])
     {
        A=255-i;
        break;
     }
   //Then later I use A value..
   .
   .

   return 0;
}

But I think that my code is not really readable, can anyone suggest a better way to write my code and/or better optimized?


texts: Create own implementation of vector which has moving operations and push_back for rvalue

texts:
template<typename T>
class Vector
{
private:
    size_t size;
    size_t capacity;
    T* buffer;
public:
    Vector(size_t s) {
        size = 0;
        capacity = s;
        buffer = new T[capacity];
    }
    //Move constructor
    Vector(Vector&& rhs): size(rhs.size),
                          capacity(rhs.capacity),
                          buffer(tmp.buffer)
    {
        rhs.buffer = nullptr;
    }
    T& operator=(Vector&& tmp) {
        size = tmp.size;
        capacity = tmp.capacity;
        buffer = std::move(tmp.buffer);
        return *this;
    }
    void push_back(const T& v) {
        if (size >= capacity)
            reserve(capacity + 5);
        buffer[size++] = v;
    }
    void push_back(T&& v) {
        if (size >= capacity)
            reserve(capacity + 5);
        buffer[size++] = v;
    }

Have I implemented all move operations in my class Vector?
Is it correct implementation of method push_back for rvalue ?