texts: Building a tree structure from pairs of parent-child to retrieve all ancestors of a leaf

texts:
I am trying to build a tree similar to this one :

      1
     / \
    2   3
   /|\
  4 5 6
 /
7

With that tree, I must be able to get all ancestors for each leaf.

In this example, this would be :

7 -> [4, 2, 1]
6 -> [2, 1]
5 -> [2, 1]
3 -> [1]

To build that tree, I can only use an unknown number of pairs of parent-child, which are added at runtime, one at a time.

Each time a new pair arrives, I have to update the tree.

For example, the tree is empty at the beginning.

Then I am given the pair 2, 4
Resulting tree :

  2
 /
4

Then I am given the pair 1, 3
Resulting tree :

  2   1
 /     \
4       3

Then I am given the pair 2, 5
Resulting tree :

  2   1
 /|    \
4 5     3

Then I am given the pair 1, 2
Resulting tree :

    1
   / \
  2   3
 /|
4 5

You get the idea.

Here is my Node class :

public class Node<T> {
    private T data;
    private Node<T> parent;
    private Map<T, Node<T>> children;

    public Node(T data, Node<T> node) {
        this.data = data;
        this.parent = node;
    }

    public Node(T data) {
        this.data = data;
    }

    public boolean hasChildren() {
        if (this.children != null) {
            return this.children.size() > 0;
        }
        return false;
    }

    public void addNode(Map<Long, Node<T>> tree, Node<T> node) {
        tree.put((Long) node.data, node);
        Node<T> parent = tree.get(node.parent.data);
        if (parent != null) {
            if (parent.children != null {
                parent.children.put(node.data, node);
            } else {
                parent.children = new HashMap<T, Node<T>>();
                parent.children.put(node.data, node);
            }
        }
    }

    public Map<Long, Node<T>> getLeaves(Map<Long, Node<T>> tree) {
        Map<Long, Node<T>> leaves = new HashMap<Long, Node<T>>();
        for (Entry<Long, Node<T>> node : tree.entrySet()) {
            if (!node.getValue().hasChildren()) {
                leaves.put(node.getKey(), node.getValue());
            }
        }
        return leaves;
    }

    public Set<Node<T>> getAncestors(Node<T> leaf) {
        Set<Node<T>> ancestors = new HashSet<Node<T>>();

        if (leaf.parent != null) {
            getAncestors(leaf.parent, ancestors);
        }
        return ancestors;
    }

    private void getAncestors(Node<T> leaf, Set<Node<T>> listOfAncestors) {
        if (leaf.parent != null) {
            listOfAncestors.add(leaf.parent);
        }
    }

    public Map<Long, Set<Long>> transformToMap(Map<Long, Node<T>> tree) {
        Map<Long, Node<T>> leaves = getLeaves(tree);
        Map<Long, Set<Long>> hierarchy = new HashMap<Long, Set<Long>>();

        for (Entry<Long, Node<T>> leaf : leaves.entrySet()) {
            Set<Node<T>> ancestors = new HashSet<Node<T>>();
            Set<Long> ancestorsId = new HashSet<Long>();
            ancestors.addAll(getAncestors(leaf.getValue()));
            for (Node<T> node : ancestors) {
                ancestorsId.add((Long) node.data);
            }
            hierarchy.put((Long) leaf.getKey(), ancestorsId);
        }
        return hierarchy;
    }
}

Can it be improved ?


texts: How can I make my solution for Chef and Digits run faster?

texts:
Problem Statement

  Given \$n\$ digits and \$m\$ indices \$x\$ from \$1. \ldots,n\$, calculate the
  difference \$b_y = a_x - a_y\$ for all indices \$y \; (y < x)\$. Then, calculate \$B1\$,
  the sum of all \$b_y\$ which are greater than \$0\$ and \$B2\$,
  the sum of all \$b_y\$ which are less than \$0\$. The answer for this step is \$B1 - B2\$.

  Input

  The first line contains two integers \$n, m\$ denoting the number of
  digits and number of steps. The second line contains \$n\$ digits (without
  spaces) \$a_1, a_2, ..., a_n\$. Each of next \$m\$ lines contains single integer
  \$x\$ denoting the index for current step.
  (ADIGIT: Chef and Digits from CodeChef)

My Issue

I've tried quite hard to optimize the following solution, but online judge always shows Time Limit Exceeded.

My Question

Is it possible to optimize this code further to bring time down less than 1 second, or should I change my approach or perhaps shift to C?

import sys
final=[]
z,y=[int(x) for x in sys.stdin.readline().split()]
stra=sys.stdin.readline()
for i in xrange(y):
    b1=b2=0
    curr=int(input())-1
    for x in stra[:curr]:
        mu=int(stra[curr])-int(x)
        if(mu>0):
            b1+=mu
        else:
            b2+=mu
    final.append(str(b1-b2))
print("\n".join(final))


texts: Is there better alternative to making an optional set of elements from iterable in java?

texts:
I'm feeling uneasy with this service method that I wrote:

    @Override
    public Optional<Set<TenantDTO>> getAllTenantsOfUsers(Set<Long> usersIds) {

        return Optional.ofNullable(usersIds)
                .map((ids) -> tenantRepository.findAll(QTenant.tenant.users.any().id.in(usersIds)))
                .map((it) -> StreamSupport.stream(it.spliterator(), false))
                .map((strm) -> strm.map((tenant) -> tenantMapper.toDto(tenant)).collect(Collectors.toSet()));

    }

My tenantRepository.findAll returns an iterable of Tenant entity

Is this the better approach to get all performance, with good code?


texts: Generate a Json from Strings using Jackson library

texts:
I am pretty new to Java and I got a requirement of converting Strings to a json structure. My below codes works fine but I have to create multiple objects and my code looks bit ugly. I want to know the better approach.

I want the below Json Structure from three Strings SourceApplication, messagType and payload

Required Json Structure

{
    "request": {
        "header": {
            "sourceApplication": "SomeString"
            "messageType": "SomeString"
        },
        "body": {
            "payload": "SomeString"
        }
    }
}

Below is my code.

POJO Class (For mapping)

package com.test.transformer;

import java.io.Serializable;

public class JsonMapper implements Serializable {

    private Request request;

    public Request getRequest ()
    {
        return request;
    }

    public void setRequest (Request request)
    {
        this.request = request;
    }

    public static class Request implements Serializable{

        private Body body;

        private Header header;

        public Body getBody ()
        {
            return body;
        }

        public void setBody (Body body)
        {
            this.body = body;
        }

        public Header getHeader ()
        {
            return header;
        }

        public void setHeader (Header header)
        {
            this.header = header;
        }

    }

    public static class Header implements Serializable{

        private String sourceApplication;
        private String messageType;

        public String getSourceApplication ()
        {
            return sourceApplication;
        }

        public void setSourceApplication (String sourceApplication)
        {
            this.sourceApplication = sourceApplication;
        }

        public String getMessageType ()
        {
            return messageType;
        }

        public void setMessageType (String messageType)
        {
            this.messageType = messageType;
        }

    }

    public static class Body implements Serializable{

        private String payload;

        public String getPayload ()
        {
            return payload;
        }

        public void setPayload (String payload)
        {
            this.payload = payload;
        }
    }

}

My Main Class

package com.test.transformer;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

public class JsonTest {

    public static  void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        String srcApp = "TestSrc";
        String msgType = "msgtype";
        String payload = "mainMsg";

        JsonMapper.Header h = new JsonMapper.Header();
        JsonMapper.Body b = new JsonMapper.Body();
        JsonMapper.Request r = new JsonMapper.Request();

        h.setSourceApplication(srcApp);
        h.setMessageType(msgType);
        b.setPayload(payload);

        r.setHeader(h);
        r.setBody(b);

        JsonMapper j = new JsonMapper();

        j.setRequest(r);

        String jsonInString = null;
        try {
            jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(j);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(jsonInString);
    }
}


texts:
I did this small project where there are six one-liner anonymous methods that can swap case of a given string of any length. For example "heLLo, woRLd" ==> "HEllO, WOrlD". I used this string as the example to demonstrate how each of the function works. This string "heLLo, woRLd" can simply be replaced with Console.ReadLine() to get user anticipated inputs. I understand one-liners are not readable and maybe not considered good practice, and used variable names are not proper as well. This whole project was for fun. I believe that way I can learn more. My expectation is that someone can tell me if there are more ways to do this case-swapping (of course, has to be one-liner)?. I think I used 3 (kinda) algorithms to do the swapping. Moreover, all of the one-liners are void functions and all the succeeding functions are shorter than the preceding ones.

using System;
using System.Linq;

class x
{
    static void Main(string[] args)
    {
        // one-liner string swapcase
        (new Action<string>(delegate (string x) { foreach (char i in x) { char b = i; b^= char.IsLetter(b) ? (char)32 : (char)0; Console.Write(b); } }))("heLLo, woRLd");

        Console.WriteLine();

        //one-liner string swapcase2
        (new Action<string>(delegate (string x) { foreach (char i in x) { Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)); } }))("heLLo, woRLd");

        Console.WriteLine();

        // one-liner string swapcase3
        ((Action<string>)(delegate (string x) { foreach (char i in x) { Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)); } }))("heLLo, woRLd");

        Console.WriteLine();

        //one-liner string swapcase4
        ((Action<string>)((x) => { foreach (char i in x) { Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)); } }))("heLLo, woRLd");

        Console.WriteLine();

        //one-liner string swapcase5
        "heLLo, woRLd".ToList().ForEach(i => Console.Write(char.IsUpper(i) ? char.ToLower(i) : char.ToUpper(i)));

        Console.WriteLine();
        //one-liner string swapcase6
        "heLLo, woRLd".ToList().ForEach(i => Console.Write(i^= char.IsLetter(i) ? (char)(1 << 5) : (char)0));
        Console.ReadLine();
    }
}


texts:
I implemented the golden section search algorithm recursively in Lisp. My code is:

(defconstant phi 0.618033988749895D0)

(defun linemin (f x1 x2 &key (xi1 (- x2 (* (- x2 x1) phi)))
                             (xi2 (+ x1 (* (- x2 x1) phi)))
                             (tol 0.001))
   (if (> tol (- xi2 xi1))
      (/ (+ xi1 xi2) 2)
      (if (> (funcall f x1) (funcall f x2))
         (linemin f xi1 x2 :tol tol :xi1 xi2)
         (linemin f x1 xi2 :tol tol :xi2 xi1))))

I sought to make this tail-recursive. Does Lisp provide a way of ascertaining whether the function was optimized and turned into a loop at compile time? Btw I'm using Lispworks.

Any other input is appreciated, of course.


texts: Splitting a list of numbers into multiple lists

texts:
I need split the list I get from the select into multiple list so I can use Parallel.For() to generate the next query in different threads.

I create the main list
Create the sub list
Keep filling sub list until reach max capacity.
Add sublist to main list

Create new sub list

When finish the loop save the last sublist

