texts: Approach for one class to safely refer to another, with both having unknown lifetimes

texts:
It is not always possible to simplify program design by strictly managing the lifetimes of objects. If two objects have unpredictable lifetimes, but one of them needs to refer to the other, a simple pointer or reference is a segmentation fault waiting to happen.

The approach that I tried first was to have both objects contain a pointer to the other, and code in the destructors of both objects that would set the other object's pointer to null:

#include <iostream>

class Manager;

class Tracked
{
public:
    ~Tracked();
    void act() {std::cout << "hello world!\n";}
    void setManager(Manager *manager) {manager_ = manager;}
    void markManagerInvalid() {manager_ = nullptr;}
private:
    Manager *manager_;
};

class Manager
{
public:
    void attach(Tracked &tracked)
    {
        tracked_ = &tracked;
        tracked_->setManager(this);
    }
    void detach()
    {
        if(tracked_ != nullptr)
        {
            tracked_->markManagerInvalid();
            tracked_ = nullptr;
        }
    }
    void invoke()
    {
        if(tracked_ != nullptr)
            tracked_->act();
    }
private:
    Tracked *tracked_;
};

Tracked::~Tracked()
{
    if(manager_ != nullptr)
        manager_->detach();
}

int main()
{
    Manager manager;
    {
        Tracked tracked;
        manager.attach(tracked);
        manager.invoke(); //output: hello world!
    }//"tracked" goes out of scope: the pointer in "manager" is now invalidated.
    manager.invoke();
}

This works and sounds very simple but in practice it has serious drawbacks:

There is not only tight coupling but also a circular dependency between Tracker and Manager.
In order to have many Manager instances link to the same Tracked instance, the Tracked class would have to incorporate a list of Manager pointers to instances that are linking to it.
The code is complex and error prone, and would get even worse with multiple instances linking to each other.

To get around this I devised a different solution: A dynamically allocated pointer to the Tracked instance. The pointer would be set to nullptr by the pointed Tracked instance in the insance's destructor to mark the instance as expired. The same pointer instance is shared using std::shared_ptr with all objects requiring safe access to the Tracked instance.

#include <iostream>
#include <memory>

class Tracked
{
public:
    using Handle = std::shared_ptr<Tracked*>;
    Tracked() : handle_(new Tracked*(this)) { }
    ~Tracked() {*handle_ = nullptr;}
    void act() {std::cout << "hello world!\n";}
    Handle getHandle() {return handle_;}
private:
    Handle handle_;
};

class Manager
{
public:
    void attach(Tracked &tracked) {handle_ = tracked.getHandle();}
    void detach() {handle_.reset();}
    void invoke()
    {
        if(handle_ != nullptr)
        {
            if(*handle_ != nullptr)
                (*handle_)->act();
        }
    }
private:
    Tracked::Handle handle_;
};

int main()
{
    Manager a, b, c;
    {
        Tracked tracked;
        a.attach(tracked);
        b.attach(tracked);
        a.invoke(); //output: hello world!
    } //"tracked" goes out of scope: the handles in "a" and "b" are now invalidated.
    b.invoke();
    c.invoke();
}

I have found surprisingly little information on this, is this a known idiom or design pattern?

Edit:
At the conclusion of writing this question I realized that I could just allocate the Tracked object with new and manage the object with a std::shared_ptr, distributing a std::weak_ptr to each Manager. If std::weak_ptr::lock() would return a null shared_ptr, the Tracked instance would be expired.


texts: Counting standard deviation from parsed XML file

texts:
I wrote a method that calculates the average and standard deviation of sell currency exchange-course (ASK).  But I think that it isn't the easiest way to define such behavior.

In my opinion there is too much creating of BigDecimal values.
I have also doubts about using an ArrayList to get values in order to count standard deviation, maybe there is a better data structure to achieve that goal.

The method contains also counting average of buy currency exchange-course (BID in parsed file) but don't focus on it please.

package pl.parser.nbp;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Counting {
public void countAverageAndStandartDeviaton(String address){
    try
    {
        DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = df.newDocumentBuilder();
        Document doc = db.parse(address);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("Rate");

        List<BigDecimal> listForStandartDeviation = new ArrayList<>();
        BigDecimal averageOfBid = new BigDecimal("0");
        BigDecimal averageOfAsk = new BigDecimal("0");
        BigDecimal divisor = new BigDecimal(nList.getLength());

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                BigDecimal valueForBidAverage = new BigDecimal(eElement.getElementsByTagName("Bid").item(0).getTextContent());
                BigDecimal valueForStandartDeviation = new BigDecimal(eElement.getElementsByTagName("Ask").item(0).getTextContent());
                averageOfBid = averageOfBid.add(valueForBidAverage);
                averageOfAsk = averageOfAsk.add(valueForStandartDeviation);
                listForStandartDeviation.add(valueForStandartDeviation);

            }
        }
        averageOfBid = new BigDecimal(averageOfBid.divide(divisor).toString()).setScale(4, RoundingMode.HALF_UP);
        averageOfAsk = new BigDecimal(averageOfAsk.divide(divisor).toString());
        System.out.println(averageOfBid + " - BID Average");

        BigDecimal sumStandartDeviation = new BigDecimal("0");
        for(int i = 0 ; i<listForStandartDeviation.size(); i++){
            BigDecimal valueFromList = new BigDecimal(listForStandartDeviation.get(i).toString());
            sumStandartDeviation = sumStandartDeviation.add((valueFromList.subtract(averageOfAsk)).pow(2));
        }
        sumStandartDeviation = sumStandartDeviation.divide(divisor);
        sumStandartDeviation = new BigDecimal(Math.sqrt(sumStandartDeviation.doubleValue()))
                .setScale(4, RoundingMode.HALF_UP);
        System.out.println(sumStandartDeviation +  " - ASK Standart Deviation");

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}


texts: Optimizing Python loop with Numba for live load analysis

texts:
I have written some code that computes flexural moments imposed by different trucks for a bridge with 300 ft length. Truck data are contained in two lists: ax_list and sp_list, which are the axle weights and axle spacings, respectively.

There is nothing much to the code, however, this needs to be repeated for millions of different truck types, and I am trying to optimize my code, which takes real long time when the actual data size set is concerned.

I tried using Numba to see if I can get any speed gains, but it did not change the execution time, whether I add Numba @jit decorators for each function or not. What am I doing wrong here? Any help would be welcome! I also included code to generate representative pseudo data for 1000 records below:

import random
from numba import jit
import numpy as np
from __future__ import division

#Generate Random Data Set

ax_list=[]
sp_list=[]

for i in xrange(1000):
    n = random.randint(3,10)
    ax = []
    sp = [0]
    for i in xrange(n):
        a = round(random.uniform(8,32),1)
        ax.append(a)
    for i in xrange(n-1):
        s = round(random.uniform(4,30), 1)
        sp.append(s)
    ax_list.append(ax)
    sp_list.append(sp)

#Input Parameters
L=300
step_size=4
cstep_size=4
moment_list=[]

@jit
#Simple moment function
def Moment(x):
    if x<L/2.0:
        return 0.5*x
    else:
        return 0.5*(L-x)

#Attempt to vectorize the Moment function, hoping for speed gains
vectMoment = np.vectorize(Moment,otypes=[np.float],cache=False)

@jit
#Truck movement function that uses the vectorized Moment function above
def SimpleSpanMoment(axles, spacings, step_size):
    travel = L + sum(spacings)
    spacings=list(spacings)
    maxmoment = 0
    axle_coords =(0-np.cumsum(spacings))
    while np.min(axle_coords) < L:
        axle_coords = axle_coords + step_size
        moment_inf = np.where((axle_coords >= 0) & (axle_coords <=L), vectMoment(axle_coords), 0)
        moment = sum(moment_inf * axles)
        if maxmoment < moment:
            maxmoment = moment
    return maxmoment

Then to run the loop for 1000 times:

%%timeit
for i in xrange(len(ax_list)):
    moment_list.append(np.around(SimpleSpanMoment(ax_list[i], sp_list[i], step_size),1))

yields:

1 loop, best of 3: 2 s per loop


texts:
I have 856k addresses of pattern:

660 1st Ave   New York, NY 10016

(with 3 spaces between Ave and New York)

I need to parse and store parts as:

Street, City, State, Zip

I tried to split through regex but it was super slow, so I went traditional:

def splitAddress(address):
    split = '   '
    ad = address.strip()

    try:
       if(split in ad):
           addr = ad.split(split)
           if(len(addr)==2):
                addr1 = addr[1].strip().split(",")
                if len(addr1)==2:
                      addr2 = addr1[1].strip().split(" ")

                      if len(addr2)==2:
                           return addr[0], addr1[0], addr2[0], addr2[1]
                      else:
                           return "0","0","0","0"
                else:
                     return "0","0","0","0"
           else:
               return "0","0","0","0"
       else:
           return "0","0","0","0"
    except ValueError as e:
          print(addr[0], addr1[0], addr2[0], addr2[1])
          print(e)

I then got the parts as:

df['STREET'],df['CITY'], df['STATE'], df['ZIP'] = zip(*df['ADDRESS'].map(splitAddress))

But this is turning out to be pretty slow (it takes 18 mins for 856k addresses).