This works but I bet there is an easy / clean way to do this, I can change the db if needed.

List<List<long>> result = new List<List<long>>();
using (var conn = new NpgsqlConnection(strConnection))
{
    conn.Open();
    using (var cmd = new NpgsqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandText = "SELECT route_source_id " +
                          "FROM route_sources " +
                          "WHERE has_route IS NULL " +
                          "LIMIT 1000; ";

        using (var reader = cmd.ExecuteReader())
        {
            const long list_size = 100;

            long row_id = 0;
            List<long> route_list = new List<long>();

            while (reader.Read())
            {
               if (row_id++ > list_size) // Add the sublist to the result
               {
                   result.Add(route_list);
                   row_id = 0;
               }

               if (row_id == 0)  // Create new sublist
               {
                  route_list = new List<long>();
               }

               if (!reader.IsDBNull(0)) // fill the sublist
               {
                    route_list.Add(reader.GetInt64(0));
               }
            }

            if (route_list.Count > 0 ) // add the last sublist
            {
               result.Add(route_list);
            }
        }
   }
 }
 return result;

EDIT: aditional part of the process.

I have ticker to check the db for pending id to be process

// read 1000 rows split into 10 list, using above function
List<List<long>> route_pending = getRouteRange();
long total_rows = 0;

while (route_pending.Count > 0)
{
     foreach (List<long> range in route_pending)
     {
         total_rows += range.Count;
     }
     routeParallelGeneration(route_pending);
     route_pending = getRouteRange(); // keep reading next 1000 rows
}

And the parallel function, here I call my db storeproc with an array parameter. So max 10 connections with array of size 100. Here was where got issues with the excesive number of connections and decide split the data into 10 lists

public void routeParallelGeneration(List<List<long>> route_pending)
{
    Action<List<long>> forEachLoop = route_source_id => //Begin definition of forLoop
    {
        using (var conn = new NpgsqlConnection(strConnection))
        {
            conn.Open();
            using (var cmd = new NpgsqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandText = "SELECT avl_db.process_route(@route_source)";
                cmd.CommandType = CommandType.Text;

                NpgsqlParameter p = new NpgsqlParameter("@route_source", NpgsqlDbType.Array | NpgsqlDbType.Bigint);
                p.Value = route_source_id;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();
            }
        }
    };
    Parallel.ForEach(route_pending, forEachLoop);
}


texts: Optimal way to filter DataFrame by many arguments, without usage of multiple ifs and for loops

texts:
I am learning about survival analysis and I made some implementation in Python using lifelines and plotly. However depending on the number of arguments I would have to almost rewrite my function again because of all these ifs and fors. Could you suggest the way I could make it smarter?
Here is my code:

def classicLifelineFigure(frames, timeName = None, protocol = None, mutation = None, getter = getDfToSurvivalAnalysis):

    '''

    Function that returns lifeline figure object to be displayed on the website

    Parameters:

        frames --> dictionary with frames for features, mutations etc.
        timeName --> time on which we perform analysis
        protocol --> name of protocol if present in analysis
        mutation --> name of mutation if present in analysis
        getter --> function to get separate dataframes for analysis from one big dataframe

    '''

    kmf = KaplanMeierFitter()
    fig = go.Figure()

    if timeName == None:
        return fig

    dfToAnalysis = getter(frames, timeName, protocol, mutation)
    dfToAnalysis['TIME'] = dfToAnalysis['TIME'] / 365

    if protocol != None:

        if mutation != None:

            for prot in set(dfToAnalysis['PROTOCOL'].values):
                for mut in set(dfToAnalysis['MUTATION'].values):

                    tempDf = dfToAnalysis[(dfToAnalysis['PROTOCOL'] == prot) & (dfToAnalysis['MUTATION'] == mut)]
                    results = kmf.fit(tempDf['TIME'], tempDf['EVENT'])
                    traceDf = results.survival_function_.copy()
                    fig.add_trace(go.Scatter(
                        x = traceDf.index,
                        y = traceDf.iloc[:,0],
                        mode = 'lines',
                        name = 'Protocol value = {}, mutation value = {}'.format(prot, mut)
                    ))

        if mutation == None:
            for prot in set(dfToAnalysis['PROTOCOL'].values):
                tempDf = dfToAnalysis[dfToAnalysis['PROTOCOL'] == prot]
                results = kmf.fit(tempDf['TIME'], tempDf['EVENT'])
                traceDf = results.survival_function_.copy()
                fig.add_trace(go.Scatter(
                    x = traceDf.index,
                    y = traceDf.iloc[:,0],
                    mode = 'lines',
                    name = 'Protocol value = {}'.format(prot)
                ))

    elif mutation != None:
        for mut in set(dfToAnalysis['MUTATION'].values):

            tempDf = dfToAnalysis[dfToAnalysis['MUTATION'] == mut]
            results = kmf.fit(tempDf['TIME'], tempDf['EVENT'])
            traceDf = results.survival_function_.copy()
            fig.add_trace(go.Scatter(
                x = traceDf.index,
                y = traceDf.iloc[:,0],
                mode = 'lines',
                name = 'Mutation value = {}'.format(mut)
            ))

    else:
        results = kmf.fit(dfToAnalysis['TIME'], dfToAnalysis['EVENT'])
        traceDf = results.survival_function_.copy()
        fig.add_trace(go.Scatter(
            x = traceDf.index,
            y = traceDf.iloc[:,0],
            mode = 'lines',
            name = 'Survival function'
        ))

    fig.update_layout(showlegend = True)

    return fig


texts: What is the correct way to alter ComboBox between two DataSources?

texts:
I am looking to alter one combobox between two DataSources depending on the button clicked.
Here are the 2 lists:
List<ComplaintModel> productNames = new List<ComplaintModel>();
List<ComplaintModel> specificProductNames = new List<ComplaintModel>();

This is the functions for both of the Data Sources:
public Complaints_Form()
{
    InitializeComponent();

    // When Form is loaded - load with this Data Source First
    loadProducts();

}

private void loadProducts()
{
    DataAccess db = new DataAccess();
    productNames = db.LoadProducts();

    product.DataSource = productNames;
    product.DisplayMember = "Product";
    product.SelectedIndex = 0;
}

// On button click - alter the Data Source
public void searchButton_Click(object sender, EventArgs e)
{
    // New datasource
    DataAccess db = new DataAccess();
    specificProductNames = db.FindOrderNumber(orderNumber.Text);

    product.DataSource = specificProductNames;
    product.DisplayMember = "Product";
    product.SelectedIndex = 0;
}

Question

Is this the correct way of altering between data-sources?

The reason I have this question - the form is actually fairly slow. Especially when I load or clear the textboxes and also clear the data-bindings.


texts:
I wrote a program that records how many times 2 fair dice need to be rolled to match the probabilities for each result that we should expect.

I think it works but I'm wondering if there's a more resource-friendly way to solve this problem.

import random

expected = [0.0, 0.0, 0.028, 0.056, 0.083,
         0.111, 0.139, 0.167, 0.139, 0.111,
         0.083, 0.056, 0.028]

results = [0.0] * 13  # store our empirical results here

emp_percent = [0.0] * 13  # results / by count

count = 0.0  # how many times have we rolled the dice?

while True:
    r = random.randrange(1,7) + random.randrange(1,7)  # roll our die
    count += 1
    results[r] += 1
    emp_percent = results[:]

    for i in range(len(emp_percent)):
        emp_percent[i] /= count
        emp_percent[i] = round(emp_percent[i], 3)

    if emp_percent == expected:
        break

print(count)
print(emp_percent)


texts:
I wrote a python model for the game "snake" that I'm not really satisfied with.

My intention was to separate the game logic from the drawing and input handling (which worked quite well) but I've got several points which I don't know how to solve better.

To use this model one needs to initialize it with callbacks that fire when the score increases and when the game is over. They pass the score as an integer. I don't like this solution because it feels a lot like C, passing around function pointers.
For the drawing the user needs to access the head, tail and food variables in the model. Should I write explicit getters for that? I prefixed everything the user shouldn't directly access with an underscore. How can I make this interface more clear?
One needs to call _move_snake(dx, dy) with the direction dx, dy the snake should move although the model already has a variable that holds the snake's direction. But I guess this way it's easier for testing?

import random

class SnakeModel(object):

    """
    Model for a snake-like game.
    """

    def __init__(self, width, height,
                 gameover_callback, atefood_callback):
        """
        Initializes the game

        gameover_callback and atefood_callback are callback functions. They
        are passed the current player score (length of the snake's tail) as an
        integer.
        """
        self.width = width
        self.height = height
        self._gameover = gameover_callback
        self._ateFood = atefood_callback
        self.reset()

    def reset(self):
        """
        Starts a new game.

        Sets the starting position, length and direction of the snake as well
        as the position of the first food item.
        """
        self._dir = (0, -1)

        # You can read head, tail and food directly for drawing
        self.head = (self.width / 2, self.height - 2)
        self.tail = [(self.width / 2, self.height - 1)]
        self.food = (self.width / 2, self.height / 3)

    def step(self):
        """
        Advances the game one step
        """
        # check for collisions
        if self.head in self.tail:
            self._gameover(len(self.tail))

        # eat food
        if self.head == self.food:
            self.tail.insert(0, self.head)
            self.food = self._new_food_location()
            self._ateFood(len(self.tail))

        # move snake
        self._move_snake(*self._dir)

    def set_snake_direction(self, dx, dy):
        """
        Sets the direction the snake will move on the next step
        """
        self._dir = (dx, dy)

    def _move_snake(self, dx, dy):
        """
        Moves the snake one step in the given direction.

        The snake can move through the game area's borders and comes out on the
        other side.
        """
        x, y = self.head
        newX = (x + dx) % self.width
        newY = (y + dy) % self.height
        self.head = (newX, newY)
        self.tail.insert(0, (x, y))
        self.tail.pop()

    def _new_food_location(self):
        """
        Returns a new possible food position which is not in the snake.
        """
        game_field = set([(x, y) for x in range(self.width)
                          for y in range(self.height)])
        possible = game_field - set(self.tail) - set([self.head])
        new_position = random.choice(list(possible))
        return new_position


texts: Non-re-indexing List with defragmentation

texts:
I'm currently coding something where I have Objects that take on an ID, and are stored in a List. For easy retrieval, the ID of the object is it's index in the list. However, that means that the object cannot be removed from the list without everything going to hell, since the list will be re-indexed and thus I won't be able to retrieve the right object from the list by knowing its ID anymore.

I also did not want to use a Map, since that just looks ugly and makes a big part of my code look more complicated than it should.

Thus, I tried to simply use a list, but modify it in order to be able to get an index that won't change as long as the object is alive.

@SuppressWarnings("serial")
public class SafeIndexList<E> extends ArrayList<E> {

    Stack<Integer> safeIndexes = new Stack<Integer>();

    @Override
    public E remove(int index){
        if(this.size()-1 == index) return super.remove(index);
        else {
            E e = this.get(index);
            this.set(index, null);
            safeIndexes.push(index);
            return e;
        }
    }