texts:
(repost: https://stackoverflow.com/questions/59665338/censoring-words-in-lua#comment105491094_59665338, as advised)

Im currently making a discord censor bot for my friend, and I was wondering if anyone with experience could help me, or if theres an easier way to complete my code.

local BadWords = {
    ['poop']=true,
}

client:on('messageCreate', function(msg)
    Msg = msg.content
    local msgs = string.split(Msg,' ')
    for i,v in pairs(msgs) do
        if BadWords[v:lower()] then
            msg:reply({
                embed = {
                    fields = {
                    {name = "Bad Word",value=v,inline = true},
                    },
                    color = discordia.Color.fromRGB(114, 137, 218).value,

                    --footer = os.time(),
                }
            })
            --msg:reply(('Blacklisted word: %s'):format(v))
        end
    end
    --[[table.foreach(msgs,function(i,v)
        if BadWords[i] or BadWords[v] then
            msg:reply(('Blacklisted word: %s'):format(v))
        end
    end)--]]
end)
client:run(Settings.Token)

There's nothing wrong with it, nor is it complete but my idea was to split, or concatenate all the words they send respectively, mutate into all versions of the word (i.e. farm, f4rm, type shit) and then checking the BadWord list.

Mostly what I was wondering was if there's a more efficient way to do this, or if I just gotta do what I gotta do


texts: Random retrievable number based on day and month

texts:
I wrote a function to get a 2-digit random number for each day, but it should be retrievable.
For example, today's random number is 72, but later I can provide "day and month" and get this 72 again.
function ranDay($day,$month){

    $pow1 = round(pow($day,$day))*$month;
    $pow2 = round(pow($day,$day))+$month;

    $dig1 = intval(substr($pow1,0,1));
    $dig2 = intval(substr($pow2,-1));

    echo $dig1.$dig2;
}

Now if I provide 27 and 1, I get 48 and I can get this number again later.
Am I doing this right?
The only issue I see in my code is that I can't get 0 for the first digit, and it would be nice to cover that too.
Please review this and tell me if I should consider doing something else.
EDIT:
Based on the accepted answer in ended up using this code instead:
function hashDay($day, $month) {
    echo substr(hexdec(substr(hash('sha256',($month.$day)),0,15)),-2);
}

reason i used 2 substr is amazingly when i used -2 instead of 0,15 in first substr, i got 1-3 digits instead of always 2 digits...


texts: Finding indices of numbers that sum to a target

texts:
I've taken this algorithm question, which is to find the indexes of any two numbers in an array that sum to a given number. It is quite a simple problem to solve. But it is the execution time of my code algorithm that bugs me.

#include <iostream>
#include <vector>
using namespace std;

class TwoSum
{
public:
  static std::pair<int, int> findTwoSum(const std::vector<int>& list, int TargetSum)
  {
    for (int increment = 0; increment < list.size(); increment++)
    {
        for (int i = 0; i < list.size(); i++)
        {
            if (list.at(increment) + list.at(i) == TargetSum)
            {
                return make_pair(increment, i);
            }
        }
    }
    return make_pair(-1, -1);
  }
};

int main(int argc, const char* argv[])
{
   vector<int> list = {1, 3, 5, 7, 9 };
   int targetSum = 12;
   pair<int, int> indices = TwoSum::findTwoSum(list, targetSum);

   indices.first == -1 && indices.second == -1 ?
   cout << "No vector elements can be added to achieve the target sum" << endl :
   cout << "The target sum can be achieved by adding the vector element " << indices.first << " and " << indices.second;
   cout << endl;

   return 0;
}

It is guaranteed correct as I tested it with the website's compiler (or whatever you call it), they can test your code just by pasting and running it on their code editor. I tested this on my IDE as well, and it worked fine.

The problem is, my code failed the performance test when dealing with large number of vector elements as it took longer than the website's expectation. For me, the function named findTwoSum()is already straightforward. And I don't have any idea how to optimize this function. Note that the test's focus here is the function itself and how fast it executes.

Any modifications in function's return type and parameter is not allowed. As the website stated that you cannot modify the main function's contents, implying that you cannot also change how the function is called.

But I slightly modified the main function for you to know what the program is trying to achieve.


texts:
Below is an implementation of Dijkstra's shortest path algorithm. It's input graph is represented as an association list of source nodes to assoc of target node and arc weight.

My question is about the following, am I missing a way of simplifying min-path function used in reduce? Maybe the great and powerful loop could do reduce's job?

(defun dijkstra (source target graph)
  (labels ((min-path (&optional arc-1 arc-2)
             (let ((price-1 (cdr arc-1))
                   (price-2 (cdr arc-2)))
               (cond
                 ((and (not (null arc-1)) (not (null arc-2))) (if (< price-1 price-2)
                                                                arc-1 arc-2) )
                 ((and (not (null arc-1)) (null (arc-2))) arc-1)
                 ((and (not (null arc-2)) (null (arc-1))) arc-2))))
           (get-best-path (visited)
             (reduce #'min-path (loop for pick in visited
                                      for start = (car pick)
                                      for cost = (cdr pick)
                                      append (loop for arc in (cdr (assoc start graph))
                                                   when (null (assoc (car arc) visited))
                                                   collect (cons (car arc) (+ cost (cdr arc))))))))
    (loop named main-loop
          with visited = (list (cons source 0))
          for best-arc = (get-best-path visited)

          when (not (null best-arc))
          do (push best-arc visited)
          until (or (null best-arc)
                  (eql (car best-arc) target))
          finally
          (format t "Found shortest path from ~A to ~A: ~A~%" source target best-arc)
          (return-from main-loop (cdr best-arc)))))

I'm new to Lisp, and I would appreciate any advice, especially on bad Lisp habits and  bad Lisp style in my code, thanks.

UPD: new version with review comments applied - no warnings, unlike the original version.

(defun dijkstra (source target graph)
  (labels ((min-path (&optional arc-1 arc-2)
             (cond ((and arc-1 arc-2) (if (< (cdr arc-1) (cdr arc-2)) arc-1 arc-2))
                   (arc-1 arc-1)
                   (arc-2 arc-2)
                   (t nil)))
           (get-best-path (visited)
             (reduce #'min-path
                     (loop for pick in visited
                           for start = (car pick)
                           for cost = (cdr pick)
                           append (loop for arc in (cdr (assoc start graph))
                                        unless (assoc (car arc) visited)
                                        collect (cons (car arc) (+ cost (cdr arc))))))))
    (loop with visited = (list (cons source 0))
          for best-arc = (get-best-path visited)
          when best-arc do
          (push best-arc visited)
          until (or (null best-arc) (eql (car best-arc) target))
          finally (return (cdr best-arc)))))


texts: jQuery make DRY two almost identical on click function

texts:
Is there a simple way to DRY this jQuery code?

  $('ul.icons li.size').click(function() {
    $('ul.icons li.size').not(this).removeClass('selected');
    $(this).toggleClass('selected');
  });

  $('ul.icons li.color').click(function() {
    $('ul.icons li.color').not(this).removeClass('selected');
    $(this).toggleClass('selected');
  });


texts: Python3 BFS Flood Fill with Deque and 2D Indexing

texts:
I'm currently in a programming competition where time is key, therefore I'm trying to optimize my solution as much as possible. I am trying to implement a BFS Flood Fill solution on a map size of 30x30 (900 operations) where the time limit is 1 second. I'm falling a bit short on time (a little bit above 1 second). I changed all my lists into a deque (for speed) and I changed my 1D list into a 2D list for faster indexing. I'm trying to calculate the distance for each node to every other node so that I can just look it up later on.

What else can I try to get a bit of speed?

Here is my BFS Function:

def BFS5(grid, start):
    visited = deque([])
    for _ in range(height):
        visited.append(deque([-1]*width))

    queue = deque([start])
    _x, _y = start.x, start.y
    visited[_y][_x] = 0
    distance = 1
    while queue:
        current_point = queue.popleft()
        if grid[current_point.y][current_point.x] == -1:
            continue

        adjacent_points = current_point.get_adjacents(grid)
        for point in adjacent_points:
            if grid[point.y][point.x] == -1:
                continue
            if visited[point.y][point.x] >= 0:
                continue
            _x, _y = point.x, point.y
            visited[_y][_x] = distance
            queue.append(point)
            distance += 1
    return visited

Grid example:

[
    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
    [-1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1],
    [-1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1],
    [1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1],
    [-1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1],
    [1, 1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1],
    [-1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1],
    [1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1],
    [-1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1],
    [-1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1],
    [-1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1],
    [-1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1],
    [-1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1],
    [-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1],
    [-1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1],
    [-1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1],
    [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
]


texts:
As with my other question this is regarding my Kalaha solver.

Currently the way I find out the optimal progression of moves is with a command like this:

snd $ head $ reverse $ sortByMostInStore $ pickAllPaths $ generatePotList 4

The snd is there to just get the list of moves from the ([Pot], [Int]) pair and the reverse is there because the sorting is ascending. My main problem is that pickAllPaths is really taking every possible path. This results in manageable execution time for generatePotList 5 with 17352 paths, but bring it up to 6 marbles in each pot and that results in 7657399 paths, which takes a significantly longer time to compute.

-- The [Int] is the list of starting positions you picked up marbles from.
pickAllPaths :: [Pot] -> [([Pot], [Int])]
pickAllPaths startingListOfPots = resultingPotsAndPaths where
    resultingPotsAndPaths = branchLoop startingListOfPots []

    branchLoop :: [Pot] -> [Int] -> [([Pot], [Int])]
    branchLoop listOfPots pathTaken
        | null validStartingPositions = [(listOfPots, pathTaken)]
        | otherwise = loopHelper validStartingPositions listOfPots pathTaken []
        where
            validStartingPositions = map position $ filter (not . isPotEmpty) potsOwnedByPlayer
            potsOwnedByPlayer = take 6 listOfPots

    loopHelper :: [Int] -> [Pot] -> [Int] -> [([Pot], [Int])] -> [([Pot], [Int])]
    loopHelper [] _ _ returnList = returnList
    loopHelper (x:xs) listOfPots pathTaken returnList
        | not $ landsInStore = loopHelper xs listOfPots pathTaken combinedList
        | otherwise = branchLoop resultingPots (pathTaken ++ [x]) ++ loopHelper xs listOfPots pathTaken returnList
        where
            (resultingPots, landsInStore) = makeStartingMove listOfPots x
            combinedList = ((resultingPots, (pathTaken ++ [x])) : returnList)

Since I'll generally only be interested in the three best (and maybe worst) paths, which is less than 1% of all the calculated paths, I'm sure there must be a better way of doing this.

Is there a way to avoid unnecessary recursion?


texts: Summation of Arithmetic Progression Modulo Series

texts:
Here is the link to the problem: Aladin on Kattis.com

  Problem

  Aladin was walking down the path one day when he found the strangest
  thing: N empty boxes right next to a weird alien machine. After a bit
  of fumbling around he got the machine to do something. The machine now
  accepts 4 integers \$L\$, \$R\$, \$A\$ and \$B\$. After that hitting the big red
  glowing button labeled "NE DIRAJ"1 causes the machine to go crazy and
  follow the next routine:

  Set the number of stones in the box labeled L to A modulo B.
  It proceeds to fly to the box labeled L + 1, and set the number of stones there to (2 ⋅ A) mod B.
  It procedes to fly to the box labeled L + 2, and set the number of stones there to (3 ⋅ A) modB.
  Generally, it visits each box labeled between L and R, and set the number of stones there to ((X − L + 1) ⋅ A) mod B, where X is the box label.
  After it visits the box labeled R. It settles down for further instructions.

  During the game Aladin wonders what is the total number of stones in some range of boxes.

  Write a program that simulates the device and answers Aladin's questions.

  Input

  The first line contains two integers: the number of boxes \$N\$ (\$1 \le N \le 1000000000\$) and the number of queries \$Q\$ (\$1 \le Q \le 50000\$).

  The next \$Q\$ lines contain information about the simulation.

  If the line starts with 1, than it follows the format "1 L R A B"
  (\$1 \le L \le R \le N\$) (\$1 \le A, B \le 1000000\$), meaning that Aladin keyed in numbers \$L\$, \$R\$, \$A\$ and \$B\$ in the device and allowed the device to do its job.

  If the line starts with 2, then it follows the format "2 L R"
  (\$1 \le L \le R \le N\$), meaning that Aladin wonders how many stones in total are
  ther stones are in boxes labeled \$L\$ to \$R\$ (inclusive).

  Output

  For each query beginning with 2 output the answer to that particular query. Queries should be processed in the order they
  are given in the input.

  Sample Input 1

6 3
2 1 6
1 1 5 1 2
2 1 6

  Sample Output 1

0
3

  Sample Input 2

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

  Sample Output 2

3
2
1
0

  Sample Input 3

4 4
1 1 4 7 9
2 1 4
1 1 4 1 1
2 1 4

  Sample Output 3

16
0

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

long countStones(long, long, long, long, long, long);

int main(int __argc, char *__argv[])
{
    std::string filepath;
    long N, Q, *boxes;

  if(__argc == 2) {
    filepath = std::string(__argv[1]);
  }

  std::ifstream* infile = !filepath.empty() ? new std::ifstream(filepath.c_str()) : static_cast<std::ifstream*>(&std::cin);

  *infile >> N >> Q;

  long opt, L1 = 0, R1 = 0, L2 = 0, R2 = 0, A, B;

  for(long i = 1; i <= Q; i++) {
    *infile >> opt;

    if(opt == 1) {
      *infile >> L1 >> R1 >> A >> B;
    }
    if(opt == 2) {
      *infile >> L2 >> R2;
      cout << countStones(L1, R1, L2, R2, A, B) << endl;
    }
  }

    return 0;
}

long countStones(long L1, long R1, long L2, long R2, long A, long B) {
  long ret = 0, start = L1, end = R1;

  if(R2 < L1) return 0;
  if(L2 > R1) return 0;

  if (L2 > L1) start = L2;
  if (R2 < R1) end = R2;

  for(long i = start; i <= end; i++) {
    ret += ((i - L1 + 1) * A) % B;
  }

  return ret;
}

The problem works fine with all the with Sample Cases #1, #2, & #3. But when I upload the code on the website (open.kattis.com) it fails on the case #4, which is unknown to me. I couldn't find a logical error in my code.

Also, when I had written the code which was storing the modulo calculations for each box (array) the problem did pass the case #4 but failed #5 (Memory Exceeded). So I changed the code to NOT STORE the values in the array & just calculate on the fly & add it to the count of stones.

I need to modify the code so that it passes Test #4, whose input values are unknown to me. That is to find the logical error in the code.


texts: Asking for feedback, when utilizing Pandas, why is it better to use pandas.Series than lists data type?

texts:
I found out the hard way, when utilizing pandas is better to use pandas.Series than lists data type to manipulate data.
Even if I understood how pandas stores different data types, I did not realize the ramification of using lists of strings instead of pandas.Series of objects.
Pandas dtype

Like the pic above shows, pandas store strings as objects, it does not discriminate between strings, lists, dictionaries and etc, python iterable.
I made my own function that returns a pandas.DataFrame column names, columns' pandas dtypes and columns' python data types, see pic below.

Most pandas.DataFrames that I encountered have a NaN values representing any values that are undefined.
A pandas.DataFrame column of string objects, first_names for example, can contain NaN values, NaN is a float data type.
The main reason that the NaN value is commonly utilize, it is due to its usefulness, when combine with a function like DataFrame.dropna(), it becomes a well recognize and powerful tool for data manipulation.
Most pandas teaching materials utilize lists and pandas.DataFrames to manipulate data, so I did the same, see code below:
    # Removes Html code and \n
    for name in essay_names:
        # Initializes essay text list
        essay_txts = []
        for essay in profiles[name]:
            # Checks if the essay is empty, NaN
            if type(essay) == type(.0):
                # Adds NaN text to the essay texts Series, empty text
                essay_txts.append(np.NaN)
            else:
                essay_clean = re.sub('', '', essay).replace('\n', ' ').replace('  ', ' ')
                essay_txts.append(essay_clean)
        # Stores cleaned essay text
        profiles[f'{name}_text'] = essay_txts

The code lines essay_txts = [] and essay_txts.append(np.NaN) create issues when trying to manipulating the DataFrames data with DataFrame.dropna(), the essay_txts is a list of strings, the np.nan value was not saved in the list as a float but as string, 'nan', and by consequence it was also saved in the DataFrame as a string.
The DataFrame.dropna() function will not recognize the value as NaN float and it will not drop the DataFrame row where the values was inputted.
Replacing the code lines
essay_txts = []
essay_txts.append(np.NaN)
with
essay_txts = pd.Series(dtype='object')
essay_txts = essay_txts.append(pd.Series(np.NaN), ignore_index=True)
is my solution to the issues created by using lists and trying to utilize the NaN value to manipulate data with pandas.
See full code below
    # Removes Html code and \n
    for name in essay_names:
        # I use pandas Series, a Series will accept NaN float and object (string) values
        essay_txts = pd.Series(dtype='object')
        for essay in profiles[name]:
            # Checks if the essay is empty, NaN
            if type(essay) == type(.0):
                # Adds NaN text to the essay texts Series, empty text
                essay_txts = essay_txts.append(pd.Series(np.NaN), ignore_index=True)
            else:
                essay_clean = re.sub('', '', essay).replace('\n', ' ').replace('  ', ' ')
                essay_txts = essay_txts.append(pd.Series(essay_clean), ignore_index=True)
        # Stores cleaned essay text
        profiles[f'{name}_text'] = essay_txts
Thank you for feedback, or for sharing a better way to address the issues created by using lists and trying to utilize the NaN value to manipulate data with pandas.


texts: Implementing multiprocessing to compare large number of entries in a python dictionary

texts:
I am a beginner in python programming, and I am trying to implement multiprocessing to the code I use daily for my data treatment. Essentially, the input file has around 10 - 30 millions of reads where each read contains 4 lines of information. There are two elements in the first line of every four lines that I am looking at. First I search if the first element is in the dictionary. If not, then I add to the dictionary the first element is the key while the second element is the value. But if the first element is already in the dictionary, I proceed to compare whether the second element is within the value list corresponding to the key. Similarly, if the second element is not already present in the list of values, it will be added, otherwise it is considered a duplicate.
Now as you can see, the dictionary is going to grow as more lines are read. In the end, it will just be too slow for a single process to complete the task efficiently. For my data it sometimes can take a week to do finish. Now I have a simple understanding that if I can implement something such multiple processes can be utilized to simultaneously compare with my dictionary, it would speed things up significantly (I can reserve as many as 16 CPU threads dedicated to my task). But unfortunately, multiprocessing/multithreading seems to be a complicated thing. I would appreciate if someone can direct me a path on what should I be focusing on.
Below is the code that I am currently using:

def sequence_mismatch (input_seq, input_dict, input_linker_length, j):
    local_smm_list=[]
    for stored in input_dict[input_seq[0:j:]]:
        local_smm=0
        for x in range(0, 7):
            if input_seq[input_linker_length+j+x] != stored[x]:
                local_smm += 1
        local_smm_list.append(local_smm)
    if min(local_smm_list) == 0:
        return 1
    else:
        return 0

# Main
from datetime import datetime
import itertools
import sys
try:
    input_fastq = sys.argv[1]
    linker_length_str = sys.argv[2]
    output_file_name = sys.argv[3]
    randomer_length = sys.argv[4]
except:
    print("Usage: ./PCRDupRm.py your_fastq.fastq linker_length output_file_name randomer_length")
    sys.exit(1)
startTime = datetime.now()
linker_length=int(linker_length_str)
i = int(randomer_length)
output_file = open(output_file_name, 'w+')
scanned_dict = {}
with open (input_fastq, 'r') as seq_data:
    for line1, line2, line3, line4 in itertools.izip_longest(*[seq_data]*4):
        if line2[0:i:] not in scanned_dict:
            scanned_dict.update({line2[0:i:]: [line2[(linker_length + i):(linker_length + i + 7):]]})
            output_file.write(line1)
            output_file.write(line2)
            output_file.write(line3)
            output_file.write(line4)
        else:
            comparison = sequence_mismatch (line2, scanned_dict, linker_length, i)
            if comparison == 1:
                continue
            else:
                scanned_dict[line2[0:i:]].extend([line2[(linker_length + i):(linker_length + i + 7):]])
                output_file.write(line1)
                output_file.write(line2)
                output_file.write(line3)
                output_file.write(line4)

output_file.close()
print (datetime.now() - startTime)


texts: String template using concrete implementation instead of external library

texts:
Q1: What are the benefits of using any external library e.g Antlr3.StringTemplate?

Q2: What are the potential issues with the below implementation?

public class StringTemplate
{
    private string text = string.Empty;
    public StringTemplate(string template)
    {
        this.text = template;
    }

    public StringTemplate SetAttribute(string attribute, object value)
    {
        text = text.Replace($"${attribute}$", value?.ToString() ?? "");
        return this;
    }
    public override string ToString()
    {
        return text.ToString();
    }
}

And use it like below

 private void writeMsg()
 {
     var email = "Dear $name$...";//Loading from html file place holder used pattern $placeholder$.

     var template =
         new StringTemplate(email)
         .SetAttribute("name", "John");

     Console.WriteLine(template.ToString());
 }


texts: Parent with N-Childs where each child can have N-Childs

texts:
I know my question sounds strange but I have a situation in which I have Parent Data  which can have 'N' Childs and each child can further have N-Childs and so on.

So its Like.

Parent

a. Child

    i. Child
    ii. Child

b. Child

    i.Child

I hope I've made myself Clear. So here is a snapshot of the Database Table:

So I have wrote this Code to get my Data From Database. It is a recursive Function:

public static List<CaseCommunication> GetCaseCommunicationByCustomerCaseId(int customerCaseId)
        {
            var parentCaseCommunications =
                EntityHandler.GetEntitiesContext().CaseCommunications.Where(x => x.CustomerCaseId == customerCaseId && x.ParentCaseCommunicationId == null);

            var mappedParentCommuncations = Mapper.Map<IEnumerable<CaseCommunication>>(parentCaseCommunications).ToList();

            foreach (var parent in mappedParentCommuncations)
            {
                parent.ChildCommunications = GetListOfChildCommunicationsByParentId(parent.CaseCommunicationId);
            }

            return mappedParentCommuncations;
        }

        public static List<CaseCommunication> GetListOfChildCommunicationsByParentId(int caseCommunicationId)
        {
            var childCommunications =
                EntityHandler.GetEntitiesContext().CaseCommunications.Where(x => x.ParentCaseCommunicationId == caseCommunicationId);

            var mappedChild = Mapper.Map<IEnumerable<CaseCommunication>>(childCommunications).ToList();

            foreach (var child in mappedChild)
            {
                child.ChildCommunications = GetListOfChildCommunicationsByParentId(child.CaseCommunicationId);
            }

            return mappedChild;
        }

This is the function called from the other class: GetCaseCommunicationByCustomerCaseId

While GetListOfChildCommunicationsByParentId  is the recursive function.

I was just need to know is there a better way of writing this?

Is this efficient?


texts:
I'm trying to define a function which takes an array and prints it to a predefined total width in as many columns as needed. Think of the way ls prints files for example.

Here is the kind of output I am looking for:

$ ./print-columns.py

Files
    /home/stephen/dev/src/cmake-browser/cmakeclient.cpp    /home/stephen/dev/src/cmake-browser/projectsources.cpp
    /home/stephen/dev/src/cmake-browser/main.cpp           /home/stephen/dev/src/cmake-browser/includesmodel.cpp
    /home/stephen/dev/src/cmake-browser/mainwindow.cpp     /home/stephen/dev/src/cmake-browser/definesmodel.cpp
    /home/stephen/dev/src/cmake-browser/debugwidget.cpp    /home/stephen/dev/src/cmake-browser/highlighter.cpp
    /home/stephen/dev/src/cmake-browser/projecttree.cpp    /home/stephen/dev/src/cmake-browser/helpviewer.cpp
    /home/stephen/dev/src/cmake-browser/projectmodel.cpp   /home/stephen/dev/src/cmake-browser/main.cpp
    /home/stephen/dev/src/cmake-browser/projectcode.cpp    /home/stephen/dev/src/cmake-browser/helpviewer.cpp
    /home/stephen/dev/src/cmake-browser/projectdetail.cpp

Targets
    KF5ItemModels                    kdescendantsproxymodel_smoketest klinkitemselectionmodeltest
    krecursivefilterproxymodeltest   kselectionproxymodel_smoketest   kselectionproxymodeltest
    proxymodeltestapp                proxymodeltestsuite              testmodelqueuedconnections

I created the following script to do that. I'm trying to brush up on my Python, and re-learn how to write pythonic code in the most modern way (latest Python 3), and it doesn't feel very pythonic (and it's not the kind of code I usually write).

#!/usr/bin/env python3

import sys, subprocess, json, math

def col_print(title, array):
  print()
  print()
  print(title)

  indent = " " * 4

  if not array:
    print(indent + "<None>")
    return

  padsize = 1
  # Hardcoded for this example
  termwidth = 150

  maxitemwidth = len(max(array, key=len))

  numCols = int((termwidth + padsize) / (maxitemwidth + padsize))

  numRows = int(math.ceil(len(array) / float(numCols)))

  pad = " " * padsize

  for index in range(numRows):
    print(indent + pad.join(item.ljust(maxitemwidth) for item in array[index::numRows]))

col_print("Files",
          ["/home/stephen/dev/src/cmake-browser/cmakeclient.cpp",
          "/home/stephen/dev/src/cmake-browser/main.cpp",
          "/home/stephen/dev/src/cmake-browser/mainwindow.cpp",
          "/home/stephen/dev/src/cmake-browser/debugwidget.cpp",
          "/home/stephen/dev/src/cmake-browser/projecttree.cpp",
          "/home/stephen/dev/src/cmake-browser/projectmodel.cpp",
          "/home/stephen/dev/src/cmake-browser/projectcode.cpp",
          "/home/stephen/dev/src/cmake-browser/projectdetail.cpp",
          "/home/stephen/dev/src/cmake-browser/projectsources.cpp",
          "/home/stephen/dev/src/cmake-browser/includesmodel.cpp",
          "/home/stephen/dev/src/cmake-browser/definesmodel.cpp",
          "/home/stephen/dev/src/cmake-browser/highlighter.cpp",
          "/home/stephen/dev/src/cmake-browser/helpviewer.cpp",
          "/home/stephen/dev/src/cmake-browser/main.cpp",
          "/home/stephen/dev/src/cmake-browser/helpviewer.cpp"]
)

col_print("Targets",
          ["KF5ItemModels",
          "krecursivefilterproxymodeltest",
          "proxymodeltestapp",
          "kdescendantsproxymodel_smoketest",
          "kselectionproxymodel_smoketest",
          "proxymodeltestsuite",
          "klinkitemselectionmodeltest",
          "kselectionproxymodeltest",
          "testmodelqueuedconnections"]
)

Can you help write a better col_print function?


texts:
I've tried to roll out my own HyperScript implementation. I would be interested in any suggestions to improve it or point me to any other better implementation which is still maintained. I checked the HyperScript project, but it doesn't seem to have any recent updates, so I tried this:

var DOM = {
    h: function(tagName, props, children) {
        var element = document.createElement(tagName);
        if (props) {
            for (var item in props) {
                element[item] = props[item];
            }
        }
        if (children && Array.isArray(children) && children.length > 0) {
            children.forEach(function(child) {
                element.appendChild(child);
            });
        }
        return element;
    },
    div: function(props, children) {
        return this.h('div', props, children);
    },
    label: function(props, children) {
        return this.h('label', props, children);
    },
    input: function(props, children) {
        return this.h('input', props, children);
    },
    button: function(props, children) {
        return this.h('button', props, children);
    },
    li: function(props, children) {
        return this.h('li', props, children);
    }
};

Usage:

DOM.button({ className: "destroy" });


texts:
This function was hard to write as a Clojure newbie, and I don't like the result.
Can you help me find a better (more readable) way to do it?

(defn split-seq
  "Splits a seq into blocks defined by start-fn and stop-fn.
  Returns a lazy seq of seqs"
  [start-fn stop-fn lines]
  (let [step (fn [c state]
                 (when-let [s (seq c)]
                   (if (stop-fn (first s))
                     (cons state (split-seq start-fn stop-fn (rest s) ))
                     (recur (rest s)
                        (if (start-fn (first s))
                            '()
                            (cons (first s) state))))))]
    (lazy-seq (step lines '()))))

(defn post-start? [l] (.startsWith l "#ENTRY_START"))
(defn post-end? [l] (.startsWith l "#ENTRY_END"))

(defn split-lines
    "Split a line-seq into entries based on #ENTRY_START and #ENTRY_END."
    [data]
    (split-seq post-start? post-end? data))

;
; Test
;
(def test-data [
    "Header line"
    "#ENTRY_START"
    "entry line 1 "
    "entry line 2"
    "#ENTRY_END"
    "This line should be filtered out"
    "#ENTRY_START Having data here shouldn't make a difference."
    "entry line 1 "
    "entry line 2"
    "#ENTRY_END"
    "This should be gone too"])

(split-lines test-data)

; yields (("entry line 2" "entry line 1 ") ("entry line 2" "entry line 1 "))
; The order of elements doesn't matter in my case because I'm making a map with this data

With Arthurs help, the final code looks like this:

(defn entry-seq [data]
    (let [[f r] (split-with #(not (post-end? %))
                  (rest (drop-while #(not (post-start? %)) data)))]
      (when (not-empty f) (lazy-seq (cons f (entry-seq2 r))))))

Still lazy and a lot more readable!


texts: Probe for open application on a TCP port

texts:
I need to examine an application port to see if it opens and I need to put the retry count as a parameter. Since I'm new to Node I wanted to get your feedback on it
for improvements.

checkAppPr: function (port) {
        var result = Promise.defer();
        var checkStatus = function (next, result, times) {
            portscanner.checkPortStatus(port, '127.0.0.1', function (error, status) {
                if (error) {
                    result.reject(error);
                } else {
                    if (status === 'open') {
                        console.log("Application status: open");
                        result.resolve();
                    } else {
                        times--;
                        if (times > 0) {
                            setTimeout(function () {
                                next(next, result, times);
                            }, 1000);
                        } else {
                            result.reject("start timeout");
                        }
                    }
                }
            })
        }
        checkStatus(checkStatus, result, 20);
        return result.promise;
    }


texts: Generate all possible combinations of letters in a word

texts:
This is a JavaScript function that returns ALL the possible combinations of whatever word the user enters. I am looking to clean this code up a bit...any and all suggestions are welcome!

  function allAnagrams (word) {
  if (word.length < 2) {
    return [word];
  } else {
      var allAnswers = [];
      for (var i = 0; i < word.length; i++) {
        var letter = word[i];
        var shorterWord = word.substr(0, i) + word.substr(i + 1, word.length - 1);
        var shortwordArray = allAnagrams(shorterWord);
        for (var j = 0; j < shortwordArray.length; j++) {
          allAnswers.push(letter + shortwordArray[j]);
        }
      }
      return allAnswers;
  }
}

allAnagrams("")


texts: Display image from live webcam as taken, with four different color filters and in B/W

texts:
I have a live webcam windows which means there are six subdivided windows in a single window live. And show pictures in colored and black and white. Is there anyway I can make the code minimalistically minimized? I believe the code is considerably long.

import cv2
import cv
import numpy as np
import matplotlib.image as mpimg
from matplotlib import pyplot as plt

def threshold_slow(T, image):
    # grab the image dimensions
    h = image.shape[0]
    w = image.shape[1]
    d = image.shape[2]
    # loop over the image, pixel by pixel
    for y in range(0, h):
        for x in range(0, w):
            for z in range(0, d):
                # threshold the pixel

                if image[y, x,z] >= T:
                    image[y, x,z] = 255
                else:
                    image[y, x,z] = 0

    # return the thresholded image
    return image
def grab_frame(cam):

    #cv2.namedWindow("test")

    #img_counter = 0

    while True:
        ret, color1 = cam.read()
        #r = 100.0 / color1.shape[1]
        r = 640.0 / color1.shape[1]
        #r = 0.25
        dim = (100, int(color1.shape[0] * r))
        dim = (640,480)
        # perform the actual resizing of the image and show it
        color = cv2.resize(color1, dim, interpolation = cv2.INTER_AREA)

        #color = color1.copy()
        b = color.copy()
        # set green and red channels to 0
        b[:, :, 1] = 0
        b[:, :, 2] = 0

        g = color.copy()
        # set blue and red channels to 0
        g[:, :, 0] = 0
        g[:, :, 2] = 0

        r = color.copy()
        # set blue and green channels to 0
        r[:, :, 0] = 0
        r[:, :, 1] = 0

        #y= color.copy()
        #gray = cv2.cvtColor(l,cv2.COLOR_RGB2GRAY)
        #_,y = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)
        #y = cv2.cvtColor(y, cv2.COLOR_GRAY2RGB)

        y = cv2.add(r,g)

        d = color.copy()
        gray1 = cv2.cvtColor(d,cv2.COLOR_RGB2GRAY)
        _,p = cv2.threshold(gray1, 60, 255, cv2.THRESH_BINARY)
        p = cv2.cvtColor(p, cv2.COLOR_GRAY2RGB)
        #threshold_slow(220,p)
        return [color,b,g,r,y,p]

cam = cv2.VideoCapture(0)

    #cv2.waitKey(0)
while(1):
    ret, color = cam.read()
    [color,b,g,r,y,p] = grab_frame(cam)
    horiz = np.hstack((color,b,g))
    #verti = np.vstack((color,r))
    horiz1 = np.hstack((r,y,p))
    verti = np.vstack((horiz,horiz1))
    cv2.imshow('HORIZONTAL', verti)

    if not ret:
        break
    k = cv2.waitKey(1)

    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break

cam.release()

cv2.destroyAllWindows()


texts: An imitation of reading a C Struct from binary file in python 2.7

texts:
Preliminary

I need to read a binary file constructed by writing a Struct to it with Python. So I decided to write a simple wrapper using struct module.

Code

import struct

class structure:
    def __init__ ( self, little_endian = True ):
        self._little_endian = little_endian

        self._table  = dict() #stores field name, its format and value
        self._pack  = list()  #stores field names in order fields must be read

    def add_field( self, field_name, field_format ):
        if field_name in self._table.keys():
            print "WARNING :: Field with name '%s' already exists in this structure" % field_name
        elif field_format == "":
            print "WARNING :: Format cannot be an empty string"
        else:
            self._table[ field_name ] = { "format" : field_format, "value" : None }
            self._pack.append( field_name )
        #maybe error handling is required here

    def get_value( self, field_name ):
        try:
            return self._table[ field_name ][ "value" ]
        except KeyError:
            print "WARNING :: There is no such field named '%s' in this structure" % field_name
            return None

    def get_format_string( self ):
        f_str = ""

        for key in self._pack:
            f_str += self._table[ key ][ "format" ]

        if (self._little_endian == True):
            f_str = "<" + f_str
        else:
            f_str = ">" + f_str

        return f_str

    def get_size( self ):
        return struct.calcsize( self.get_format_string() )

    def fill( self, file_ptr ):
        result = struct.Struct( self.get_format_string() ).unpack( file_ptr.read( self.get_size() ) )
        for (i,key) in enumerate(self._pack):
            self._table[ key ][ "value" ] = result[ i ]

    def show( self ):
        print "General info:"
        print "%20s = %s"  % ( "Format string", self.get_format_string() )
        print "%20s = %d" % ( "Size (bytes)", self.get_size() )
        print "Value:"
        for key in self._pack:
            print "%20s = " % key, self._table[ key ][ "value" ]

Usage

Usage is straightforward. I used the real binary produced by OWON oscilloscope here so some of the values might look strange (consist non-printable characters).

import structure

s = structure.structure( little_endian=True )
s.add_field( "header", "10s" )
s.add_field( "serial", "14s" )
s.add_field( "string", "18s" )
s.add_field( "trig_time", "f" )
s.add_field( "float1", "f" )
s.add_field( "float2", "f" )

with open( "./data/trigger.bin" ) as f:
    s.fill( f )

s.show()

Output

General info:
       Format string = <10s14s18sfff
        Size (bytes) = 54
Value:
              header =  SPBS01e�
              serial =  SDS60621715234
              string =
           trig_time =  99.0
              float1 =  3.41239206136e-06
              float2 =  0.001953125

As always any suggestions, ideas and critics are appreciated.


texts:
I'm not a scripting expert by any means, but I put together some code that I needed for Google Sheets. The good news is that it actually works!

However, it's noticeably slow to run (about 15 seconds).  I'm sure it's not optimized to deal with arrays and other fun things that I don't fully understand...

function ShowHideClosedCards() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var lastRow = sheet.getLastRow();

  strVisible = sheet.getRange('N1').getValue(); //Get the value of N1
  if (strVisible == '** Closed accounts are visible **') { //If the closed accounts are visible...
      for( i=6 ; i<=lastRow ; i++) { // Start with row 6 and continue through the last row: i <= lastRow
       var status = sheet.getRange("F"+i).getValue(); //Get the value of the cell.
       if (status !== "") { // If there's something in the "Date Closed" cell, then that should mean it's closed
         sheet.hideRows(i); // Hide the row
       }
       }
       sheet.getRange('N1').setValue('** Closed accounts are hidden **');
  } else {  // Otherwise, assume the closed accounts are hidden...
       for( i=6 ; i<=lastRow ; i++) { // Start with row 6 and continue through the last row: i <= lastRow
       var status = sheet.getRange("F"+i).getValue(); //Get the value of the cell.
       if (status !== "") { // If there's something in the "Date Closed" cell, then that should mean it's closed
         sheet.showRows(i); // Show the row
       }
       }
       sheet.getRange('N1').setValue('** Closed accounts are visible **');
  }
}

The gist of it is that it should go through each row (from 6 through 500) and if there's anything in column F of that row, hide the row.  Then it marks one cell (N1) to let the user know that the closed accounts are hidden.

If the user runs the code again, it should do the same thing, but unhide those rows (and only those rows).  Then it marks N1 again to let the user know that the closed accounts are visible.

Any suggestions on how to get it to run faster?


texts:
I am playing a bit with vanilla JavaScript and created a simple JavaScript calculator using eval().  Any suggestions for improvements?

var keys = document.getElementsByClassName('number'),
    getTotal = document.getElementById('showTotal'),
    btnReset = document.getElementById('reset'),
    visor = document.getElementById('visor');

for (var i = 0; i < numbers.length; i++) {
  numbers[i].onclick = addNum;
}

getTotal.onclick = showResult;
btnReset.onclick = clearVisor;

function addNum() {
  visor.value += this.value;
}

function showResult() {
  var total = 0;
  total = visor.value;
  visor.value = '';
  visor.value = eval(total);
}

function clearVisor() {
  visor.value = '';
}

<form name="calc">

    <input type="text" name="visor" id="visor">

    <input type="button" class="keys" value="7"> <input type="button" class="keys" value="8"> <input type="button" class="keys" value="9">

    <input type="button" class="keys" value="4"> <input type="button" class="keys" value="5"> <input type="button" class="keys" value="6">

    <input type="button" class="keys" value="1"> <input type="button" class="keys" value="2"> <input type="button" class="keys" value="3">

    <input type="button" class="keys" value="/"> <input type="button" class="keys" value="*"> <input type="button" class="keys" value="-">

    <input type="button" class="keys" value="+"> <input type="button" id="reset" value="c"> <input type="button" id="showTotal" value="=">

  </form>


texts:
I have this ExpressJS route for saving and listing Category model.

exports.save = function(req, res, next){
  //validate here>>>
  var name = req.body.name;
  var description = req.body.description;

  new Category({
    name: name,
    description: description,
  }).save(function(err, docs){
    if ( err ) {
      console.log('error: saving category');
      next(error);
    }else{
      console.log('category saved.');
      res.redirect('categories');
    }
  });
}

exports.list = function(req, res, next){
  Category.find(function ( err, categories, count ){
    if (err) {
      console.log('error: listing categories');
      next(error);
    }
    res.render( 'categories/list', {
        categories : categories
    });
  });
}

Is having console.log and next(error) OK?  How could I improve the above code in terms of conventions in NodeJS / ExpressJS?


texts:
I think I got the implementation right, but I'm a bit unsure if this implementation will do fine in terms of space (stack) because I'm doing a foldRight. Would I want to use foldLeft if e.g. I wanted to execute flatMap on a large list? Also, any other suggestion for improvement would be appreciated.

Note: I understand there are standard libraries, this is for my own practice

sealed trait List[+A]

case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]

object List {
  @tailrec
  final def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = {
    l match {
      case Nil => z
      case Cons(x, xs) => foldLeft(xs, f(z, x))(f)
    }
  }

  def reverse[A](xs: List[A]):List[A] = {
    foldLeft(xs, Nil:List[A])((b,a)=>Cons(a,b))
  }

  def append[A](l1: List[A], l2: List[A]): List[A] = {
    def f(acc: List[A], x2:A): List[A] = {
      x2 match {
        case Nil => acc
        case x => Cons(x, acc)
      }
    }
    foldLeft(l2,l1)(f)
  }

  def map[A,B](l: List[A])(f: A => B): List[B] = {
    reverse(foldLeft(l, Nil:List[B])((b,a) => Cons(f(a), b)))
  }

  def foldRight[A,B](l: List[A], z: B)(f: (A, B) => B): B = {
    l match {
      case Nil => z
      case Cons(x, xs) => f(x, foldRight(xs, z)(f))
    }
  }

  def flatMap[A,B](l: List[A])(f: A => List[B]): List[B] = {
    foldRight(l, Nil:List[B])((a, b) => append(b, reverse(f(a))))
  }

}


texts:
This CAPTCHA is not text but basically images of objects that the users has to identify between an array of options. My current code is kind-of slow because the query takes almost .7s to execute and it has to run three times.

I'm looking for a way to improve it and make it faster.

// Loop through to display the pictures and options
for ($i = 0; $i < 2; $i ++) {
    $answers = array();

    // Fill an array with 5 random objects unique objects
    $result = mysqli_query($link, "SELECT MAX(captcha_images.image_code) AS image_code, captcha_objects.name FROM captcha_objects LEFT JOIN captcha_images ON captcha_images.object_id = captcha_objects.id WHERE captcha_images.approved = 1 GROUP BY captcha_objects.name ORDER BY RAND() LIMIT 5") or die(mysqli_error($link));
    while($row = mysqli_fetch_assoc($result)) $answers[] = array("code" => $row['image_code'], "name" => $row['name']);

    // Pick the first one as the correct answer
    $_SESSION['captcha_ans'][] = $answers[0];
    $chosen_objects_id[] = mysqli_get_value("id", "captcha_objects", "name", $answers[0]['name'], false);

    // Shuffle 'em
    shuffle($answers);

    // show picture
    $image = ImageCreateFromString(base64_decode($_SESSION['captcha_ans'][$i]['code']));

    // Generate the output of the image, encode it and include it as a data URI
    ob_start();
    imagejpeg($image);
    $base64 = base64_encode(ob_get_contents());
    ob_end_clean();
    echo '

<select name="answer[]"><option value=""></option>';

    // show answers
    foreach ($answers as $answer)
        echo '<option value="'.$answer['name'].'">'.$answer['name'].'</option>';

    // close options
    echo '</select>
';
    unset($answers);
}


texts: Dynamically resizing panels based on browser window size

texts:
I've just finished building my responsive carousel currently trying to optimize my code to make it more efficient. I've created a number of if conditions in my carousel, what does it sets the sizes of each elements based on the condition. Is there a way to reduce the number of if statements.

    var carouselWidth = 0,
        slider = $('.carousel .slider'),
        carouselContainerWidth = $('.carousel').width(),
        carouselPanel = $('.carousel .slider .panel'),
        browserWindow = $(window),
        sliderWidth = $('.carousel .slider').width();

    //Set Different Size of Image Panels based on Browser Size
    ///////////////////////////////////////////////////////////

    //Display 5 Panels
    if ($(browserWindow).width() >= 1500 ) {
        var setPanelWidth = carouselPanel.outerWidth( carouselContainerWidth / 5, true ),
            panelSize = setPanelWidth.outerWidth();
    }

    //Display 4 Panels
    if ($(browserWindow).width() < 1500) {
        var setPanelWidth = carouselPanel.outerWidth( carouselContainerWidth / 3, true ),
            panelSize = setPanelWidth.outerWidth();
    }

    //Display 3 Panels
    if ($(browserWindow).width() < 1120) {
        var setPanelWidth = carouselPanel.outerWidth( carouselContainerWidth / 2, true ),
            panelSize = setPanelWidth.outerWidth();
    }

    //Display 1 Panels
    if ($(browserWindow).width() < 768) {
        var setPanelWidth = carouselPanel.outerWidth( carouselContainerWidth / 1, true ),
            panelSize = setPanelWidth.outerWidth();
    }


texts: Print largest/smallest no (even, odd) from user defined list of given size

texts:
After reviews of my previous codes 1st, 2nd learned many new things. So with those in mind, this is my solution for another question.

Question: Write a program that ask user for list size and values and find largest and smallest no, even no, odd no?
Expected output: For user defined list,

[13, 7, 19, 21, 3, 4, 27, 47, 50, 11] -> 50, 3, 50, 4, 47, 3

[2, 4, 6, 8, 10] -> 10, 2, 10, 2, None, None

[1, 3, 5, 7, 9] -> 9, 1, None, None, 9, 1

Format: largest_no, smallest_no, largest_even, smallest_even, largest_odd, smallest_odd

My solution:
def largest_and_smallest(given_list):
    """Extracts required numbers from given_list.

    >>> largest_and_smallest([13, 7, 19, 21, 3, 4, 27, 47, 50, 11])
    (50, 3, 50, 4, 47, 3)

    >>> largest_and_smallest([2, 4, 6, 8, 10])
    (10, 2, 10, 2, None, None)

    >>> largest_and_smallest([1, 3, 5, 7, 9])
    (9, 1, None, None, 9, 1)

    """
    sorted_list = sorted(given_list)
    largest_no = max(sorted_list)
    smallest_no = min(sorted_list)

    list_of_even = [even_no for even_no in sorted_list if ((even_no % 2) == 0)]
    if len(list_of_even) == 0:
        largest_even = None
        smallest_even = None
    else:
        largest_even = max(list_of_even)
        smallest_even = min(list_of_even)

    list_of_odd = [odd_no for odd_no in sorted_list if ((odd_no % 2) != 0)]
    if len(list_of_odd) == 0:
        largest_odd = None
        smallest_odd = None
    else:
        largest_odd = max(list_of_odd)
        smallest_odd = min(list_of_odd)

    return largest_no, smallest_no, largest_even, smallest_even, largest_odd, smallest_odd

def input_handler():
    """Checks validity of input. Any mistakes causes the program to stops."""
    size = input("Enter a size of list?\n>")
    if size.strip() == "":
        exit("Program Terminated. (No Input)")
    elif size.isdigit():
        list_size = int(size)
        list_of_no = [int(input("Enter value:")) for _ in range(list_size)]  # bad input causes error.
        return list_size, list_of_no
    else:
        exit("Program Terminated. (Bad Input)")

def main():
    print("All input should be integers.")
    list_size, list_of_no = input_handler()
    l_no, s_no, l_even, s_even, l_odd, s_odd = largest_and_smallest(list_of_no)
    print()
    print(f"From provided values of list of a size {list_size}:")
    print(f"Largest no.: {l_no}, Smallest no.: {s_no}, Largest even no.: {l_even}, "
          f"Smallest even no.: {s_even}, Largest odd no.: {l_odd}, Smallest odd no.: {s_odd}")
    return

if __name__ == '__main__':
    import doctest
    doctest.testmod(main())

So, from this review I would like to know:

I have used list comprehension as per suggestion in previous code, have I used that correctly? For example, I made separate list for even and odd numbers could I have done that in different way?

I made a separate function to handle input is that a bad practice? What is the best way to handle inputs, that checks different corner cases?

If there is any recommendations going forward from this will help me a lot.


texts: Sum of all the primes less than or equal to N

texts:
public static long sumOfPrimes(long max){
    long sum = 0;
    long primes[] = new long[((int)max/2)+1];
    int index = 0;
    for(long counter = 2; counter <= max; counter++){
        if(isPrime(counter, primes)){
            sum += counter;
            primes[index++] = counter;
        }
    }
    return sum;
}

public static boolean isPrime(long num, long[] primes){
    if(num == 2 || num == 3){
        return true;
    }

    //System.out.println(Arrays.toString(primes));
    long primesCount = primes.length;
    for(int i = 0; i < primesCount; i++){
        if(primes[i] !=0 && num % primes[i] == 0){
            return false;
        }
    }

    long range = (long) Math.sqrt((double)num);
    if(primesCount > 0 && primes[primes.length-1] < range)
    {
        for(long counter = 2; counter <= range; counter++){
            if(num % counter == 0){
                return false;
            }
        }
    }
    return true;
}

This code works fine for smaller N. For larger N, it throws timeout exception.

How can I improve my code? How do I fix timeout issue?


texts:
In this program, there is a code that the user has to try to solve in 10 guesses.  If you have any numbers in the right spot, it will tell you how many you have correct and the value of the correct numbers so you can figure it out.
I know there has to be a much simpler way to do this, I just can't put one together.  I could use arrays (although i'm not the best with them yet) to find certain values, but i'm not positive on how to do that.  Any tips?
(I apologize in advance for any sloppy coding or poor choice of variable names.  Also this is in a main method, i just didn't copy the class name or the main method)

    String code = "53492";
    int guesses = 10;
    Scanner s12 = new Scanner(System.in);
    System.out.println("Try to guess the 5 number code. You have 10 guesses: ");
    String guess = s12.nextLine();
    int right = 0;
    int combo = 0; //correct values combined
    int correctInt = 0;

    for(int i = 0; i < 10; i++) //will allow you to guess a certain amount of times
    {
        combo = 0;
        right = 0;
        for(int x = 0; x < 5; x++) //starts searching at first spot(0)
        {
            int guessInt = Integer.parseInt(guess);
            int codeInt = Integer.parseInt(code);
            String getCorrectInt = guess.substring(x, x + 1);
            correctInt = Integer.parseInt(getCorrectInt);  //stores value of num at the value of
            String getCodeGuess = code.substring(x, x + 1);
            int codeGuess = Integer.parseInt(getCodeGuess);
                if(guessInt == codeInt)
                {
                    System.out.println("Correct! You guessed it!");
                    System.exit(0);
                }
                if(correctInt == codeGuess)  //if the num at the position matches the code at the right position
                {
                    combo += correctInt;    //totals up the correct amount of numbers in right spot
                    right++; //keeps track of how many are right
                }
        }
        guesses--;
        System.out.println("You have " + right + " number(s) correct that equal to " + combo + " and you have " + guesses + " guesses left.");
        System.out.println("Guess again: ");
        guess = s12.nextLine();
    }
    System.out.println("You ran out of guesses!  The code was " + code);


texts: Check if strings are substrings of another string in Python

texts:
My problem starts with a list A (length around n = 100) of big strings (around 10000 characters each). I also have another q = 10000 strings of length 100. I want to check if each string is a substring of any element of the list A.

I've tried to do this using inor any but it is still taking too much time as there are 10000 iterations and in each iteration I'm checking if s of length 100 is in str of length 10000.

n,q=[int(item) for item in input().split()]
desc=[]
for i in range(n):
    desc.append(input())
desc="\t".join(desc)
for j in range(q):
    quest=input().strip()
    if quest in desc:
        print("It's in !")
    else:
        print("It's not in ..")

Is there any better way to do this much faster?

Note: The numbers I'm expliciting are upper bounds not exact values of the lengths.


texts: Using a decorator to apply an inherited method to all child objects of the inherited type

texts:
I wanted to share this and get some feedback.  My goal was to be able to have an object with methods:

class Thing(object):
    def __init__(self, data=123):
        self.data = data

    def add_one(self):
        self.data += 1

    def add_number(self, number):
        self.data += number

And then a collection object, MetaThing that can hold several Thing objects, which inherits from Thing like this:

class MetaThing(Thing):

    def __init__(self):
        super(MetaThing, self).__init__()

        self.list = [1, 2, 3, 4, 5]
        self.things = []
        self.setupThings()

    def setupThings(self):

        for i in self.list:
            thing = Thing(data=i)
            self.things.append(thing)

Finally, I want to be able to apply the methods in Thing to all the Thing instances stored in MetaThing.things when those same methods are called on MetaThing.

Doing this explicitly creates methods like this:

    def add_one(self):
        for t in self.things:
            t.add_one()

    def add_number(self, number):
        for t in self.things:
            t.add_number(number)

So I started wondering if this would be a good situation for a decorator, so I wrote one that I think does what I want:

def allthings(func):
    def new_func(*args, **kwargs):
        self = args[0]
        for thing in self.things:
            arglist = list(args)
            arglist[0] = thing
            func(*arglist, **kwargs)

    return new_func

So now, the MetaThing method can use the @allthings decorator to call an inherited method on all child objects without rewriting the for loop every time:

class MetaThing(Thing):

    def __init__(self):
        super(MetaThing, self).__init__()

        self.list = [1, 2, 3, 4, 5]
        self.things = []
        self.setupThings()

    def setupThings(self):

        for i in self.list:
            thing = Thing(data=i)
            self.things.append(thing)

    @allthings
    def add_one(self):
        self.add_one()

    @allthings
    def add_number(self, number):
        self.add_number(number)

Finally this block verifies that it's working:

if __name__ == '__main__':

    meta = MetaThing()

    meta.add_one()

    print [t.data for t in meta.things]

    meta.add_number(5)

    print [t.data for t in meta.things]

Is this a valid approach? Is there a better way to achieve this? Am I crazy for using decorators in this way?

My actual scenario is a PlottedShape with lots of methods like plot, delete, update, select, apply_opacity, apply_color, apply_wireframe, etc. and I also have a PlottedMultiShape made up of multiple shapes (like a snowman shape made of multiple circles).  If PlottedMultiShape.select() is called I want to call select on all the child PlottedShape objects -- and I'd like this same behavior for all of the other methods as well.  Using a decorator seemed like a good "Don't Repeat Yourself" tactic.


texts: PHPmailer sanitazion/validation a second oppinion.

texts:
I wonder if someone could give me some pointers to my PHPmailer Process file and see if they find any misstakes or things that I have missed in the validation/sanitation of the data.
Any input would be most wellcome!

<?php
//includes
require_once('func/mail/mailcon/config-info.php');
require_once('include/class.phpmailer.php');
//Sanitazion and cleanup.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$entries = array();
$errors = array();
// Escape and extract all the post values
foreach ($_POST as $key => $value) {
    $entries[$key] = sanitize($value);
}

// Get a set of variable variables for easier use
foreach ($entries as $key => $value) {
    ${$key} = $value;
}
//validation
//contact_Name
if (empty($contact_Name)) {
$errors['contact_Name'] = 'Detta fält måste fyllas i.';
}
elseif (mb_strlen($contact_Name, 'UTF-8') > 50) {
$errors['contact_Name'] = 'Detta namn är för långt, får inte vara över 50 tecken.';
}
//contact_Foretag.
if (mb_strlen($contact_Foretag, 'UTF-8') > 50) {
$errors['contact_Foretag'] = 'Detta företagsnamn är för långt, får inte vara över 50 tecken';
}
//contact_Email
if (empty($contact_Email)) {
$errors['contact_Email'] = 'Detta fält måste fyllas i.';
}
elseif (!(filter_var($contact_Email, FILTER_VALIDATE_EMAIL))) {
$errors['contact_Email'] = 'Fyll i en giltig E-post address.';
}
//contact_Subject
if (empty($contact_Subject)) {
$errors['contact_Subject'] = 'Detta fält måste fyllas i.';
}
elseif (mb_strlen($contact_Subject, 'UTF-8') > 50) {
$errors['contact_Subject'] = 'Detta ämne är för långt, får inte vara över 50 tecken.';
}
//contact_Message
if (empty($contact_Message)) {
$errors['contact_Message'] = 'Detta fält måste fyllas i.';
}
elseif (mb_strlen($contact_Message, 'UTF-8') > 5000) {
$errors['contact_Message'] = 'Detta meddeoande är för långt, får inte vara över 5000 tecken.';
}

//If no errors
if (empty($errors)) {

$formOK = true;
$mail = new PHPMailer(true);

try {
  $mail->IsSMTP();
  $mail->SMTPDebug = 0;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = "ssl";
  $mail->Host = MAIL_HOST;
  $mail->Port = MAIL_PORT;
  $mail->Username = MAIL_USER;
  $mail->Password = MAIL_PASS;
  $mail->SetFrom($contact_Email, $contact_Name);
  $mail->Subject = "$contact_Subject";
  $mail->Body = "Your received the following message from $contact_Mame ($contact_Foretag)   <$contact_Email>:\r\n\r\n$contact_Message";
  $mail->AddAddress(MAIL_ADDR);
  $mail->Send();

 } catch (PHPMailerException $e) {
 header("HTTP/1.1 500 Internal Server Error");
        echo "Exception occurred: ".$e->errorMessage();
        exit();
 }
}
else {
    $formOK = false;
}

//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
    session_start();
    $return_data = array(
        'formOK'  => $formOK,
        'errors'  => $errors,
        'entries' => $entries
    );
    $_SESSION['return_data']  = $return_data;
    header('Location: ' . BASE_URL);
    exit();
}
} //First
else {
header('Location: ' . BASE_URL);
exit();
}


texts: Find out how many laptops Molly can buy based on available money, array of quantities and array of costs

texts:
Problem description:

  Molly wants to purchase laptops for her school. Find out how many laptops she can purchase by comparing the vendors available.
  Each vendor sells the laptops in batches, with a quantity identifying how many laptops on each batch, and a cost for the whole batch.
  Sample input: 50 [20,19] [24,20]
  That means Molly has 50 dollars to spend. The first vendor has 20 laptops per batch and each batch costs 24 dollars. The second vendor has 19 laptops per batch and each batch costs 20 dollars.
  The possible answers are 40 and 38. If she buys from the first vendor, she will spend 48 dollars (24 * 2) and since she's buying 2 batches the total quantity is 40 (20 * 2).
  If however she would buy from the second vendor, the maximum quantity would be 38, since each batch has 19 laptops and she'd run out of money after the second batch.
  The final answer is then 40, since 40 is higher than 38.
  This seems similar to the Knapsack problem.

My solution is listed below. The permute method is there to generate the possible permutations between the indices. For instance if we have 3 items in the input array the permutations are:
012 021 102 120 201 210

import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.stream.IntStream;

public class ShoppingBudget {

  public static void main(String[] args) {
    ShoppingBudget sb = new ShoppingBudget();
    assertEquals(40, sb.budgetShopping(50, List.of(20, 19), List.of(24, 20)));
    assertEquals(20, sb.budgetShopping(4, List.of(10), List.of(2)));
    assertEquals(0, sb.budgetShopping(1, List.of(10), List.of(2)));
    assertEquals(41, sb.budgetShopping(50, List.of(20, 1), List.of(24, 2)));
  }

  private void permute(int start, int moneyAvailable, int[] inputIndices,
      List<Integer> budgetQuantities, List<Integer> budgetCosts, MaxQuantity maxQuantity) {
    if (start == inputIndices.length) { // base case

      int possibleMax = findSolution(inputIndices, moneyAvailable, budgetQuantities, budgetCosts);

      maxQuantity.value = Math.max(maxQuantity.value, possibleMax);

      return;
    }
    for (int i = start; i < inputIndices.length; i++) {
      // swapping
      int temp = inputIndices[i];
      inputIndices[i] = inputIndices[start];
      inputIndices[start] = temp;
      // swap(input[i], input[start]);

      permute(start + 1, moneyAvailable, inputIndices, budgetQuantities, budgetCosts, maxQuantity);
      // swap(input[i],input[start]);

      int temp2 = inputIndices[i];
      inputIndices[i] = inputIndices[start];
      inputIndices[start] = temp2;
    }
  }

  private int findSolution(int[] inputIndices, int moneyAvailable,
      List<Integer> budgetQuantities, List<Integer> budgetCosts) {
    int remaining = moneyAvailable;
    int counter = 0;

    for (int index : inputIndices) {
      if (remaining == 0) {
        break;
      }

      int quantity = budgetQuantities.get(index);
      int cost = budgetCosts.get(index);

      if (cost <= remaining) {
        int howManyToBuy = remaining / cost;
        counter += howManyToBuy * quantity;
        remaining -= (howManyToBuy * cost);
      }
    }

    return counter;
  }

  private int budgetShopping(int n, List<Integer> budgetQuantities,
      List<Integer> budgetCosts) {
    int[] inputIndices = IntStream.rangeClosed(0, budgetQuantities.size() - 1).toArray();
    MaxQuantity maxQuantity = new MaxQuantity();
    maxQuantity.value = Integer.MIN_VALUE;
    permute(0, n, inputIndices, budgetQuantities, budgetCosts, maxQuantity);

    return maxQuantity.value;
  }
}

class MaxQuantity {
  int value;
}


texts: Batch Processing : Design check with SRP and OCP prinicple

texts:
I have to create a batch process which reads data from DB , process it and saves it in db . The batch data is fetched organization wise ( each organization has set of data to be processed) at once.We need to process only specific set of data i.e organization related and save it into db. Hence i have designed below classes . Does this design breaks SRP and OCP?

Should the process method in DepositProcess have the code to iterate the batch data ?

Batch Processor Interface

package com.ibank.batch;

public interface BatchProcessor {

    public void process();

}

Deposit Processort class

package com.ibank.batch;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.ibank.batch.svc.DepositBatchProcessorSvc;

public class DepositProcessor implements BatchProcessor {

    @Override
    public void process() {
        DepositBatchProcessorSvc svc = new DepositBatchProcessorSvc();
        HashMap<String, List<String>> batchData = svc.fetchBatchData();
        Set<String> key = batchData.keySet();
        Iterator<String> keyItr = key.iterator();
        while (keyItr.hasNext()) {
            String organizationId = (String) keyItr.next();
            List<String> claimsList = batchData.get(organizationId);
            svc.saveBatchData(claimsList);
        }
    }

}

Service interface and implementation class

package com.ibank.batch.svc;

import java.util.List;

public interface BatchProcessorSvc {

    public Object fetchBatchData();

    public <T>  void  saveBatchData(List<T> data);

}

package com.ibank.batch.svc;

import java.util.HashMap;
import java.util.List;

public class DepositBatchProcessorSvc implements BatchProcessorSvc {

    @Override
    public HashMap<String, List<String>> fetchBatchData() {
        return null;

    }

    @Override
    public <String> void saveBatchData(List<String> claimList) {

    }

}

DAO interface and implementation

package com.ibank.batch.dao;

import java.util.List;

public interface BatchProcessorDao {

    public Object fetchBatchData();

    public <T>  void  saveBatchData(List<T> data);

}

package com.ibank.batch.dao;

import java.util.HashMap;
import java.util.List;

public class DepositBatchProcessorDao implements BatchProcessorDao {

    @Override
    public HashMap<String, List<String>> fetchBatchData() {
        return null;
    }

    @Override
    public <String> void saveBatchData(List<String> claimList) {

    }

}


texts:
I have made a simple program that tests if the given element exists in any STL container. The program tests if the container has a find member function. It will use it if it does. Otherwise, it will call the STL find function instead. I would like to know how I can improve it further?

#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <set>
#include <vector>
#include <array>
#include <type_traits>

template <typename C> decltype(std::declval<C>().find(0), std::true_type{}) test(int);
template <typename C> std::false_type test(...);
template <typename C> using has_find = decltype(test<C>(0));

template <bool B, typename T, typename F>
std::enable_if_t<std::integral_constant<bool, B>::value, T>
conditional(T&& t, F&&)
{
    return std::forward<T>(t);
}

template <bool B, typename T, typename F>
std::enable_if_t<!std::integral_constant<bool, B>::value, F>
conditional(T&&, F&& f)
{
    return std::forward<F>(f);
}

template <typename C, typename T>
auto contains(const C& container, const T& key)
{
    static auto first = [] (auto&& c, auto&& k)
    {
        return c.end() != c.find(k);
    };

    static auto second = [] (auto&& c, auto&& k)
    {
        return c.end() != std::find(c.begin(), c.end(), k);
    };

    auto op = conditional<has_find<C>::value>(first, second);

    return op(container, key);
}

int main()
{
    std::cout << std::boolalpha;

    std::array<int, 3> a = {{ 1, 2, 3 }};
    std::cout << contains(a, 0) << "\n";
    std::cout << contains(a, 1) << "\n\n";

    std::vector<int> v = { 1, 2, 3 };
    std::cout << contains(v, 0) << "\n";
    std::cout << contains(v, 1) << "\n\n";

    std::set<int> s = { 1, 2, 3 };
    std::cout << contains(s, 0) << "\n";
    std::cout << contains(s, 1) << "\n\n";

    std::map<int, int> m = { { 1, 1}, { 2, 2}, { 3, 3} };
    std::cout << contains(m, 0) << "\n";
    std::cout << contains(m, 1) << "\n";
}


texts:
This is a CodeEval challenge taken from here:

  Challenge description:

  Imagine we have an immutable array of size N which we know to be
  filled with integers ranging from 0 to N-2, inclusive. Suppose we know
  that the array contains exactly one duplicated entry and that
  duplicate appears exactly twice. Find the duplicated entry. (For bonus
  points, ensure your solution has constant space and time proportional
  to N)

  Input sample:

  Your program should accept as its first argument a path to a filename.
  Each line in this file is one test case. Ignore all empty lines. Each
  line begins with a positive integer(N) i.e. the size of the array,
  then a semicolon followed by a comma separated list of positive
  numbers ranging from 0 to N-2, inclusive):

1
2
5;0,1,2,3,0
20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14

  Output sample:

  Print out the duplicated entry, each one on a new line:

1
2
0
4

I've written this code:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 *
 * @author Mohammad Faisal
 */
public class ArrayAbsurdity {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new FileInputStream("E:\\java\\temp\\abc.txt"));
        while(input.hasNextLine()){
            String str = input.nextLine();
            if(str.equals("")){
                continue;
            }
            String[] in = str.split(";");
            int i=0;
            int[] a = new int[Integer.parseInt(in[0])];
            StringTokenizer token = new StringTokenizer(in[1], ",");
            while(token.hasMoreTokens()){
                a[i]=Integer.parseInt(token.nextToken());
                i++;
            }

            boolean success=false;
            for(i=0; i<a.length-1; i++){
                for(int j=i+1; j<a.length; j++){
                    if(a[i] == a[j]){
                        System.out.println(a[i]);
                        success=true;
                        break;
                    }
                }
                if(success){
                    break;
                }
            }
        }
    }
}

Can anybody review it and help me in improving the space and time complexity as per the problem?


texts:
I am doing some python practice and wrote a square code encoder/decoder. As described in drill #4 of Programming Practice Problems, the characters of a message are written left-to-right on a square grid, and each line of the encoded message is read by going top to bottom.

I'd like some feedback on what I wrote to see if there is anything I could have done better:

import math

def encode(message):
    message = message.replace(" ", "")
    square = math.ceil(math.sqrt(len(message)))

    # Create the "grid"
    rows = []
    for row in range(square):
        pos = row * square
        code = message[pos:pos + square]
        rows.append(code)

    print("The grid:\n{}".format("\n".join(rows)))

    # Encode the message
    coded_msg = ""
    for col in range(square):
        for row in range(square):
            # The last column of the last row will throw an out of range error, so handle that
            if col < len(rows[row]):
                coded_msg += rows[row][col]
        coded_msg += " "

    return coded_msg.rstrip()

def decode(message):
    square = math.sqrt(len(message))
    col_count = math.ceil(square)
    row_count = math.ceil(len(message) / col_count)

    cols = message.split(" ")

    decoded_msg = ""
    for row in range(row_count):
        for col in cols:
            if row < len(col):
                decoded_msg += col[row]

    return decoded_msg

if __name__ == "__main__":

    print("Gimme a message:")
    in_message = input()

    coded_message = encode(in_message)
    print("--\nSquare message:\n{}".format(coded_message))
    decoded_message = decode(coded_message)
    #print("--\nDecoded message:\n{}".format(decoded_message))

    print("--\ninput: {}\noutput: {}".format(in_message, decoded_message))


texts: Processing player's move in an ASCII rogue-like game

texts:
I'm making an ASCII roguelike game and while writing the code for processing the player's move I can't decide between these two options. I have defined a class named point to handle positions in the game, like this. I would also like to know if this is a good idea or if I should use a structure instead.

Should I pass an object as a parameter to a function or create it inside?

class point {
public:
    point();
    point(int x, int y);

    int getX() const;
    int getY() const;;

    void setX(int x);
    void setY(int y);

private:
    int x;
    int y;
};

OPTION 1

I define the target point object before calling the function.

point playerPos = player.get_position();
point moveTilePos;

switch (input) {
    case MOVE_UP:
        moveTilePos.setX(playerPos.getX());
        moveTilePos.setY(playerPos.getY()-1);
        processPlayerMove(player, moveTilePos);

which is defined as follows:

void Level::processPlayerMove(Player &player, point target) {

    char moveTileSymbol;

    moveTileSymbol = getTile(target);
    switch(moveTileSymbol){
        case WALL_SYMBOL:
            break;
        case GROUND_SYMBOL:
            setTile(player.get_position(), GROUND_SYMBOL);
            player.set_position(target);
            setTile(target, PLAYER_SYMBOL);
            break;
    }
}

I think this is more readable overall but requires a setup that maybe should be part of the function.

Option 2

Everything is handled by the function:

point playerPos = player.get_position();

switch (input) {
    case MOVE_UP:
        processPlayerMove2(player, playerPos.getX(), playerPos.getY() -1)

Which is defined like this:

void Level::processPlayerMove2(Player &player, int targetX, int targetY) {

    char moveTileSymbol;
    point target;

    target.setX(targetX);
    target.setY(targetY);

    moveTileSymbol = getTile(target);
    switch(moveTileSymbol){
        case WALL_SYMBOL:
            break;
        case GROUND_SYMBOL:
            setTile(player.get_position(), GROUND_SYMBOL);
            player.set_position(target);
            setTile(target, PLAYER_SYMBOL);
            break;
    }
}

This case is more succinct, as the function handles everything.


texts:
I'm building this website with PDO and Pattern MVC.  I'm currently working on the login page and would like to know if this structure is correct for MVC pattern.  I'd also like your opinions and advice on this.

For my login view I have:

<form action="test.php" name="loginform" method="post">
    <input type="text" name="login">
    <input type="password" name="password">
    <input type="submit" name="login_submit" value="Se connecter">
</form>

For my login controller I have:

if(isset($_POST['login_submit'])){
    if(!empty($_POST['login']) && !empty($_POST['password'])){
        $auth = new auth();
        $auth->setLogin($_POST['login']);
        $auth->setPassword(md5(sha1($_POST['password'])));
        if(($row = $auth->login('u_login,u_email,u_id_level', 'users', 'u_login', 'u_password'))){
            $_SESSION['back_office'] = array(
                'login' => $row->u_login,
                'email' => $row->u_email,
                'level' => $row->u_id_level
            );
        }else{
            message::showError('Compte non reconnu');
        }
    }else{
        message::showError('Veuillez remplir tous les champs');
    }
}

For my login model I have:

class auth{
    protected $rowUser;
    protected $login;
    protected $password;
    protected $email;

    public function setLogin($login){
        $this->login = $login;
    }
    public function setPassword($password){
        $this->password = $password;
    }
    /**
     * @return array $row
     */
    public function login($fields, $table, $col_login, $col_password){
        $query = Db::getInstance()->prepare('SELECT '.$fields.' FROM '.$table.' WHERE '.$col_login.' = :login AND '.$col_password.' = :password');
        $query->bindValue(':login',$this->login,PDO::PARAM_STR);
        $query->bindValue(':password',$this->password,PDO::PARAM_STR);
        $query->execute();
        if($query->rowCount() > 0){
            $row = $query->fetch();
            return $row;
        }else{
            return false;
        }
        $query->closeCursor();
    }
}


texts: DAO for fetching organizations and departments through a REST API

texts:
I have the following class structure:

public class CustomDAOImpl implements CustomDAO {

    public List<Organization> getOrganizations() {
        List<Organization> results = new ArrayList<Organization>();
        Client client = ClientHelper.createClient();
        Resources<OrganizationResource> response = client
                .target(restApiRoot + "organizations")
                .request(MediaType.APPLICATION_JSON)
                .get(new GenericType<Resources<OrganizationResource>>(){
                });
        List<OrganizationResource> resources = response.getContent();
        for (OrganizationResource resource : resources) {
            results.add(resource.getEntity());
        }
        return results;
    }

    public List<Department> getDepartments() {
        List<Department> results = new ArrayList<Department>();
        Client client = ClientHelper.createClient();
        Resources<DepartmentResource> response = client
                .target(restApiRoot + "departments")
                .request(MediaType.APPLICATION_JSON)
                .get(new GenericType<Resources<DepartmentResource>>(){
                });
        List<DepartmentResource> resources = response.getContent();
        for (DepartmentResource resource : resources) {
            results.add(resource.getEntity());
        }
        return results;
    }
}

The abstract class :

public abstract class ResourceSupport {
    @XmlElement(name="link")
    private List<Link> links;
}

Entities :

public class DepartmentResource extends ResourceSupport {
    @XmlElement(name="department")
    private Department entity;

    public Department getEntity(){
        return entity;
    }
}

public class OrganizationResource extends ResourceSupport {
    @XmlElement(name="organization")
    private Organization entity;

    public Organization getEntity(){
        return entity;
    }
}

I'm new to JAVA, so I am not familiar enough with generics.

How can I improve my approach to have cleaner more elegant code?

The code must compile in JAVA 7 platform.

EDIT

I tried something like this :

private <T, U> List<T> makeRequest(Class<T> clazz1, Class<U> clazz2, String path) {
    List<T> results = new ArrayList<T>();
    Client client = ClientHelper.createClient();
    Resources<U> response = client
            .target(restApiRoot + path)
            .request(MediaType.APPLICATION_JSON)
            .get(new GenericType<Resources<U>>(){
            });
    List<U> resources = response.getContent();
    ...
    return results;
}

invoke like this :

List<Organization> list = makeRequest(Organization.class, OrganizationResource.class, "organizations");

But i have now an java.lang.ClassCastExceptionjava.lang.ClassCastException:

Source : java.lang.reflect.Method cannot be cast to java.lang.Class
  at com.owlike.genson.reflect.TypeUtil.getTypes(TypeUtil.java:397)
  at com.owlike.genson.reflect.TypeUtil.match(TypeUtil.java:331)
  at com.owlike.genson.convert.BasicConvertersFactory.provide(BasicConvertersFactory.java:97)
  ...
  at com.owlike.genson.Genson.provideConverter(Genson.java:155)
  at com.owlike.genson.Genson.deserialize(Genson.java:387)
  at com.owlike.genson.ext.jaxrs.GensonJsonConverter.readFrom(GensonJsonConverter.java:122)


texts: Find a 2x2 vowel square in a grid (Coderbyte 'Vowel Square' problem)

texts:
My solution to the Coderbyte task 'Vowel Square'. It's a simple task, but I'm sure there's a more Pythonic solution than mine.

The problem:

Vowel Square
Have the function VowelSquare(strArr) take the strArr parameter being passed
which will be a 2D matrix of some arbitrary size filled with letters from
the alphabet, and determine if a 2x2 square composed entirely of vowels
exists in the matrix. For example: strArr is ["abcd", "eikr", "oufj"] then
this matrix looks like the following:

a b c d

e i k r

o u f j

Within this matrix there is a 2x2 square of vowels starting in the second
row and first column, namely, ei, ou. If a 2x2 square of vowels is found
your program should return the top-left position (row-column) of the square,
so for this example your program should return 1-0. If no 2x2 square of
vowels exists, then return the string not found. If there are multiple
squares of vowels, return the one that is at the most top-left position
in the whole matrix. The input matrix will at least be of size 2x2.

Examples:

Input: ["aqrst", "ukaei", "ffooo"]
Output: 1-2,
Input: ["gg", "ff"]
Output: not found

My solution:

VOWELS = "aeiouAEIOU"

def find_vowel_square(strs: list):
    """Return the top left grid ref of any 2x2 sq composed of vowels only

    If more than one 2x2 sq exists. Return that which is at the most top-left
    position.
    """
    height, width = len(strs), len(strs[0])

    # Ensure all strings within strs are of equal length
    assert all(len(s) == width for s in strs)

    for string_i in range(height-1):
        for i in range(width-1):
            if strs[string_i][i] in VOWELS and strs[string_i][i+1] in VOWELS:
                if strs[string_i+1][i] in VOWELS and strs[string_i+1][i+1] in VOWELS:
                    return f"{i}-{string_i}"

    return "Not found"

assert find_vowel_square(strs=["aqree", "ukaei", "ffooo"]) == "3-0"
assert find_vowel_square(strs=["aqrst", "ukaei", "ffooo"]) == "2-1"
assert find_vowel_square(strs=["gg", "ff"]) == "Not found"


texts:
Define a macro swap(t, x, y) that interchanges two arguments of type t.(Block structure will help.)

The ideea is that a variable defined in a block structure exists only inside the block structure. So, I can create a temporary variable without affecting the code.

Here is my solution:

#include <stdio.h>

#define swap(t, x, y) {t tmp = x; x = y; y = tmp;}

int main() {
    int x = 10, y = 2;
    swap(int, x, y);

    printf("%d %d", x, y);
    return 0;
}