    public int getSafeIndex(){
        return safeIndexes.size() > 0 ? safeIndexes.pop() : size();
    }

}

Is this "good" or just complete, sorry for the wording, bullshit?


texts: BDD in PHP, Testing search in Wikipedia with Behat and Mink (Selenium2 Driver)

texts:
I am trying to learn BDD in PHP with Behat and Mink and I am using Selenium2 driver for the same.

The scenario is given on this page and is as follows:

Feature: Search
    In order to see a word definition
    As a website user
    I need to be able to search for a word

    Scenario: Searching for a page that does exist
        Given I am on "/wiki/Main_Page"
        When I fill in "search" with "Behavior Driven Development"
        And I press "searchButton"
        Then I should see "Behavior-driven development"

    Scenario: Searching for a page that does NOT exist
        Given I am on "/wiki/Main_Page"
        When I fill in "search" with "Glory Driven Development"
        And I press "searchButton"
        Then I should see "Search results"

The file behat.yml is as follows:

default:
    extensions:
        Behat\MinkExtension:
            base_url: http://en.wikipedia.org/
            goutte: ~
            selenium2: ~

I have written the below code for FeatureContext.php that I am sure needs improvements. Can anyone suggest me the points for the same?

<?php

use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;

/**
* Defines application features from the specific context.
*/
class FeatureContext implements Context, SnippetAcceptingContext
{
    /**
    * Initializes context.
    *
    * Every scenario gets its own context instance.
    * You can also pass arbitrary arguments to the
    * context constructor through behat.yml.
    */
    public function __construct()
    {

        $this->driver = new \Behat\Mink\Driver\Selenium2Driver('firefox');
        $this->session = new \Behat\Mink\Session($this->driver);
        $this->session->start();
    }

    /**
    * @Given I am on :url
    */
    public function iAmOn($url)
    {
        $this->session->visit('http://en.wikipedia.org'.$url);
    }

    /**
    * @When I fill in :field with :text
    */
    public function iFillInWith($field, $text)
    {
        $this
            ->session
            ->getPage()
            ->find('css', '[type=' . $field . ']')
            ->setValue($text);
    }

    /**
    * @When I press :button
    */
    public function iPress($button)
    {
        $this
            ->session
            ->getPage()
            ->find('css', '[id=' . $button . ']')
            ->press();
    }

    /**
    * @Then I should see :text
    */
    public function iShouldSee($text)
    {
        $title = $this
            ->session
            ->getPage()
            ->find('css', 'h1')
            ->getText();

        if ($title !== $text) {
            new Exception('Invalid page');
        }
    }

    /**
    * @AfterScenario
    */
    public function tearDown()
    {
        $this->session->stop();
    }
}


texts: JavaScript function for the get a specifed weekday n-weeks before / in the future

texts:
I'm currently working on a intranet application.

It shall have a GUI on which you can choose a weekday and a positive / negative integer. The integer stands for weeks.

So let's say someone chooses the Wednesday and (-7) then it shall display the date of the Wednesday seven weeks ago.

Tuesday and 3 => Tuesday in three weeks.

Here's the code which shall calculate the date:

    // Returns a Date Object which contains
    // the date before/in n-days and
    // before/in n-weeks.

    // -- Parameter ----------------------------
    // 1. String - The desired weekday as an
    //   abbreviation.
    //   Assign for ...
    //     Monday    : 'mo'
    //     Tuesday   : 'tu'
    //     Wednesday : 'we'
    //     Thursday  : 'th'
    //     Friday    : 'fr'
    //     Saturday  : 'sa'
    //     Sunday    : 'su'

    // 2. Number - Positive number => n-weeks in
    //   the future.
    //   Negative number => n-weeks before.

    // -- Return -------------------------------
    // (Date) Object

    function getDayBeforeIn(day, weeks) {
      var currentDate = new Date();
      var currentStamp = currentDate.getTime();
      var weekdays = {
        'mo': 1,
        'tu': 2,
        'we': 3,
        'th': 4,
        'fr': 5,
        'sa': 6,
        'su': 0
      }
      var milliSecondsDay = 24 * 60 * 60 * 1000;

      day   = day   || 'mo';
      weeks = weeks || 0;

      currentStamp += weeks * 7 * milliSecondsDay;
      currentStamp +=
        (weekdays[day] - currentDate.getDate()) *
         milliSecondsDay;

      return new Date(currentStamp);
    }

    // Returns the Day, Month, Year of an
    // JavaScript Date Object as as String
    // in the Date format DMY.

    // -- Parameter ----------------------------
    // 1. Date-Object
    // 2. String - Is used for separating
    // Day-Year and Month-Year.

    // -- Return -------------------------------
    // String

    function getDayMonthYearDate(dateObject, separator) {
      var day   = '0' + dateObject.getDate();
      var month = '0' + (dateObject.getMonth() + 1);
      var year  = dateObject.getFullYear();

      separator = separator || '.';

      return day.slice(-2) + separator +
             month.slice(-2) + separator + year;
    }

    // -- TEST -----------------
    for (var i = 0; i < 10; i++) {
      var result = getDayBeforeIn('th', i * (- 1));

      console.log(getDayMonthYearDate(result));
    }
    /* -- Results ---
        04.02.2016
        28.01.2016
        21.01.2016
        14.01.2016
        07.01.2016
        31.12.2015
        24.12.2015
        17.12.2015
        10.12.2015
        03.12.2015
    */

All suggestions and hints concerning improvements welcome.


texts: How to name a method that sets some values in a javabean?

texts:
Often I find myself setting various fields in a Javabean and then passing that Javabean to some method.

customerEntity.setName("Foo");
customerEntity.setAge(45);
customerEntity.setAddress(address);

em.merge(customerEntity);

Or

requestPayload.setCustomerId(2343);
requestPayload.setCustomerPreference("green");
//lots more
sendRequest(requestPayload)

Not liking so much of data-population cluttering, I'd move those to a separate method..

public void doSomeOperation(Customer customer)
    {
          em.merge(prepareCustomerEntity(customer));
    }

private Customer prepareCustomerEntity(Customer customer)
   { customer.setName("Foo");
    customer.setAge(45);
    customer.setAddress(address);
    return customer;
   }

What would be a good name for such a method ? Maybe something like prepareXXX() or populateXXX()? Naming it as prepareXXX() makes it sound like a void method.. populateXXX() sounds better? Or should I just name it as setCustomerValues(). But setXXX() name makes it sound like a typical Javabean setter, which this is not.


texts: PHP class architecture and dependency injection

texts:
Let me start off by saying I am not new to PHP or PDO, but very new to OO PHP, and have been struggling to get a firm idea of best practices in my head regarding dependency injection and structuring my classes and their methods.

The code I am providing will clearly be built on once I know I am doing things the correct way, so imagine more methods etc. using the same techniques I have used below, and what needs to be changed to make the whole package efficient and stable.

Whilst I am working on other PHP projects at work, the code below is not for or from any project, simply to help me learn before using OO in a real project. I also would normally do far more error checking, checking variables are set etc but have fiddled with this code so much, I haven't done this yet.

Here are the issues I see with it:

It seems that I am not taking advantage of the extra efficiency prepared statements bring when re-using the same statement but with different values. By doing this in a method like below, I would be preparing the statement every time, even if I just wanted to change the values.
I am not using a dependency injection container. Whilst it may not be necessary for small classes like these, I feel it would be better to use on in the long run.
I am worried I am on the track to creating tonnes of methods for every different type of query - see the findById and returnObjectById methods - they are structured very differently - one calling a query method in the Database class, the other running the query within the User class - I have no idea which is best. But also I feel I could end up creating a new page, realizing I need ANOTHER type of query, and then having to either write one in that file as a single instance (which would make me think why don't I do this for all), or create ANOTHER method in the User or Database class.
Are my methods within the correct classes - should the returnObjectById for example, be in the database class?

Note: Classes are auto loaded with spl_autoload_register in the config file, where DB constants are also set.

class_Database.php

    class Database
    {
    private $conn;

    public function __construct() {
        $this->openConnection();
    }

    public function getConnection()
    {
        $conn = $this->conn;
        return $conn;
    }

    public function openConnection() {
        try {
            $this->conn = new PDO('mysql:host=' . DB_SERVER . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo 'There was an error connecting to the database, Error: ' . $e->getMessage();
            die();
        }
    }

    public function standardQuery($sql, array $params)
    {
        $stmt = $this->conn->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}

class_User.php

 class User
    {
    public $id;
    public $first_name;
    public $last_name;
    public $username;
    public $password;
    public function __construct()
    {

    }
    public function findById(Database $db, $id)
    {
        $user = $db->standardQuery("SELECT * from users WHERE id = :id", array(':id' => $id));
        return $user;
    }
    public function returnObjectById(Database $db, $id)
    {
        $stmt = $db->getConnection()->prepare("SELECT * from users where id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_CLASS, "User");
    }
}

Essentially, answers to my points above would be great, but I'd like to know if I am in any way moving in the right direction, or if I should stop and start over with a different technique.


texts: Optimize nested loops for counting the total number of selections

texts:
The question is: To select 2 numbers out of n positive integer inputs (order matters), where the number that is placed anywhere before the second must be greater than the second by a given number m. Count the total number of selections.
An example answer would be, given the inputs 5 1 3 2 4 and m is 0, the total number of selections is 5 (51,53,52,54,32)
Another example answer would be, given the inputs 6 5 4 3 2 1 and m is 2, the total number of selections is 6 (63,62,61,52,51,41)
How do I improve my double for-loop method in terms of time?
using namespace std;

int main()
{
    int n, m, i, j, m = 0, sum = 0;
    cin >> n >> m;
    int *a=new int[n];
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    for(i=0;i<n-1;i++)
    {
        if (a[i] - m <= 0)  continue;
        int temp=a[i]-m;
        for(j=i+1;j<n;j++)
        if(a[j]<temp) sum++;
    }
    cout<<sum<<endl;
    return 0;
}
`


texts: Is my code fine in the areas of read and write?

texts:
What:

This is a code that when executed simply writes packet to certain file types. Packet is very simple and contains things like:

description, partCount, price...

Please:

Ignore the usage of namespace std; as this is for educational
purposes, mostly. It will most likely not be reproduced in a real
program.
Focus on reviewing the read and write portions as I would love
feedback on those portions.
I used some other things for simplicity, but in general I am mainly
looking for feedback on read/write portions of the code.

Intent:

I'm specifically looking for feedback on the read and write portions of the code. Could I get feedback on it as well as is it feasible as a piece of code and what can I improve on/etc.???

Main.cpp:

#include <iostream>
#include <fstream>
#include <vector>

#include "Packet.h"

using namespace std;

int main() {
    cout << "----------------------------------------------------" << endl;
    cout << "Input and Output Filing System" << endl;
    cout << "----------------------------------------------------" << endl;
    ifstream inFile;
    ofstream outFile;
    fstream bOutFile;
    vector<Packet> package;
    Packet one(0, "A packet of cheese.", 21.99, 4);
    package.push_back(one);
    Packet two(1, "A packet of super-cheese.", 31.99, 2);
    package.push_back(two);

    cout << "Starting to write packets to file..." << endl;

    outFile.open("Insert Your Destination of File Here.Txt");
    for (int i = 0; i < package.size(); ++i) {
        outFile << "{" << endl;
        outFile << package[i].getPartId() << "," << endl;
        outFile << package[i].getDescription() << "," << endl;
        outFile << package[i].getPartCount() << "," << endl;
        outFile << package[i].getPrice() << "," << endl;
        outFile << "}" << endl << endl;
    }
    outFile.close();

    cout << "Starting to read packets from file..." << endl;

    inFile.open("Insert Your Destination of File Here.Txt");
    string line;
    while (getline(inFile, line)) {
        if (line[0] != '{' && line[0] != '}') {
            cout << line.substr(0, line.size() - 1) << endl;
        }
    }
    inFile.close();

    cout << "Starting to write packets to binary..." << endl;

    bOutFile.open("Insert Your Destination of File Here.bin", ios::out | ios::binary);
    for (int i = 0; i < package.size(); ++i) {
        bOutFile.write((char*)&package[i], sizeof(package[i]));
    }
    bOutFile.close();

    system("pause");
}

Packet.h:

#pragma once
#include <string>

using namespace std;

class Packet {
public:
    Packet(int partId, string description, double price, int partCount) :
        partId(partId), description(description), price(price), partCount(partCount) {}
    int getPartId() const { return partId; }
    string getDescription() const { return description; }
    double getPrice() const { return price; }
    int getPartCount() const { return partCount; }

private:
    int partId;
    string description;
    double price;
    int partCount;
};


texts:
This is my first ever Python program so I would really like to know if it's any good (I mean if it is well writen), and if not then how to make it better.
I would also like to know if there is a way to get all the veriables in one line without a space between them.

This calculator is basicly this calculator which I wrote in C++ upgraded and writen in Python.

def calculate(num1, num2, act):
    if(act=='+'):
        total=num1+num2
    elif(act=='-'):
        total=num1-num2
    elif(act=='*'):
        total=num1*num2
    elif(act=='/'):
        total=num1/num2
    else:
        print("input not recognized")
    return total

def calc2():
    user_input=input("Enter a num1 act num2 (with a space between them): ")   #Gets the values
    var1, action, var2=user_input.split()     #assigns the values into the variables
    if(action=='/' and var2==0):      #checks for division by 0
        print("YOU CAN'T DIVIDE BY ZERO!!!")
    else:
        print(calculate(float(var1), float(var2), action))     #calls the 'calculating' function, recives and prints the total of act

def calc3():
    user_input=input("Enter a num1 act1 num2 act2 num3 (with a space between them): ")      #Gets the values
    var1, action1, var2, action2, var3=user_input.split()           #assigns the values into the variables
    if(action1=='/' and var2==0 or action2=='/' and var3==0):      #checks for division by 0
        print("YOU CAN'T DIVIDE BY ZERO!!!")
    elif((action2=='*' or action2=='/') and (action1=='+' or action2=='-')):    #checks if act2 should be done before act1 (order of operation)
        total=calculate(float(var2), float(var3), action2)     #calls the 'calculating' function, recives the total of act2
        print(calculate(float(var1), float(total), action1))     #calls the 'calculating' function, assigns the total of act2 as num2, recives and prints the total of act1
    else:                                                             #act1 is done before act2 (order of operation)
        total=calculate(float(var1), float(var2), action1)         #calls the 'calculating' function, recives the total of act1
        print(calculate(float(total), float(var3), action2))     #calls the 'calculating' function, assigns the total of act1 as num1, recives and prints the total of act2

def main():
    amount=float(input("How many numbers? (2-3 numbers) "))
    if(amount==2):
        calc2()
    elif(amount==3):
        calc3()
    else:
        print("I SAID TWO OR THREE NUMBERS")

main()           #starts program

Input/Output

  Input:2 + 3 * 4
  Output:14


texts: Rails model for aggregate data instead of a real table

texts:
I have a rails app with a Project model. Each project has usages which is numeric data.
I need to get all the usage for each month and year. I also need to get usage for specific months and years across multiple projects.
Instead of writing one large service file with raw SQL queries to handle this, I have decided to extract a lot of the code to a model which isn't based on any table, but instead gets the data by using certain SQL aggregation features.
This allows me to take (almost) full advantage of ActiveRecord in consumers to extend the default query to get specific fields (e.g. where the month is May or the project is project #15).
Here is the example of the code I wrote:
class MonthlyUsage < ActiveRecord::Base
  self.table_name = 'projects'

  default_scope do
    select(select_monthly_data_and_dates)
      .group('year', 'month', '"projects"."id"')
  end

  def self.select_monthly_data_and_dates
    <<~SQL.squish
      "projects"."id" AS "project_id",
      SUM("usages"."usage") AS "monthly_usage",
      date_part('year', "usages"."timestamp")::INT AS "year",
      date_part('month', "usages"."timestamp")::INT AS "month"
    SQL
  end
end

In reality there are a few joins and extra steps to this code which I'm omitting here since they aren't relevant.
Basically I'm of two minds on this. On the one hand I think it allows for powerful querying and fits the definition of a model, but on the other hand I think it might be too "hacky" and not really much clearer than just using a service file (e.g. setting the table name as 'projects' even though that's not really the real table name). That's why I'm asking for code review here, to get some opinions on whether this is good or bad, as well as how you would do it.


texts: Comparing multiple variables and assigning new values respectively

texts:
I know there is a more elegant way to write this.  The logic is solid and doing what I want it to, but I feel like when written like this, it is awfully cumbersome to have these many if statements essentially doing the same thing.

if (forward) {
    if (counter == listEnd) {
        counter = 0;
    }
    else {
        counter++;
    }

    if (nextCounter == listEnd) {
        nextCounter = 0;
    }
    else {
        nextCounter++;
    }

    if (prevCounter == listEnd) {
        prevCounter = 0;
    }
    else {
        prevCounter++;
    }
} // end if


texts:
What would be the best way to refactor following methods?

private string CalcualtePercentageDifference(string temp1, string temp2)
    {

        double number1 = ParseDouble(temp1);
        double number2 = ParseDouble(temp2);
        double percentageDifference = 0;

         if (number1 == 0 || number2 == 0)
         {
             return "0 %";
         }

        if ((number1 >= number2) && number1 > 0 && number2 > 0)
        {
            double tempNumber = number2*100/number1;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if ((number2 >= number1) && number1 > 0 && number2 > 0)
        {
            double tempNumber = number1*100/number2;
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if (number1 < 0 && number2 > 0)
        {
            double tempNumber = (number2 + Math.Abs(number1))/Math.Abs(number1);
            Math.Abs(percentageDifference = 100 - tempNumber);
        }

        if (number2 < 0 && number1 > 0)
        {
            double tempNumber = (number1 + Math.Abs(number2))/Math.Abs(number2);
            Math.Abs(percentageDifference = 100 - tempNumber);
        }
        if (number1 < 0 && number2 < 0)
        {
            number1 = Math.Abs(number1);
            number2 = Math.Abs(number2);

            if ((number1 >= number2))
            {
                double tempNumber = number2 * 100 / number1;
                Math.Abs(percentageDifference = 100 - tempNumber);
            }
            if ((number2 >= number1))
            {
                double tempNumber = number1 * 100 / number2;
                Math.Abs(percentageDifference = 100 - tempNumber);
            }
        }

        return Math.Round(percentageDifference) + " %";

    }

    private static double ParseDouble(object value, string valueName = "")
    {
        double outValue = double.NaN;

        try
        {
            outValue = Convert.ToDouble(value);
        }
        catch (FormatException e)
        {
            //We will get here when value contains NumberDecimalSeparator different from this in current culture
            //Convert now using suitable culture
            outValue = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ","
                       ? Convert.ToDouble(value, CultureInfo.InvariantCulture)
                       : Convert.ToDouble(value, new CultureInfo("pl-PL"));
        }
        catch (InvalidCastException)
        {
        }

        return outValue;
    }


texts:
Am attempting to recreate a common feature, where a user can type several items in to a textarea, separated by commas and newlines and then submit them, i.e. for multiple record entry.

The data does not come from a CSV file and is manually entered.

// data looks like this in the textarea:

Widget 1, 4, 10
Widget 2, 1.3, 10
Widget 3, 5.5, 15

Then submit the form:

$products = explode("\r\n", $_POST['productsTextarea']); // sanitize

$y = 0;
$productArray = array();

// explode and trim each product, assign values to an array
foreach($products as $product) :
    $product = array_map('trim', explode(',', $product));
    $productArray[$y]['name'] = $product [0];
    $productArray[$y]['cost'] = $product [1];
    $productArray[$y]['quantity'] = $product [2];
    $y++;
endforeach;

-

// desired output of $productArray
array(
    (int) 0 => array(
        'name' => 'Widget 1',
        'cost' => '4',
        'quantity' => '10',
    ),
    (int) 1 => array(
        'name' => 'Widget 2',
        'cost' => '1.3',
        'quantity' => '10',
    ),
    (int) 2 => array(
        'name' => 'Widget 3',
        'cost' => '5.5',
        'quantity' => '15',
    ),
)

I feel this isn't particularly extensible (i.e. the array keys are hard coded) and wonder how it would cope with a lot of items.

Name, Cost, Quantity, Colour, Location, Postcode // header row?
Widget 1, 4, 10, blue, Foo, Bar
Widget 2, 4, 10, red, Foo, Bar


texts:
I was asked this in an interview yesterday. I could add whatever methods, members and constructors I wanted but I couldn't change the signature of the provided toString and append methods.

I implemented something like this:

import java.util.ArrayList;
import java.util.List;

public class StringBuilder {

  private List<Character> characterBuffer;

  public StringBuilder() {
    characterBuffer = new ArrayList<Character>();
  }

  public void append(String anotherString) {
    if(anotherString != null) {
      char[] charArray = anotherString.toCharArray();
      for(int i=0;i<charArray.length; i++) {
        characterBuffer.add(charArray[i]);
      }
    }
  }

  public String toString() {
    char[] charArray = new char[characterBuffer.size()];
    for(int i=0; i<charArray.length; i++) {
      charArray[i] = characterBuffer.get(i);
    }
    return new String(charArray);
  }

}

When asked if there was another approach I might have taken, I suggested using a primitive char array buffer that can grow if there is an overflow. Not liking to leave things unfinished, I implemented this solution when I got home:

import java.util.Arrays;

public class StringBuilder {

  private char[] characterBuffer;
  private int curIndex;

  public StringBuilder() {
    characterBuffer = new char[5];
    curIndex = 0;
  }

  public void append(String anotherString) {
    if(anotherString != null) {
      char[] charArray = anotherString.toCharArray();
      int charArrayLength = charArray.length;
      if(overflow(charArrayLength)) {
        characterBuffer = Arrays.copyOf(characterBuffer, newLength(charArrayLength));
      }
      for(int i=0;i<charArray.length; i++) {
        characterBuffer[curIndex++] = charArray[i];
      }
    }
  }

  private int newLength(int arrayLength) {
    return (characterBuffer.length + arrayLength) + 10;
  }

  private boolean overflow(int arrayLength) {
    return (arrayLength + curIndex) > characterBuffer.length;
  }

  public String toString() {
    return new String(characterBuffer, 0, curIndex);
  }

}

I'd like both approaches reviewed.


texts:
I need to find a set of hours, starting from now, every 6 hours.

So if now is midnight, I want [ 0, 6, 12, 18 ].
If now is 15h (3pm), I want [ 15, 21, 3, 9 ]

For now I have brute-forced it:

var now = new Date();
var hours = [];
var h = now.getHours();
// add current hour (tomorrow)
hours.push(h);

// to add 6 hours
var inXh = function(toAdd) {
    var inh = h + toAdd;
    if (inh >= 24) { inh = inh - 24; }
    return inh;
};

// add in 6 hours
hours.push(inXh(6));
// add in 12 hours
hours.push(inXh(12));
// add in 18 hours
hours.push(inXh(18));

It's incredibly ugly and verbose, and I'm sure there is a much more clever way to do it, but right now I'm too tired to calculate modulos.


texts:
A Java service that connects to MongoDB in production, but opened connection count is too much. It affects on MongoDb performance, so I have come up with a solution that provides only one MongoClient instance so which will reduce the connections.
Here is my code, is it a good way to provide a singleton object from 3rd party library?
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

public class MongoClientFactory {

    private static volatile MongoClient instance = null;

    private MongoClientFactory() {}

    public static MongoClient getInstance(String connectionString) {
        if (instance == null) {
            synchronized(MongoClientFactory.class) {
                if (instance == null) {
                    instance = MongoClients.create(connectionString);
                }
            }
        }
        return instance;
    }
}


texts:
I have a method that I use nested foreach and the same variable call multiple times. I read a lot of optimizing code but I'm pretty sure I can do this with less code and best practices:

   public async Task<IEnumerable<IssueViewModel>> Get(IssueSelectModel model)

        {
            async Task<IEnumerable<IssueViewModel>> DoGet()

            {

                var issueList = await _bugTrackerRepository.Get(model);

                var userList = await _userService.Get(new UserSelectModel { RowsPerPage = 1000 });

                foreach (var item in issueList.IssueList)
                {

                    item.AssigneeName = userList.Items.FirstOrDefault(x => x.UserId == item.AssigneeId)?.UserName;

                    item.CreatedByName = userList.Items.FirstOrDefault(x => x.UserId == item.CreatedBy)?.UserName;

                    item.ModifiedByName = userList.Items.FirstOrDefault(x => x.UserId == item.ModifiedBy)?.UserName;

                    item.ClosedByName = userList.Items.FirstOrDefault(x => x.UserId == item.ClosedBy)?.UserName;

                    foreach(var comment in item.CommentList)
                    {
                        comment.CreatedByName = userList.Items.FirstOrDefault(x => x.UserId == comment.CreatedBy)?.UserName;

                        foreach(var tag in comment.TagList)
                        {
                            tag.UserByName = userList.Items.FirstOrDefault(x => x.UserId == tag.UserId)?.UserName;
                        }
                    }
                }
                return issueList.IssueList;

            }

            return await DoGet();

        }

Is it possible to use userList only one time?
Is there an alternative of multiple foreach statement?

Regards


texts: Variadic template with function argument

texts:
I am trying to develop an ECS registry. How would you improve this ? First disadvantage comes to my mind is using lambdas might be expensive, however I was not able to replicate functionality using F&& template arguments.

    engine->addEntity(1,
        Position{1, 1},
        Mesh{"thing.gltf"},
        PhysicsBody{10.0f}
    );

    engine->addEntity(2,
        Position{ 2, 2 },
        Mesh{ "other.gltf" },
        PhysicsBody{ 30.0f }
    );

    engine->entity<Position>(1, [&](auto pos) {
        std::cout << "entity";
    });
    engine->each<Position, Mesh>([] (int id, Position& pos, Mesh& mesh) {
        std::cout << "entity" << id;
    });

    template<typename First>
    void entity(int id, std::function<void(First&)> callback)
    {
        auto comp = storage<First>()->get(id);
        if (!comp) return;
        callback(*comp);
    }

    template<typename First, typename...Rest>
    void entity(int id, std::function<void(Rest&...)> callback)
    {
        auto comp = storage<First>()->get(id);
        if (!comp) return;
        entity<Rest...>(id, [](Rest&...args) {
            callback(*comp, args...)
        });
    }

    template<typename T, typename...Rest, typename F>
    void each(F&& callback)
    {
        storage<T>()->forEach([&](int id, T& value) {
            entity<Rest...>(id, [&](Rest&...args) {
                callback(id, value, args...);
            });
        });
    }


texts:
I am new to VB.NET and one of the functions I wrote is below.
The idea behind it is to just send a dictionary and table name to the function, get the result and then return.

Is this good practice or just silly?

Public Function dbInsert(ByRef EntryDetails As Dictionary(Of String, String),ByRef table as String) As Integer
    Dim command As new SqlCeCommand

    ' Loop over entries.
    Dim fieldNames() As String = {}
    Dim fieldsValues() As String = {}
    Dim pair As KeyValuePair(Of String, String)
    For Each pair In EntryDetails
        ReDim Preserve fieldNames(0 To UBound(fieldNames) + 1)
        fieldNames(UBound(fieldNames)) = pair.Key
        command.Parameters.AddWithValue("@" + pair.Key, pair.Value)
    Next

    command = New SqlCeCommand("INSERT INTO "+table+" (" + String.Join(",", fieldNames) + ")", connection.DbPublic)

    Dim newProdID As Int32 = 0
    Try
        command.ExecuteNonQuery()

        Dim cmd As New SqlCeCommand("SELECT @@IDENTITY", conn)
        newProdID = Convert.ToInt32(cmd.ExecuteScalar())
        'Console.WriteLine("added: {0}", newProdID)
        Return newProdID
    Catch e As Exception
        Console.WriteLine("Unable to insert: {0}", e.Message)
        Return 0
    End Try
End Function


texts:
I have implemented a through function for myself in a project.
Since I am still quite new in python and want to learn it correctly, I would be happy about any feedback including style, variable naming...

A first question is how to name the function. Because of Mathematica's documentation I called it through. Is there a more intuitive name?

def through(list_of_functions, value, recurse_level=np.infty):
    """Calls each function in a list

    This function is passing the value as argument to each function
    in a list.
    For a one dimensional list consisting of
    only functions it is equivalent to::

    [f(value) for f in list]

    If an element is not callable and not iterable, it is not called.
    An iterable is either directly appended or will be recursed through
    depending on recurse_level.

    Args:
        list_of_functions (list):
        value (any type):
        recurse_level (int):

    Returns:
        list:
    """
    new_list = []
    for possible_function in list_of_functions:
        try:
            new_list.append(possible_function(value))
        except TypeError: # item not callable; could be iterable
            # If it is iterable and recurse_level is not negative
            # recurse through elements
            if recurse_level >= 0:
                try:
                    new_list.append(through(possible_function,
                                            value,
                                            recurse_level))
                    recurse_level = recurse_level - 1
                except TypeError: # not an iterable; append without calling
                    new_list.append(possible_function)
            else:
                new_list.append(possible_function)
    return new_list

An example:

In: test = [[1, 2], [3, (lambda x : x ** 2)], (lambda x : x ** 3)]
In: through(test, 4, recurse_level=1)
Out: [[1, 2], [3, 16], 64]
In: through(test, 4, recurse_level=0)
Out: [[1, 2], [3, <function __main__.<lambda>>], 64]


texts:
I'm looking at my code and it doesn't look very efficient. I'm simply trying to catch exceptions or prevent them from being thrown in the first place. Can you please take a look and tell me if there is a way to make my working code more efficient?

public static void GetMoveCoordinates(ref int XCoordinate, ref int YCoordinate)
    {
        bool invalidCoordinate = false;

        do
        {
            try
            {

                Console.Write("Enter x coordinate: ");
                XCoordinate = int.Parse(Console.ReadLine());
                if (XCoordinate < 1 || XCoordinate > 3)
                {
                    invalidCoordinate = true;
                    Console.WriteLine("Invalid coordiantes, please try again.");
                }
                else
                    invalidCoordinate = false;

                if (!invalidCoordinate)
                {
                    Console.Write("Enter y coordinate: ");
                    YCoordinate = int.Parse(Console.ReadLine());
                    if (YCoordinate < 1 || YCoordinate > 3)
                    {
                        invalidCoordinate = true;
                        Console.WriteLine("Invalid coordiantes, please try again.");
                    }
                    else
                        invalidCoordinate = false;
                }
            }

            catch
            {
                Console.WriteLine("Invalid coordiantes, please try again.");
                invalidCoordinate = true;
            }
                Console.WriteLine();

        } while (invalidCoordinate);

    }  // end of GetMoveCoordinates


texts: A partially overlapping sequence of jQuery animations

texts:
I know this is a mess!  How can I write this code better?

function anim() {
            $( "#p1-animation-1" ).fadeIn( 1200, function() {
                $( "#p1-animation-1" ).fadeOut( 1200 );
                $( "#p1-animation-2" ).fadeIn( 1200, function() {
                    $( "#p1-animation-2" ).fadeOut( 1200 );
                    $( "#p1-animation-3" ).fadeIn( 1200, function() {
                        $( "#p1-animation-3" ).fadeOut( 1200 );
                        $( "#p1-animation-4" ).fadeIn( 1200, function() {
                            $( "#p1-animation-4" ).fadeOut( 1200 );
                            $( "#p1-animation-5" ).fadeIn( 1200, function() {
                                $( "#p1-animation-5" ).fadeOut( 1200 );
                                $( "#p1-animation-6" ).fadeIn( 1200, function() {
                                    $( "#p1-animation-6" ).fadeOut( 1200 );
                                    anim();
                                });
                            });
                        });
                    });
                });
            });
        }
        anim();


texts: Android application using RecyclerViews to list games in a Fragment

texts:
I am implementing MVP architecture, code works fine, I wanted your suggestions if I there can be improvements done or in any areas where I am not following the pattern correctly.

It is a simple application using RecyclerViews to list games in a Fragment.

FGames - Fragment which displays the list of Games

public class FGames extends Fragment implements GamesView {

    @BindView(R.id.rv_games)
    RecyclerView rvGames;
    private GamesAdapter gamesAdapter;
    private GamesPresenterImpl presenter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.games_layout, container, false);
        ButterKnife.bind(this, view);
        presenter = new GamesPresenterImpl(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        presenter.initUi();
    }

    @Override
    public void initRecyclerView(List<GameEntity> gameEntities) {
        gamesAdapter = new GamesAdapter(getActivity(), gameEntities);
        rvGames.setAdapter(gamesAdapter);
        rvGames.setLayoutManager(new LinearLayoutManager(getActivity()));
    }
}

Interface - GamesView

  public interface GamesView {

        /**
         * Initialise the recycler view to list Games data
         * @param gameEntities
         */
        void initRecyclerView(List<GameEntity> gameEntities);
    }

GamesPresenterImpl - Presenter implementation

    public class GamesPresenterImpl implements GamesPresenter {

    GamesView gamesView;

    public GamesPresenterImpl(GamesView gamesView) {
        this.gamesView = gamesView;
    }

    @Override
    public void initUi() {
        gamesView.initRecyclerView(getGamesData());
    }

    public List<GameEntity> getGamesData() {
        List<GameEntity> gameEntities = new ArrayList<>();
        int counter = 0;
        for(int i = 0; i<10; i++){
            GameEntity gameEntity = new GameEntity();
            counter ++;
            gameEntity.setName("Test name " + counter);
            gameEntity.setJackpot(100000055);
            gameEntities.add(gameEntity);
        }
        return gameEntities;
    }
}

Interface - GamesPresenter

public interface GamesPresenter {
    void initUi();
}


texts: Is this method a good candidate for a service layer?

texts:
Should the following GetPhysicalFileLocation() method in the Car class have its own Service Layer?

public class Car
{
    public int id;
    public string model;
    public int year;
    public IList<Pic> lstCarPics;
}

Then we have the respective class:

public class Pic
{
    public string filename;
    public string fileLocation;
    public string GetPhysicalFileLocation()
    {
        string LocalDirectory = "~\\CarFiles\\";
        DirectoryInfo diPath = new
            DirectoryInfo(HttpContext.Current.Server
                         .MapPath(LocalDirectory + car.id);
    }
}

Seeing that this method and others will access physical file locations throughout the application, would something like this justify having it's own FileService?

I'm having trouble understanding when methods like this should fall under it's own service layer vs leaving it in its class.


texts:
Here is my Python code for Project Euler #2:

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

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

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

How well did I do and what improvements can I make?

sum = 0
fib = []
i = 2

fib.append(0), fib.append(1), fib.append(1)
while fib[i] < 4000000:
    i += 1
    fib.append(fib[i-1] + fib[i-2])
    if (fib[i] % 2 ==0):
        sum += fib[i]

print sum

EDIT: Thanks everyone for answering and commenting. All answers and some comments provide different suggestions which is very helpful.


texts: Node.js put records to Kinesis with infinite retry strategy.

texts:
My application is really easy. It's going to add 500 records at a time to AWS Kinesis and if there's an error occur I'll just add that back to the queue and it's going to be retry. It's going well but I feel like there's a bug somewhere that I don't see.

'use strict';

const _ = require('lodash');
const moment = require('moment');

const config = require('../config');
const logger = require('../logger');
const numbers = require('../helpers/numbers');

const streamName = config.kinesis.streamName;

let records = [];
module.exports = (kinesis) => {
  let sendRecords = () => {
    let payloadRecords = {
      Records: records,
      StreamName: streamName
    };

    if (records.length >= 500) {
      const pushingToKinesis = records.splice(0, 500);
      payloadRecords.Records = pushingToKinesis;
    } else {
      records = []
    }

    kinesis.putRecords(payloadRecords, (err, data) => {
      if (err) {
        logger.error(err);
      }

      const failedRecord = _.get(data, 'FailedRecordCount', 0);

      if (failedRecord > 0) {

        logger.warn(`There are ${data.FailedRecordCount} failed`);

        data.Records.forEach((record, index) => {
          if (_.has(record, 'ErrorCode') || _.has(record, 'ErrorMessage')) {
            logger.debug(record);
            logger.debug(payloadRecords.Records[index]);

            records.push(payloadRecords.Records[index]);
          }
        });
      }
    });
  };

  let putRecord = (record) => {
    let payload = {
      Data: JSON.stringify(record),
      PartitionKey: String(numbers.random() * 100000)
    };
    records.push(payload);

    if (records.length >= config.kinesis.maxRecords) {
      sendRecords();
    }
  };

  return {
    putRecord: putRecord,
    recordCount: () => {
      return records.length;
    },
    clearRecord: () => {
      records = [];
    },
    init: () => {
      setInterval(() => {
        if (!_.isEmpty(records)) {
          sendRecords();
        }
      }, 200);
    }
  };
};


texts: k-means clustering algorithm implementation

texts:
Here is my personal implementation of the clustering k-means algorithm.

from scipy.spatial import distance
import numpy as np
import random

# (x,y) coordinates of a point
X = 0
Y = 1

def get_first(k, points):
    return points[0:k]

def cost(cetroids, clusters):
    cost = 0

    for i in range(len(centroids)):
        centroid = centroids[i]
        cluster = clusters[i]
        for point in cluster:
            cost += (distance.euclidean(centroid, point))**2

    return cost

def compute_centroids(clusters):
    centroids = []

    for cluster in clusters:
        centroids.append(np.mean(cluster, axis=0))

    return centroids

def kmeans(k, centroids, points, method, iter):
    clusters = [[] for i in range(k)]

    for i in range(len(points)):
        point = points[i]
        belongs_to_cluster = closest_centroid(point, centroids)
        clusters[belongs_to_cluster].append(point)

    new_centroids = compute_centroids(clusters)

    if not equals(centroids, new_centroids):
        print "Iteration " + str(iter) + ". Cost [k=" + str(k) + ", " + method + "] = " + str(cost(new_centroids, clusters))

        clusters = kmeans(k, new_centroids, points, method, iter+1)

    return clusters

def closest_centroid(point, centroids):
    min_distance = float('inf')
    belongs_to_cluster = None
    for j in range(len(centroids)):
        centroid = centroids[j]
        dist = distance.euclidean(point, centroid)
        if dist < min_distance:
            min_distance = dist
            belongs_to_cluster = j

    return belongs_to_cluster

def contains(point1, points):
    for point2 in points:
        if point1[X] == point2[X] and point1[Y] == point2[Y]:
            return True

    return False

def equals(points1, points2):
    if len(points1) != len(points2):
        return False

    for i in range (len(points1)):
        point1 = points1[i]
        point2 = points2[i]
        if point1[X] != point2[X] or point1[Y] != point2[Y]:
            return False

    return True

if __name__ == "__main__":
    data = [[-19.0748,     -8.536       ],
            [ 22.0108,      -10.9737    ],
            [ 12.6597,      19.2601     ],
            [ 11.26884087,  19.90132146 ],
            [ 15.44640731,  21.13121676 ],
            [-20.03865146,  -8.820872829],
            [-19.65417726,  -8.211477352],
            [-15.97295894,  -9.648002534],
            [-18.74359696,  -5.383551586],
            [-19.453215,    -8.146120006],
            [-16.43074088,  -7.524968005],
            [-19.75512437,  -8.533215751],
            [-19.56237082,  -8.798668569],
            [-19.47135573,  -8.057217004],
            [-18.60946986,  -4.475888949],
            [-21.59368337,  -10.38712463],
            [-15.39158057,  -3.8336522  ],
            [-40.0,          40.0       ]]
    k = 4

    # k-means picking the first k points as centroids
    centroids = get_first(k, data)
    clusters = kmeans(k, centroids, data, "first", 1)

I understood and followed the theory of the algorithm, but as you can see, when running the code, the cost on each iteration of the algorithm increases. I am new to python and I think the problem relies in some misunderstanding from my side regarding list manipulation. Any ideas?


texts:
I'm currently creating my own microframework for learning purpose and I want to make it more powerful by providing a way to register classes and instantiate them (once) only when needed. So here is my try :

<?php

namespace Framework\Core;

use Exception;
use ReflectionClass;

/**
 * Class Container
 *
 * @package App\Core
 *
 * Depandancies injection and lazy loading, I guess ? (not sure how to call it for now)
 *
 */
class Container
{

    /**
     * @var array Contains all classes instance.
     */
    private static $instances = array();

    /**
     * @var array Contains all fully qualified classes name.
     */
    private static $classes = array();

    /**
     * @var string Should contain the name of the last registered class name.
     */
    private static $lastRegistered;

    /**
     * Container constructor.
     */
    private function __construct() {}

    /**
     * Prevents cloning.
     */
    private function __clone() {}

    /**
     * Prevents deserialization.
     */
    private function __wakeup() {}

    /**
     * Gets a class instance.
     *
     * @param $name
     * @param null $renew
     * @return mixed
     * @throws Exception
     */
    public static function get($name = NULL) {
        $name = (!$name) ? self::$lastRegistered : $name;
        if (self::$classes[$name]) {
            if (self::$instances[$name]) {
                return self::$instances[$name];
            } else {
                self::$instances[$name] = new self::$classes[$name];
                return self::$instances[$name];
            }
        } else {
            throw new Exception('The following class name could not be found: ' . $name);
        }
    }

    /**
     * Registers a class.
     *
     * @param $name
     * @param $class
     * @return $this|null
     * @throws Exception
     */
    public static function register($name, $class) {
        $reflection = new ReflectionClass($class);
        if (!$reflection->isInstantiable()) {
            throw new Exception('The provided class is not instantiable: ' . $class);
        }
        if (!in_array($name, self::$classes)) {
            self::$classes[$name] = $class;
        }
        self::$lastRegistered = $name;
        return __CLASS__;
    }

    /**
     * Returns an array of all registered classes.
     *
     * @return array
     */
    public static function getRegisteredClasses() {
        return self::$classes;
    }

    /**
     * Returns an array of all instantiated classes.
     *
     * @return array
     */
    public static function getInstantiatedClasses() {
        return self::$instances;
    }

}

So basically, what it does it that it allows you to register a class name as follow :

Container::register('config', \Framework\Core\Config::class);

And then you can get the class instance like this :

Container::get('config');

You can also register() and immediately get() the class instance like this :

Container::register('config', \Framework\Core\Config::class)::get();

I added this "feature" into my microframework in order to prevent instantiating a class more than one time.

The interesting part is that it instantiates the class only when you call the get() method, not when you register it. It allows me to register all framework dependancies at once when the app starts and then get their instances later.

Obvisouly, this class needs improvement in terms of "options". Because, what if I need to register() and get() a class that needs arguments to be passed into its constructor ? I'm aware about that and before making this class more "flexible" I just wanted to know if it's useful to have a "feature" like this in my microframework.

My question is :
How is this called ? Singleton ? Container ? Dependency injection ?
Also, can my microframework benefits from having this "feature" ?


texts:
I need to find correct index in a array by comparing ranges. Here is my first try:

int TunerDriver::TunerLookUpTable(double Freq) {
  Freq /= 1e6;
  if (Freq >= 60 and Freq < 140)
    return 1;
  else if (Freq >= 180 and Freq < 280)
    return 2;
  else if (Freq >= 280 and Freq < 460)
    return 3;
  else if (Freq >= 140 and Freq < 180)
    return 4;
  else if (Freq >= 2720 and Freq < 4020)
    return 5;
  else if (Freq >= 4020 and Freq <= 6000)
    return 6;
  else if (Freq >= 2000 and Freq < 2720)
    return 7;
  else if (Freq >= 830 and Freq < 1420)
    return 8;
  else if (Freq >= 1420 and Freq < 2000)
    return 9;
  else if (Freq >= 460 and Freq < 830)
    return 10;
  else {
    //TODO: throw exception
  }
}

I believe I can use std::pair and for to increase readability. Can you assist me in this case?


texts:
I'm new in Prolog. So, I'm not sure if my code is ok and optimized. I'm also not sure if I use recursion correctly.

Task: find students that has at least 1 bad grade (1 or 2) and print them in table

hasBadGrades(N) :- student(_, N, G), containsBadGrades(G).

containsBadGrades([H|T]) :- wildcard_match('*/[1-2]', H); containsBadGrades(T).

printStudent(N, I) :- student(G, N, [M, C, O, P]),
   format("| ~a~t~5+ | ~a~t~5+ | ~a~t~16+ | ~a, ~a, ~a, ~a~t~41+ |~n", [I, G, N, M, C, O, P]).

printTHead :-
   printLine(),
   format("| ~a~t~5+ | ~a~t~5+ | ~a~t~16+ | ~a~t~40+ |~n", ['#', group, name, grades]),
   printLine().

printLine :- format("|~`-t~70||~n").

printList([S|T], N) :- printStudent(S, N), printLine(), K is N + 1, printList(T, K).

printFaildStudents :- printTHead(), setof(N, hasBadGrades(N), L), printList(L, 1).

student(1050, adams, ['math/4', 'c++/3', 'oop/4', 'physics/3']).
student(2100, alexander, ['math/3', 'c++/2', 'oop/4', 'physics/3']).
student(3151, allen, ['math/3', 'c++/4', 'oop/3', 'physics/3']).
student(4200, anderson, ['math/3', 'c++/2', 'oop/2', 'physics/3']).
student(5250, bailey, ['math/4', 'c++/3', 'oop/3', 'physics/4']).
student(1050, baker, ['math/3', 'c++/3', 'oop/4', 'physics/2']).
student(2100, barnes, ['math/4', 'c++/3', 'oop/3', 'physics/2']).
student(3151, bell, ['math/4', 'c++/3', 'oop/4', 'physics/4']).
student(4200, bennett, ['math/4', 'c++/3', 'oop/4', 'physics/3']).
student(5250, brooks, ['math/4', 'c++/3', 'oop/3', 'physics/3']).
student(1050, brown, ['math/3', 'c++/4', 'oop/4', 'physics/2']).
student(1050, flores, ['math/4', 'c++/3', 'oop/4', 'physics/3']).
student(2100, foster, ['math/4', 'c++/4', 'oop/3', 'physics/4']).
student(3151, garcia, ['math/3', 'c++/3', 'oop/2', 'physics/3']).
student(4200, gonzales, ['math/3', 'c++/4', 'oop/4', 'physics/3']).
student(5250, gonzalez, ['math/4', 'c++/2', 'oop/3', 'physics/3']).
student(1050, gray, ['math/3', 'c++/4', 'oop/3', 'physics/4']).
student(2100, green, ['math/2', 'c++/4', 'oop/1', 'physics/4']).
% . . .


texts: Speeding up repetitive initialisation with structured data?

texts:
I need to speed up this code: it creates a multilinear function. I considered the below methods but no idea which with the largest benefit.

replacing dummy variables with things such as anonymous functions
having all code in the same file (my instructor's hint)
improving the looping: getting rid of num2str
other?

I need to repeatedly create this kind of initialisations and I am trying to get it as fast as possible. It may be that the reason for the slowness of my code lies somewhere else, not this code, say it if you think so! There may be some elegant functional way to write this fast and more compactly. I already know that the whole code is probably slow because of the mlfnneg but in order to speed it up I need to make sure the bug is not early ie on this code aka during the initialisation of test-cases.

 %Creating a mlf to check the negativity of the multilinear function

 % Example: 0<x_i<i/Density
 lbs_str=containers.Map;  % I need variables here only to initialise mlf at the end
 ubs_str=containers.Map;
 terms=containers.Map;

 for i = 1:100
    i=num2str(i); % possible to make this more elegant? contairers.Map requires string
    lbs_str(i)=0;
    ubs_str(i)=i/100;
    terms(i)=struct('coeff',1,'vars',{{i}});
    % Tested catstruct [1] to append new terms to the mlf_terms but not intended:
    % it does not do {terms('1'), terms('2'),...} aka {terms.values}
 end

 lbs=mlfpoint(lbs_str);
 ubs=mlfpoint(ubs_str);
 mlf_terms=struct('const',0,'terms',{terms.values});
 mlf=mlfcreate(mlf_terms);

 mlfnneg(lbs,ubs,mlf)


texts:
Below is a simple "class" for displaying messages.  It stores the output html div and then displays messages to it as needed.

It works fine.  For readability, and encapsulation purposes, I'd like the componenets of the "class" in a contianer of sorts or a javascript object?  What is the simplest way to to do this.

Or...is there a simple way to do this?

Currently the only container is the comments I've surrounded the code with.

/**
 *      Module  :       Model
 *      Name    :       -Message
 *      Input   :       div via the constructor
                        message type via display
 *      Output  :       TextStream via display to Control.sendInner
 *      Notes   :       Symmetric, client holds message location so needs extra variable
 */

var Message = function( div )
{
    this.div = document.getElementById( div );
};

Message.prototype.messages =
{
    name:       'Please enter a valid name',
    email:      'Please enter a valid email',
    pass:       'Please enter passoword, 6-40 characters',
    url:        'Pleae enter a valid url',
    title:      'Pleae enter a valid title',
    tweet:      'Please enter a valid tweet',
    empty:      'Please complete all fields',
    empty_bm:   'Please complete all fields',
    same:       'Please make emails equal',
    taken:      'Sorry, that email is taken',
    validate:   'Please contact support to reset your password'
};

Message.prototype.display = function( type )
{
    Control.sendInner( this.div, this.messages[type] )
};

/**      Message End        */


texts:
I've been using this variation of the Repository pattern for over a year now:

 public interface IReadOnlyRepository<T, in TId>
     where T : AbstractEntity<TId>
    {
        T Get( TId id );
        IEnumerable<T> GetAll();
    }

/// <summary>
/// Defines a generic repository interface for
/// classes solely in charge of getting and processing data from a data source
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TId">The type of the id.</typeparam>
public interface IRepository<T, in TId> : IReadOnlyRepository<T, TId> where T : AbstractEntity<TId>
{
    /// <summary>
    /// Determines whether the specified entity has duplicates.
    /// </summary>
    /// <param name="entity">The entity.</param>
    /// <returns>
    ///   <c>true</c> if the specified entity has duplicates; otherwise, <c>false</c>.
    /// </returns>
    bool HasDuplicates(T entity);

    /// <summary>
    /// Inserts the specified entity.
    /// </summary>
    /// <param name="entity">The entity.</param>
    void Save( T entity );
    /// <summary>
    /// Inserts the entity or updates it if it already exists.
    /// </summary>
    /// <param name="entity">The entity.</param>
    T SaveOrUpdate( T entity );

    /// <summary>
    /// Updates the specified entity.
    /// </summary>
    /// <param name="entity">The entity.</param>
    /// <returns></returns>
    T Update(T entity);

    /// <summary>
    /// Deletes the specified entity from the data source.
    /// </summary>
    /// <param name="entity">The entity.</param>
    void Delete(T entity);

    /// <summary>
    /// Deletes the entity with the specified id.
    /// </summary>
    /// <param name="id">The id.</param>
    void Delete(TId id);
}

but recently, after rereading some books on Design Patterns, I've had this seemingly amazing idea to apply some patterns to my repositories.

public interface IRepository<T, in TId> : IReadOnlyRepository<T, TId> where T : AbstractEntity<TId>
{
    void Execute(IRepositoryCommand command);
    void Execute(IBatchRepositoryCommand command);
}

public interface IRepositoryCommand<T>
{
    void Execute(T entity);
}

public interface IBatchRepositoryCommand<T>
{
    void Execute(IEnumerable<T> entities);
}

public SaveCommand<T> : IRepositoryCommand<T>
{
    public void Execute(T entity)
    {
        // Logic for saving goes here
    }
}

public BatchSaveCommand<T> : IRepositoryCommand<T>
{
    public void Execute(IEnumerable<T> entities)
    {
        // Logic for batch saves go here
    }
}

which would then be called like this:

_myRepository.Execute(new SaveCommand());

My reasoning is that placing logic for the common data access operations (e.g. saving, deleting) gets to be so repetitive that right now I'm relying on a T4 template to recreate those everytime I have a new entity enter the playing field. This way I just define the most commonly used Data Access operations and then have any of my callers execute whatever action they need to execute.

Can you critique my work? I do have the tendency to overthink and overengineer things.


texts: Express routing with a login action using SQLite

texts:
I'm new to Express and SQL, so I don't know the conventional ways of combining the two. Right now I have done it the following way:

app.get('/login', function (req, res) {
    res.render('login');
});

app.get('/home', function (req, res) {
    res.render('home');
});

app.post('/login', function (req, res) {
    db = new sqlite3.Database(file);
    db.serialize(function () {
        [...]
        db.all(query, function (err, rows) {
            if(rows.length == 1) {
                [...]
                res.render('home', {
                    username: rows[0].username
                });
            }
            else {
                res.render('login', {
                    message: "Login not successful!"
                });
            }
        });
    });
    db.close();
});

However, I feel like the routing should be separated from the database stuff. What should I do different? Or is this normal?


texts:
I have this method that returns true if attribute is already used and false otherwise:

public boolean alreadyUsed(Node node, int attribute)
{
    if (node.parent == null)
    {
        return false;
    }

    if (node.children != null)
    {
        if (node.splitAttribute == attribute )
        {
            return true;
        }
    }
    return alreadyUsed(node.parent, attribute);
}

Can this be written in a more understandable way?


texts: Filtering FASTQ file based on read names from other file (how to increase performance) Python

texts:
I have some code here that basically takes in a list of IDs (sequencing read names) using STDIN, and then filters fin (a gzipped FASTQ file) to just those reads with a read name which matches one of the IDs, and then writes the name and sequence to fout (a gzipped FASTA file). Fairly standard data processing problem in bioinformatics.
The code below can run through about 100k/sec lines of fin, however fin is about 500M lines, so it still takes over an hour.
Can this be sped up significantly? I'm hoping for a 10x or better improvement in performance. I may be taking a performance hit running line.decode('utf-8'), however it's necessary for matching since gzip files are read as bytestring. I'm willing to drop down and rewrite this in C if this will substantially increase speed.
import sys
import gzip
import re

id_array = []
for line in sys.stdin:
    id_array.append(line.rstrip())

ids = set(id_array)

with gzip.open(sys.argv[1], "r") as fin:
    with gzip.open(sys.argv[2], "w") as fout:

        take_next_line = False
        for line in fin.readlines():
            seq_search = re.search('[@+]([^\s]+)', line.decode('utf-8'))

            if take_next_line:
                fout.write(line)
                take_next_line = False

            elif seq_search and seq_search.group(1) in ids:
                take_next_line = True
                fout.write('>' + line[1:])


texts:
Current best practice for using a lock_guard looks like this:

// introduce scope to take the lock
{
    lock_guard lock(sync);    // sync is an accessible mutex object
    do_protected_stuff();     // may throw, but the mutex is released regardless
}
// no exception, mutex is released in normal flow

I don't like the scope being introduce without a statement.  I think it detracts from readability, and I think it's ugly.  It occurred to me that what I wanted was the equivalent of modern Python's with statement:

with Lock() as lock:          # corresponds to lock+mutex in C++
    do_protected_stuff()

I thought about it for a while and designed a syntax hack that's gotten me partway there:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using std::cout;
using std::endl;

//=============================================
// This is the "novel" part
// See main() for usage
//=============================================
// a utility class
class with_lock_
{
public:
    with_lock_(boost::mutex &mtx_) : lock(mtx_), new_lock(true) {}
    operator bool() { bool ret = new_lock; new_lock = false; return ret; }
private:
    boost::lock_guard<boost::mutex> lock;
    bool new_lock;
};
// a macro to hide the gory details
#define with_lock_guard(SYNC)   for (with_lock_ lk_(SYNC); lk_; )

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

// some global stuff for multi-thread action
// a mutex
boost::mutex sync;

// a value protected by the mutex
float zz = 0.0f;

// a thread function that will change the value and crow about it
void get_it_yourself()
{
    boost::lock_guard<boost::mutex> lock(sync);
    zz = 99999.99999f;
    cout << endl << "  ---  MINE!!" << endl;
}

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

int main()
{
    boost::thread runit;

    //=============================================
    // This is the intended use...
    // a little syntactic hack, inspired by Python
    //=============================================
    with_lock_guard (sync)
    {
        runit = boost::thread(get_it_yourself);
        cout << "Starting... ";
        boost::this_thread::sleep(boost::posix_time::millisec(500));
        cout << "OK!  Z = " << zz << endl;
    }

    // wait for that thread to complete
    runit.join();

    return 0;
}

Accept, for this discussion, that having a keyword to introduce the scope is preferable to introducing scope with just a brace.  This hack lets you pretend you have a real with-like statement: you can follow it with a single or compound statement.

I do have a concern regarding the scope of the with_lock_ object. As I read things, at some level (persisting even into C++11?) the scope of a variable introduced within a for statement is the block enclosing the for. In practice, it's working OK for me with MSVS 2008; there is a compiler option regarding this, which defaults to the behavior I need in this situation.

Even without backing off from the basic idea, I see room for improvement.  For one thing, a true with statement in C++ would be able to accept other types of RAII-based objects, as Python does.  But so far in practice, I've only really the undesirable syntax with lock_guard.

What I'm looking for is a way to generalize this feature such that, at least, any mutex type, from any namespace, can be used.  Better, if any lock type can be used.  A cleaner implementation than abusing for or the operator bool() would be of interest.

Also: I'm not concerned if it breaks older compilers, but it would good to know if this works or doesn't in platforms/compilers other than Windows/MSVS2008+. Comments decrying the whole abomination are fine.


texts:
I have ~40,000 JPEG images from the Kaggle melanoma classification competition. I created the following functions to denoise the images:
# Denoising functions
def denoise_single_image(img_path):
    img = cv2.imread(f'../data/jpeg/{img_path}')
    dst = cv2.fastNlMeansDenoising(img, 10,10,7,21)
    cv2.imwrite(f'../processed_data/jpeg/{img_path}', dst)
    print(f'{img_path} denoised.')

def denoise(data):
    img_list = os.listdir(f'../data/jpeg/{data}')
    with concurrent.futures.ProcessPoolExecutor() as executor:
        tqdm.tqdm(executor.map(denoise_single_image, (f'{data}/{img_path}' for img_path in img_list)))

The denoise function uses concurrent.futures to map the denoise_single_image() function over the full list of images.
ProcessPoolExecutor() was used based on the assumption of denoising as a CPU-heavy task, rather than an I/O-intensitve task.
As it stands now, this function takes hours to run. With a CUDA-configured Nvidia GPU and 6 GB VRAM, I'd like to optimize this further.
Is there any way to improve the speed of this function?
Multi-core processing documentation
OpenCV documentation


texts: Check is_permutation on a pair of same sized arrays - follow-up

texts:
After considering the suggestions of my previous question, Check whether given a pair of arrays are permutation of each other, I changed the code.

Resolved the bug reported earlier
In place of std::set using std::unordered_map to attain \$O(n)\$ complexity
In place of indexing array used std::array

#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<array>
template <typename T1, std::size_t N>
std::unordered_map<int,int> make_unordered_map(std::array<T1,N> & array)
{
    std::unordered_map<int,int> temp_unordered_map;
    auto temp_unordered_map_end = temp_unordered_map.end();
    for( auto &x: array)
    {
        auto it_temp_unordered_map = temp_unordered_map.find(x);
        if( it_temp_unordered_map == temp_unordered_map_end)
        {
            temp_unordered_map.insert(std::pair<T1,int>(x,1));
        }
        else
        {
            ++(it_temp_unordered_map->second);
        }
    }
    return temp_unordered_map;
}

template <typename T1, std::size_t N1, std::size_t N2>
bool is_permutation(std::array<T1,N1> & array1, std::array<T1,N2>&  array2)
{
    if( N1  != N2)
       return false;
    else
    {
        std::unordered_map<int,int> first_map = make_unordered_map(array1);
        std::unordered_map<int,int> second_map = make_unordered_map(array2);

        std::pair<std::unordered_map<int,int>::iterator,std::unordered_map<int,int>::iterator> myPair=
                std::mismatch(first_map.begin(),first_map.end(),second_map.begin(),
                [](std::pair<const int,int>& seed1, std::pair<const int,int> & seed2)
                  { return seed1.second == seed2.second;}
            );

        if(( myPair.first == first_map.end()) && (myPair.second == second_map.end()))
            return true;
        else
            return false;
    }
}

int main()
{
    std::array<int,5> array1 {{1,3,1,4,5}};
    std::array<int,4> array2 {{1,1,4,3}};

    if(::is_permutation<int,array1.size(), array2.size()>(array1, array2))
        std::cout<< " Arrays are permutation of each other\n";
    else
        std::cout<< " Arrays are not permutation of each other\n";

    return 0;
}


texts:
Question:

  Special Pythagorean triplet, Euler Problem 9

  A Pythagorean triplet is a set of three natural numbers, \$a<b<c\$, for which, $$a^2+b^2=c^2$$ For example, \$3^2+4^2=9+16=25=5^2\$.

  There exists exactly one Pythagorean triplet for which \$a+b+c=1000\$.

  Find the product \$abc\$.

I got the code to work using algebraic simplifications shown below.

  Given:

  \$num=1000\$

  \$a+b+c=1000\$

  \$a^2+b^2+c^2+2ab+2bc+2ca=num^2\$

  \$a^2+b^2=c^2\$

Thus:

$$2c^2+2ab+2bc+2ca=num^2$$
$$c(c+b)+a(b+c)=\frac{num^2}{2}=500num$$
$$(a+c)(b+c)=500num$$
$$(num-b)(num-a)=500num$$
$$num-b=\frac{500num}{num-a}$$
$$b=num-\frac{500num}{num-a}$$

So, I scan through \$a\$ and if I receive an integer value for \$b\$ we have found \$b\$, and thus \$c\$ can be found through the equation \$c=num-a-b\$.

The upper limit of \$a\$ is found by assuming that \$a\$ is the smallest among the three integers,  \$a\$, \$b\$, and \$c\$ such that \$a<b<c\$. Following this assumption, let's find the max condition by rewriting \$b\$ and \$c\$ in terms of \$a\$. So, \$b = a+n\$ and \$c = a+k\$ where \$n<k\$, so that \$a<b<c\$ remains true.

Now:

$$a+b+c=num$$
$$a+(a+n)+(a+k)=num$$
$$3a+n+k=num$$
$$3a=num-(n+k)$$
$$a=\frac{num-(n + k)}{3}$$

Now, the max acceptable value of \$a\$ according to the equation could be when \$n=1\$, and \$k=2\$ since \$a<b<c\$. In other words, the difference between the values is 1.

Therefore we loop \$a\$ up to \$\frac{num}{3} - 1\$

My code manages a runtime of ~0.166526 ms:

public class Java {

public static void main(String[] args) {

    double num = 1000.0;
    double b = 0;

    for(int a = 2 ; a <= (num/3 - 1); a++){
          b = ( num - ( 500*num / (num-a)));

          if(b == (int)b){
              System.out.println((int)(a*b*(num-a-b)));
              break;
          }

    }

}

Any suggestions for setting a lower limit for \$a\$ and probably speeding up the algorithm? The upper limit seems odd since I just used \$a+b+c=1000\$ when finding it instead of the Pythagorean Theorem.


texts: Google Drive folders properties caching to file

texts:
I have the recursive function below to cache all the folders of my company Drive into a file. It works like a charm but takes too long, specifically >30 secs to read and save the 300 folders.

What I need is to make it faster somehow. I don't know if it is possible to make the folder reading asynchronous, or if it possible to make a webhook or something to listen to changes in the Drive's folders, which would eliminate the need to run recursively over all folders.

function generateFolderTree( idParent, tree ){
  var currParent = DriveApp.getFolderById( idParent),
      folderChildren = currParent.getFolders(),
      currChild,
      currChildId;

  if( tree.length == 0 ){
    tree.push({ 'text' : currParent.getName(), 'parent' : '#', 'id' : idParent, 'state' : { 'opened' : true }, 'li_attr':{'title': ''} });
  }

  while( folderChildren.hasNext() ){
    currChild = folderChildren.next();
    currChildId = currChild.getId();

    tree.push({ 'text' : currChild.getName(), 'parent' : idParent, 'id' : currChildId, 'li_attr':{'title': currChild.getDescription()} });

    generateFolderTree( currChildId, tree );
  }
}

function geneteAndSaveTheTree(){
  var theTree = [];

  generateFolderTree(folderToIterateId, theTree);

  DriveApp.getFileById(theFileWhereAllFoldersAreStored).setContent(JSON.stringify(theTree));
  return theTree;
}

I know you can get all folders at once for a Drive, but I think it would take even longer to find out all the folders that are child of the folderToIterateId.