texts:
I did this as an exercise just to practice/improve using generics.

Independent of how useful this implementation of a Singleton is, how is my coding in terms of using generics and any other aspect of class design of code style?

void Main()
{
    var a = Singleton<MyClass>.Value;
    var b = Singleton<MyClass, MyClassFactory>.Value;
    var c = Singleton<MyClass>.Value;
    var d = Singleton<MyClass, MyClassFactory>.Value;
    var e = Singleton<MyOtherClass>.Value;
    var f = Singleton<MyOtherClass>.Value;
    var g = Singleton<MyOtherClass, MyOtherFactory>.Value;
    var h = Singleton<MyOtherClass, MyOtherFactory>.Value;
}

class SingletonBase
{
    protected static object Locker = new LockerObject();
}

class Singleton<T> : SingletonBase where T : new()
{
    static T StaticT;

    public static T Value
    {
        get
        {
            lock (Locker)
            {
                if(StaticT == null)
                {
                    StaticT = Activator.CreateInstance<Factory<T>>().Create();
                }
                else
                {
                    Console.WriteLine ("Singleton<T>::Value" + typeof(T).Name + " is already created");
                }
            }
            return StaticT;
        }
    }
}

class Singleton<T, F> : SingletonBase where T : new() where F : IFactory<T>, new()
{
    static T StaticT;

    public static T Value
    {
        get
        {
            lock (Locker)
            {
                if(StaticT == null)
                {
                    StaticT = new F().Create();
                }
                else
                {
                    Console.WriteLine ("Singleton<T, F>::Value" + typeof(T).Name + " is already created");
                }
            }
            return StaticT;
        }
    }
}

class LockerObject
{
    Guid myGUID;
    public LockerObject()
    {
        this.myGUID = Guid.NewGuid();
        Console.WriteLine ("New LockerObject " + this.myGUID.ToString());
    }
}

interface IFactory<T>
{
    T Create();
}

class Factory<T> : IFactory<T> where T : new()
{
    public T Create()
    {
        Console.WriteLine ("Factory<T>::Create()");
        return new T();
    }
}

class MyClassFactory : IFactory<MyClass>
{
    public MyClass Create()
    {
        Console.WriteLine ("MyClassFactory::Create()");
        return new MyClass();
    }
}

class MyClass
{
    public MyClass()
    {
        Console.WriteLine ("MyClass created");
    }
}

class MyOtherClass
{
    public MyOtherClass()
    {
        Console.WriteLine ("MyOtherClass created");
    }
}

class MyOtherFactory : IFactory<MyOtherClass>
{
    public MyOtherClass Create()
    {
        Console.WriteLine ("MyOtherFactory::Create()");
        return new MyOtherClass();
    }
}

Output:

New LockerObject 36aa2282-d745-43ca-84d2-998a78e39d51
Factory<T>::Create()
MyClass created
MyClassFactory::Create()
MyClass created
Singleton<T>::ValueMyClass is already created
Singleton<T, F>::ValueMyClass is already created


texts:
I have a case that looks like this :

John has 120 candies, He needs some plastic bags and marks each plastic bag with the number and puts 50 candies in each bag. So John can only fill up to 3 plastic bags :
plastic bag 1 = 50 candies
plastic bag 2 = 50 candies
plastic bag 3 = 20 candies

I want to create a Hash from the above case. The first variable is 120 candies and second variable is 50 candies for each plastic bag. I have written a method to create a Hash like that :
def make_a_hash(candies, each_candies)
  mark_number = 1
  arry = []

  begin
    put_candy = candies / each_candy > 0 ? each_candy : candies
    candies = candies - put_candy
    arry << [mark_number, put_candy]
    mark_number += 1
  end while candies > 0
  arry.to_h
end

#=> make_a_hash(120, 50)
#=> {1=>50, 2=>50, 3=>20}

That method is working, and I would like to know if there is another best practice instead my method.


texts: How can I make this piece of code more secure?

texts:
I am using db_dataobject and have provided two examples of an insert and a select query below.

Can you please help me rewrite them in a more secure way using PDO?  Is there any other way to improve them?

INSERT

 $user= new DataObjects_user;
                        $user->username  = mysql_real_escape_string (strip_tags($_REQUEST['username']));
                        $user->password  =encryptpass(mysql_real_escape_string(strip_tags($_REQUEST['password'])));
                        $user->email  =mysql_real_escape_string(strip_tags ($_REQUEST['email']));
                        $user->dob  = mysql_real_escape_string(strip_tags($_REQUEST['dob']));
                        $user->member_since  = date("Y-m-d H:i:s");
                        $id = $user->insert();

SELECT

$username= mysql_real_escape_string (strip_tags($_REQUEST['username']));
    $password=encryptpass($_REQUEST['password']);
    $user= new DataObjects_user;
    $password=mysql_escape_string(($password));

    $user->query("select activated,userid,email,username from {$user->__table} where (username = '$username' or email='$username') AND password = '$password' ");

    if($user->fetch())
    {


texts: Weighted graph from a matrix (list-of-lists)

texts:
I created this code while solving the Euler Project problem 83.

  In the 5 by 5 matrix below, the minimal path sum from the top left to
  the bottom right, by moving left, right, up, and down, is indicated in
  bold red and is equal to 2297.

  Find the minimal path sum, in matrix.txt (right click and "Save
  Link/Target As..."), a 31K text file containing a 80 by 80 matrix,
  from the top left to the bottom right by moving left, right, up, and
  down.

I have a matrix with weights stored as a list-of-lists. The task is to traverse the matrix from the top-left element to the bottom right element. At every point, I can go up, down, left or right. The problem is to find the path with the minimal summed weights.

To answer this, I converted the matrix to a graph (Make_Graph), represented as a dictionary in Python. The key in the dictionary is the string row_index, column_index (Name_Name). My next step in solving the Euler problem (not shown here) is to use Dijkstra's algorithm to find the shortest path.

I'm an amateur Python enthusiast, not a professional programmer. I have the feeling that Make_Graph can be made more Pythonic, but I don't know how. It looks a bit messy to me.

def node_name(row_index, col_index):
    return str(row_index)+","+str(col_index)

def make_graph(matrix):
    graph={}
    for rowindex,row in enumerate(matrix):
        for colindex,value in enumerate(row):
            graph[node_name(rowindex,colindex)]={}
            # Up
            if rowindex>0: graph[node_name(rowindex,colindex)][node_name(rowindex-1,colindex)]=matrix[rowindex-1][colindex]
            # Down
            if rowindex<len(matrix)-1: graph[node_name(rowindex,colindex)][node_name(rowindex+1,colindex)]=matrix[rowindex+1][colindex]
            # Left
            if colindex>0: graph[node_name(rowindex,colindex)][node_name(rowindex,colindex-1)]=matrix[rowindex][colindex-1]
            # Right
            if colindex<len(row)-1: graph[node_name(rowindex,colindex)][node_name(rowindex,colindex+1)]=matrix[rowindex][colindex+1]
    return graph

print make_graph([[1,2],[3,4],[5,6]])


texts: Find All Substrings Interview Query in C++

texts:
The following is my code for printing all the substrings of an input string. For example, with "abc", it would be "a","ab","abc","b","bc","c". Could someone please review it for efficiency (and possibly suggest alternatives)?

void findAllSubstrings(const char *s){
    int x=0;
    while(*(s+x)){
        for(int y=0; y<=x; y++)
            cout<<*(s+y);
        cout<<'\n';
        x++;
    }
    if(*(s+1))
        findAllSubstrings(s+1);
    else
        return;
}


texts: Even Fibonacci numbers under 4,000,000 (Project Euler #2)

texts:
Prompt:

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

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

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

I'd like advice on:

Using mathematical formulas instead of loops to calculate this
Making the code more efficient

This is my solution:

   function EvenFibonacciNumbers(){
            var value=parseInt(document.getElementById("input").value);
            var sum=0;
            var temp=0;
            var num2=1;
            var num1=1;

            while(num2<value){
                temp=num1+num2;
                num1=num2;
                num2=temp;
                if(num2%2==0){
                    sum+=temp;
                }
            }

            //document.getElementById("output").value=sum;
            alert("result ="+sum);
        }


texts:
I've written the code below to display a list of tasks from a Flask API. The form and associated .ajax method post to the API, immediately appending the data to the list of tasks. The code is working, but I'm fairly new to jquery and am curious if my code could be improved.

<title>Home</title>

Add Task

<form id="task-form">
    <input id="title" type="text">
    <input id="description" type="text">
    <button type="submit">Submit</button>
</form>


texts: Python search for array in large text file


texts: Profile picture upload method in Laravel 5.2

texts:
I am a Laravel newbie so please forgive me for my code... I have a method, in a Laravel controller, that updates the current logged user profile (postProfileGeneral()).
Logged user can upload a profile picture, and I manipulate the uploaded file (i.e. remove spaces, create unique name, etc.); since I'd like to reuse the upload routine, I put it on a separate method (_upload())
The code is this:

// get a unique file name
protected function _getUniqueFilename($path, $filename, $extension)
{
    $i = 2;
    $output = $filename . '.' . $extension;
    while(File::exists($path . '/' . $output)){
        $output = $filename . '_' . $i . '.' . $extension;
        $i++;
    }
    return $output;
}

// upload method, to reuse the routine
protected function _upload(Request $request, $field, $path = '')
{
    $path = ($path != '') ? $path : public_path();
    if ($request->hasFile($field)){
        $file = $request->file($field);
        if ($file->isValid()){
            $basename = $file->getClientOriginalName(); // get the original filename + extension
            $extension = $file->getClientOriginalExtension(); // get the original extension without the dot
            $filename = basename($basename, '.' . $extension); // get the original filename only
            $slug = str_slug($filename, '-'); // slug the original filename
            $name = $this->_getUniqueFilename($path, $slug, $extension);
            $file->move($path, $name);
            $output = $path . $name;
        }
    } else {
        $output = $request->input('cur_picture');
    }
    return $output;
}

// update profile
public function postProfileGeneral(Request $request)
{
    $picture = $this->_upload($request, 'picture', config('custom.users_path'));
    dd($picture);
    // rest of method here, not relevant
}

It works fine, but I feel there is a better way of doing this
My questions are:

since the getUniqueFilename() and _upload() method can be reused in other controllers too (i.e. for uploading products pictures, or whatever) where should I put them to be generally available?
in the getUniqueFilename() method I must pass Request object as a parameter: is there a better way to do this? At last, I yet have my Request object available in the postProfileGeneral() method...


texts: feedback needed for my first python tkinter simple MVC, list element to print to label

texts:
Just starting to get the idea of MVC with tkinter. I wrote this simple program and I'm looking for feedback. There are no errors, but I don't know if I set it up right or not.

import tkinter as tk

class Model():

    def __init__(self):
      self.list = ["email", "sms", 'voice']

class View(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        tk.Frame.__init__(self, parent, bg="yellow", bd=2,
           relief=tk.RIDGE)
        self.parent = parent
        self.pack()

        self.labelVariable=tk.StringVar()
        self.output=tk.Label(self, textvariable=self.labelVariable,
             bg="orange", fg="white")
        self.output.pack()

        self.hello = tk.Button(self, text="Show", command=
             self.controller.hello_Button_Pressed,  bd=2,
             relief=tk.RIDGE)
        self.hello.pack(side="left")

class Controller():
    def __init__(self):
        self.root = tk.Tk()
        self.model = Model()
        self.view = View(self.root, self)

        self.root.title("MVC example")
        self.root.geometry("250x350")
        self.root.config(background="LightBlue4")
        self.root.mainloop()

    def hello_Button_Pressed(self):
        self.view.labelVariable.set(self.model.list)

if __name__ == '__main__':
    c = Controller()


texts: Choose the Transport Layer Security protocol - requests python

texts:
I am using using the following code to choose the transport layer security protocol while issuing a request to server. Could someone please review it.
This is in reference to the following question:
https://stackoverflow.com/questions/22657498/i-want-to-choose-the-transport-layer-security-protocol-in-urllib2

import ssl
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager

class MyAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_SSLv3)

s = requests.Session()
myAdp = MyAdapter()
myAdp.init_poolmanager(5, 100)
s.mount('https://', myAdp)

try:
    url = "https://www.google.com"
    feed = s.get(url, verify = True)
    print feed.text
except Exception as e:
    print "Exception:", e


texts: Graph as adjacency lists: BFS DFS Topological Sort

texts:
I have written some code to practise graphs. Graph is represented as vector<list<int>>  . Would you share some feedback with me?
Are algorithms correct and perform well?
I implemented graph using vector<list<>> because of the name "adjacency lists". However now I think using unordered_map would be cleaner and would perform better, right? I plan to modify it later with a tamplate.
graph.h
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
#include <queue>
#include <stack>

class Graph {
public:
    Graph(): numOfVert {}, adjacencyLists {} {}
    Graph(int n): numOfVert {n}{
        adjacencyLists.resize(n);
    }
    void addEdge(std::pair<int,int> p);
    void topoSort();
    void DFS(int start);
    void BFS(int start);
    void print();
private:
    int numOfVert;
    std::vector<std::list<int>> adjacencyLists;
};

void Graph::addEdge(std::pair<int,int> p){
    if(p.first >= numOfVert || p.second >= numOfVert){
        numOfVert = p.second > p.first ? p.second + 1 : p.first + 1;
        adjacencyLists.resize(numOfVert);
    }
    adjacencyLists[p.first].push_back(p.second);
}

void Graph::print(){
    for(unsigned i = 0; i != adjacencyLists.size(); ++i){
        std::cout << i << " | ";
        std::copy(adjacencyLists[i].cbegin(),
                adjacencyLists[i].cend(),
                std::ostream_iterator<int>(std::cout, " "));
        std::cout << '\n';
    }
}

void Graph::DFS(int start){
    std::cout << "DFS: ";
    std::vector<int> visited(numOfVert, 0);
    std::stack<int> s; s.push(start);
    while(!s.empty()){
        int curr = s.top(); s.pop();
        std::cout << curr << " ";
        for(const auto x: adjacencyLists.at(curr)){
            if(visited.at(x) == 0){
                s.push(x);
                visited.at(x) = 1;
            }
        }
    }
    std::cout << "\n";
}

void Graph::BFS(int start){
    std::cout << "BFS: ";
    std::vector<int> visited(numOfVert, 0);
    std::queue<int> q; q.push(start);
    while(!q.empty()){
        int curr = q.front(); q.pop();
        std::cout << curr << " ";
        visited.at(curr) = 1;
        for(const auto x: adjacencyLists.at(curr)){
            if(visited.at(x) == 0){
                q.push(x);
                visited.at(x) = 1;
            }
        }
    }
    std::cout << "\n";
}

void Graph::topoSort(){
    std::vector<int> incom_rank (numOfVert, 0);
    std::queue<int> next;
    std::queue<int> sorted;
    // create array of incoming edge rank
    for(unsigned i = 0; i != adjacencyLists.size(); ++i){
        for(const auto x: adjacencyLists.at(i)) ++incom_rank.at(x);
    }
    // populating queue next
    for(unsigned i = 0; i != incom_rank.size(); ++i){
        if(incom_rank.at(i) == 0) next.push(i);
    }
    while(!next.empty()){
        int curr = next.front(); next.pop();
        sorted.push(curr);
        for(const auto x: adjacencyLists.at(curr)){
            --incom_rank.at(x);
            if(incom_rank.at(x) == 0) next.push(x);
        }
    }
    // print out toposorted graph
    std::cout << "TSort: ";
    while(!sorted.empty()){
        std::cout << sorted.front() << " ";
        sorted.pop();
    }
}

main.cpp
#include "Graph.h"
#include <set>

int main(){
    Graph g(10);
    std::set<std::pair<int,int>> E {{0,2},{1,3},{2,3},{2,4},{4,5},{3,5},{5,6},
                                    {6,7},{5,10},{7,12},{11,12},{8,9},{9,10},
                                    {10,11},{12,13}};
    for(auto& x: E) g.addEdge(x);
    g.print();
    g.topoSort();
}


texts: Haskell zmq & protobuf message forwarding

texts:
I wrote a test program (and first "real" Haskell program!) that receives a zmq request on 1 socket, and forwards part of that message to another socket.

There are a 2 things I specifically don't like:

I couldn't figure out a way to build a protobuf message without specifying every field.  This is especially annoying for fields like failure_message, which I had to set to Nothing
I'm not a fan of the lazyToStrictBS conversion

Is there any way to avoid these?  Also, any other things I should fix? I would be shocked if there were no other issues.

The code:

module Main where

import System.ZMQ4.Monadic
import Control.Monad (forever)
import Data.ByteString.Char8 (pack, unpack)
import qualified Data.ByteString as ByteString (ByteString, concat)
import Data.ByteString.Lazy as LBS (ByteString, toChunks)
import Control.Concurrent (threadDelay)

import Text.ProtocolBuffers.WireMessage (messageGet)
import Text.ProtocolBuffers.WireMessage (messagePut)

import ProtoMsg.ForwardRequest (ForwardRequest)
import ProtoMsg.ForwardResponse
import ProtoMsg.ReqResponse (ReqResponse)
import ProtoMsg.Status
import ProtoMsg.Retort

lazyToStrictBS :: LBS.ByteString -> ByteString.ByteString
lazyToStrictBS x = ByteString.concat $ LBS.toChunks x

main :: IO ()
main =
    runZMQ $ do
        repSocket <- socket Rep
        bind repSocket "tcp://*:9000"

        pubSocket <- socket Pub
        bind pubSocket "tcp://*:9001"

        liftIO $ putStrLn "Ready"
        forever $ do
            msg <- receive repSocket
            (liftIO.putStrLn.unwords) ["Received request:", unpack msg]

            let repMsg = ProtoMsg.ForwardResponse.ForwardResponse {
                header = ProtoMsg.ReqResponse.ReqResponse {
                    message_id = Nothing,
                    user_id = Nothing,
                    request_id = Nothing,
                    ProtoMsg.ReqResponse.status = Just ProtoMsg.Status.OK,
                    failure_message = Nothing
                }
            }
            let respMsg = ProtoMsg.Retort.Retort {
                status = Just ProtoMsg.Status.OK,
                failure_message = Nothing
            }
            send repSocket [] (lazyToStrictBS (messagePut respMsg))


texts: Input/character validation on an input-element

texts:
I took some time to create a function, which can validate which keys you input on an element. So far it has two uses:

You call .validate() on the object, but make sure it has a data-match attribute with the regex in it
You call .validate("REGEX") on the object, but replace REGEX with your actual regular expression

Here is an example:

document.getElementById("input").validate("[0-9A-Fa-f]");

This will only allow characters 0-9, A-F, and a-f. Nothing else.

I want to know, if I can improve this code. So far I have it the way I want it to be, but I would surely love someone else's feedback on it as well. It is really light-weight and can easily be implemented.

Thanks a lot!

Object.prototype.validate = function(myRegex) {
    var regex = this.getAttribute("data-match") || myRegex;
    var allowed = [8, 37, 38, 39, 40, 46];
    this.addEventListener("keydown", function(e) {
        var c = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode);
        if (!e.shiftKey && !e.metaKey) c = c.toLowerCase();
        if ((e.ctrlKey && (e.keyCode == 65 || e.keyCode == 97)) || c == '⌘-A') return true;
        if (c.match(regex) || allowed.indexOf(e.which) >= 0) {
            //Do nothing
        } else {
            e.preventDefault();
        }
    });
}

document.getElementById("input").validate("[0-9A-Fa-f]");
<input type="text" id="input" />


texts:
In my company, I've inherited some Java library that I'm now writing tests to, refactoring and fixing Sonar issues.

One particular point that Sonar is complaining about is a big chaining of if/else if/else statements, that is used in a class responsible for parsing values that come from the DB to the corresponding values used in Java. The cyclomatic complexity of this method is 32, where Sonar is configured to a threshold of 15.

I would like some ideas of a better way to write this. Maybe some design-pattern that could be applied.

Since this is a pretty critical part of the application, it would be interesting not to add a considerable overhead.

private Object getValue(final Class<?> type, final int index, final ResultSet resultSet) throws SQLException {
    Object value = null;

    if (Boolean.class.isAssignableFrom(type) || boolean.class.isAssignableFrom(type)) {
        String v = resultSet.getString(index);
        if (v != null) {
            value = "Y".equalsIgnoreCase(v);
        }
    } else if (Byte.class.isAssignableFrom(type) || byte.class.isAssignableFrom(type)) {
        value = resultSet.getByte(index);
    } else if (Byte[].class.isAssignableFrom(type) || byte[].class.isAssignableFrom(type)) {
        value = resultSet.getBytes(index);
    } else if (Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type)) {
        value = resultSet.getShort(index);
    } else if (Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
        value = resultSet.getInt(index);
    } else if (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
        value = resultSet.getLong(index);
    } else if (Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
        value = resultSet.getFloat(index);
    } else if (Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
        value = resultSet.getDouble(index);
    } else if (BigDecimal.class.isAssignableFrom(type)) {
        value = resultSet.getBigDecimal(index);
    } else if (Timestamp.class.isAssignableFrom(type)) {
        value = resultSet.getTimestamp(index);
    } else if (Time.class.isAssignableFrom(type)) {
        value = resultSet.getTime(index);
    } else if (Date.class.isAssignableFrom(type)) {
        value = resultSet.getDate(index);
    } else if (LocalTime.class.isAssignableFrom(type)) {
        String vlrString = resultSet.getString(index);
        if (StringUtils.length(vlrString) == 6) {
            value = LocalTime.of(Integer.valueOf(vlrString.substring(0, 2)), Integer.valueOf(vlrString.substring(2, 4)), Integer.valueOf(vlrString.substring(4)));
        }
    } else if (LocalDate.class.isAssignableFrom(type)) {
        Timestamp timeStamp = resultSet.getTimestamp(index);
        value = timeStamp == null ? null : timeStamp.toLocalDateTime().toLocalDate();
    } else if (LocalDateTime.class.isAssignableFrom(type)) {
        Timestamp timeStamp = resultSet.getTimestamp(index);
        value = timeStamp == null ? null : timeStamp.toLocalDateTime();
    } else if (String.class.isAssignableFrom(type)) {
        value = resultSet.getString(index);
    } else if (type.isEnum()) {
        value = DomainUtils.get((Class<Enum>) type, resultSet.getString(index));
    } else {
        value = resultSet.getObject(index);
    }

    if (resultSet.wasNull() && !type.isPrimitive()) {
        value = null;
    }

    return value;
}


texts: MongoDB - Find records in one collection that match string in 2nd collection

texts:
I have a MongoDB collection of product IDs/unique products attributes and a second collection of codes that relate to attributes common for products whose IDs are prefixed with those codes.

For example, two product IDs might be aaa17859 and aaa98542 so their code prefix is aaa.

I have several thousand codes, and the codes rarely change, so the 'codes' collection is more of a data repo. The products change frequently throughout the day, and imports can run from several hundred to a few thousand.

Currently, I am running the below to join the two sets together when the data is first loaded in.

import re

code_collection= list(db.codes.find())
for x in code_collection:
    p = re.compile(x['CODE-PREFIX'] + '.*')
    db.productdataset.update({'productID': {'$regex': p}}, { '$set': {'codeData': x['data_property']}}, multi=True )

Pro to this method is that it reduces the number of calls I would otherwise have to make once the data is initially loaded.

Major con is that when the code collection is updated (say, a new common attribute), something similar has to be rerun against the entire product collection. Plus, depending on this list, it can take a little longer than I'd like to load in the data. Also, this means I can end up with a good deal of duplication. In general, this approach just seems a little kludgy.

What I would like to optimize is a method to join these two sets together in one call, thus preventing the rerun. I have been looking at a lot of mapreduce examples, but have had trouble figuring out how I would be able to use the prefix from the code collection to use regex and  look up it's related productID.


texts:
I want to read a list of IDs (as integers) from a file in Python3. The file has a single ID per line and no blank lines.

with open(file_eval_id) as f:
    eval_ids = [list(map(int, line.split()))[0] for line in f]

Is there a cleaner way of doing it? I have doubts about referencing the list(...)[0] as the best way.


texts: Fastest way to build string feature vectors Python

texts:
I have a list of strings to search along with a list of words and want to produce boolean feature vectors indicating presence of each word within the strings. What is the fastest way to build these feature vectors in Python?

In the example below the first string would output [1, 0, 1, 1] for example. I'm currently using the Aho Corasick algorithm (https://stackoverflow.com/questions/44310516/python-find-occurrences-of-list-of-strings-within-string) to search each string in a list comprehension but think it's possible there's a faster way. The code below uses this method and averages the time over 10 runs.

import time
import numpy as np
import ahocorasick

def check_strings(A, search_list, string_to_search):
    """Use Aho Corasick algorithm to produce boolean list indicating
    prescence of strings within a longer string"""
    index_list = []
    for item in A.iter(string_to_search):
        index_list.append(item[1][0])

    output_list = np.array([0] * len(search_list))
    output_list[index_list] = 1
    return output_list.tolist()

word_list = ["foo", "bar", "hello", "world"]
strings_to_check = ["hello world foo", "foo bar", "bar world"]

A = ahocorasick.Automaton()
for idx, s in enumerate(word_list):
    A.add_word(s, (idx, s))
A.make_automaton()

run_times = []
for i in range(10):
    t0 = time.time()
    feature_vectors = [check_strings(A, word_list, s) for s in strings_to_check]
    run_times.append(time.time()-t0)

print(feature_vectors)
print(np.mean(np.array(run_times)))

Output is:

[[1, 0, 1, 1], [1, 1, 0, 0], [0, 1, 0, 1]]
1.65939331055e-05

Looking for a more efficient way of doing this, I thought it might be possible somehow by concatenating the strings to avoid the loop but can't quite figure out how to get it to work.


texts:
I have the following code to do remember-me style login:

<?php
session_start();
if(!isset($_SESSION['login'])) $_SESSION['login'] = 0;
if(isset($_COOKIE['web_login_cookie']) && $_SESSION['login'] == 0) {
    $sql = mysql_query("SELECT * FROM users");
    while($row = mysql_fetch_array($sql)) {
        $pass = sha1($row['password'] . '@#$%$#%dsf@#$SDFg');
        if($_COOKIE['web_login_cookie'] == $pass) {
            $_SESSION['userID'] = $row['userID'];
            $_SESSION['login'] = 1;
            if($row['level'] == 1) {
                $_SESSION['admin'] = 1;
            }
        }
    }
    if(mysql_num_rows($sql) == 0) {
        setcookie("web_login_cookie", "", time()+(60*60*24*14));
        session_destroy();
    }
}
?>

I have this code in my header file. Is this secure enough or will it pose any security risks in the future?


texts: Changing text with a click event: how to restore default state of text in jQuery if/else statement

texts:
I have a click event that calls a function which makes some CSS changes (acts on Text in 3 unique text elements).

The function (below) works, but is lacking a 'restore default' function (to return the text to its original state), AND is in dire need of refactoring.

Q: How can the original state of ALL text elements be restored once user clicks away from this section?

Here is the partially working, ugly function:

function txtResize() {

        var clicked = this.id;

        if (clicked == "Text1")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text2, #Text3").css("opacity", "0.2");
        }
        else if (clicked == "Text2")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text1, #Text3").css("opacity", "0.2");
        }
        else if (clicked == "Text3")
        {
            $("#" + clicked).css("opacity", "1");
            $("#Text1, #Text2").css("opacity", "0.2");
        }
         // code above is ok, below does not work

        else if ( !(clicked == "Text1") && !(clicked == "Text2") && !(clicked == "Text3") )
        {
            $("#Text1, #Text2, #Text3").css("opacity", "1");  // return to default state
        }

 };

UPDATE: (20 Jan) - Have improved the code, but it still somewhat clunky and involves two distinct functions.

function txtResize() {

        var clicked = this.id;

        if (clicked === "Text1" || clicked === "Text2" || clicked === "Text3" )
        {
            $("#Text1, #Text2, #Text3").animate({"opacity": "0.2"}, 500)
            $("#" + clicked).animate({"opacity": "1"}, 200);
        }
};

function txtRestore(){
        $("#Text1, #Text2, #Text3").animate({"opacity": "1"}, 1000);
};


texts:
I'm trying to solve Codeeval's The Ministry of Truth challenge, and have hit 97.5% - is anyone able to spot where my code is missing the last 2.5%? The percentage indicates that one or more of their test cases is failing.
Here's the question - I've used the original wording because I'm worried if I give my version of the problem then it'll be one that misses that 2.5% edge case:

Challenge Description:
It's 1984, and you are working as an official at the Ministry of Truth. You have intersected a message subjected to Big Brother's doctrine.
Your task is to delete letters from certain "utterances" in order to replace them with an "utterance" approved by the Ministry.
A "word" is a single sequence of Latin letters, and an "utterance" is a sequence of multiple words and spaces.
To compare two "utterances," you have to replace all blocks of spaces with one space. Utterances are considered to be identical when resulting expressions match.
One line contains two different expressions separated by semicolon ';'. The first expression is the original utterance, and the second one is the utterance you want to get.
If you cannot fulfill the order, print a single line «I cannot fix history». Otherwise, output the original utterance by replacing the letters that must be erased with underscore and by replacing all blocks of white spaces with a single white space.
Sample input lines:

Higher meaning;Hi mean
this is impossible;im possible
twenty   two minutes;two minutes
Higher meaning;e

Sample output lines:

Hi____ mean___
I cannot fix history
______ two minutes
____e_ _______

Here's the code so far (Python 3):

import sys
import re

with open(sys.argv[1], 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue

        original, target = line.split(';')

        # Replace contiguous spaces with one space
        original = re.sub(r"\s+", " ", original)

        # Split target into targets
        targets = target.split()

        redacted, current_target, i, not_possible, space_next = '', 0, 0, False, False
        while i < len(original):
            if not space_next and current_target is not None and targets and len(targets) > 0 and len(original) >= i+len(targets[current_target]) and original[i:i+len(targets[current_target])] == targets[current_target]:
                redacted += targets[current_target]
                i += len(targets[current_target])

                if current_target < len(targets)-1:
                    current_target += 1
                    space_next = True
                else:
                    current_target = None

            elif original[i] == ' ':
                 redacted += ' '
                 space_next = False
                 i += 1
            else:
                redacted += '_'
                i += 1

        print('I cannot fix history' if current_target is not None else redacted)


texts:
I've created a parser which is able to parse the full content of houzz.com. After going to the given address, it parses the sub-category links from the left sided bar. Each sub-category links spreads across several pages with pagination. Then it goes to the main page of each sub category links and parses the content over there. I tried to do the whole thing with my level best.

Sub HouzzFull()
Const url = "https://www.houzz.com/professionals/"
Dim http As New ServerXMLHTTP60
Dim html As New HTMLDocument, htm As New HTMLDocument, hmm As New HTMLDocument
Dim str As String, link As String, main As String
Dim topics As Object, topic As Object
Dim links As Object, post As Object, gist As HTMLHtmlElement

With http
    .Open "GET", url, False
    .send
    html.body.innerHTML = .responseText
End With
Set topics = html.getElementsByClassName("sidebar-item-label")

    For i = 1 To topics.Length - 1
    str = topics(i).href

    With http
        .Open "GET", str, False
        .send
        htm.body.innerHTML = .responseText
    End With
    Set links = htm.getElementsByClassName("pageNumber")
        For y = 0 To links.Length - IIf(links.Length > 0, 1, 0)

        If y > 0 Then
        link = links(y).href

        With http
            .Open "GET", link, False
            .send
            htm.body.innerHTML = .responseText
        End With

        End If

        Set topic = htm.getElementsByClassName("pro-title")
            For Each post In topic
            main = post.href

            With http
                .Open "GET", main, False
                .send
                hmm.body.innerHTML = .responseText
            End With

                For Each gist In hmm.getElementsByClassName("container profile-carded")
                    x = x + 1
                    With gist.getElementsByClassName("profile-full-name")
                        If .Length Then Cells(x, 1) = .Item(0).innerText
                    End With
                    With gist.getElementsByClassName("info-list-text")
                        If .Length > 1 Then Cells(x, 2) = Replace(.Item(1).innerText, "Contact:", "")
                    End With
                    With gist.getElementsByClassName("info-list-text")
                        If .Length > 2 Then Cells(x, 3) = Replace(.Item(2).innerText, "Location:", "")
                    End With
                    With gist.getElementsByClassName("click-to-call-link text-gray-light trackMe")
                        If .Length Then Cells(x, 4) = .Item(0).phone
                    End With
                    With gist.getElementsByClassName("proWebsiteLink")
                        If .Length Then Cells(x, 5) = .Item(0).href
                    End With
                Next gist
            Next post
        Next y
    Next i
End Sub


texts:
I just submitted a Python solution to the 'Two Sum' problem on LeetCode.

The Problem

  Given an array of integers, return indices of the two numbers such
  that they add up to a specific target.

  You may assume that each input would have exactly one solution, and
  you may not use the same element twice.

  Example

  Given nums = [2, 7, 11, 15], target = 9

  Because nums[0] + nums[1] = 2 + 7 = 9

  return [0, 1].

My Solution

class Solution:
    def twoSum(self, nums, target):
        number_bonds = {}
        for index, value in enumerate(nums):
            if value in number_bonds:
                return [number_bonds[value], index]
            number_bonds[target - value] = index
        return None

It was accepted and then told me the following:

  Your runtime beats 83.12 % of python3 submissions.

This means that 16.88% of python3 submissions were more efficient than this one.

How can I get this more efficient than the solution provided above? Is there a funky way to do this with numpy that I'm not getting? Is there maybe another data structure I should use in this situation? Or a better algorithm altogether? I've explored a few alternate solutions and profiled with timeit but none were faster than this.


texts:
I have this quicksort implementation that guarantees that the recursion depth will be at most logarithmic in \$n\$:

LogQuicksort.java

package net.coderodde.util;

public class LogQuicksort {

    private LogQuicksort() {}

    public static void sort(int[] array) {
        sort(array, 0, array.length);
    }

    public static void sort(int[] array, int fromIndex, int toIndex) {
        while (fromIndex < toIndex) {
            int i = partition(array, fromIndex, toIndex - 1);
            int leftPartLength = i - fromIndex;
            int rightPartLength = toIndex - 1 - i;

            if (leftPartLength < rightPartLength) {
                sort(array, fromIndex, i);
                fromIndex = i + 1;
            } else {
                // leftPartLength >= rightPartLength
                sort(array, i + 1, toIndex);
                toIndex = i;
            }
        }
    }

    private static int partition(int[] array, int lo, int hi) {
        int pivot = array[hi];
        int i = lo;

        for (int j = lo; j < hi; ++j) {
            if (array[j] <= pivot) {
                swap(array, i, j);
                i++;
            }
        }

        swap(array, i, hi);
        return i;
    }

    private static void swap(int[] array, int i, int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}

Demo.java

package net.coderodde.util;

import java.util.Arrays;
import java.util.Random;

public class Demo {

    private static final int ARRAY_LENGTH = 50_000_000;
    private static final int FROM_INDEX = 10;
    private static final int TO_INDEX = ARRAY_LENGTH - FROM_INDEX;

    public static void main(String[] args) {
        long seed = System.nanoTime();
        Random random = new Random(seed);
        int[] array = getRandomIntArray(ARRAY_LENGTH, random);
        System.out.println("Seed = " + seed);

        warmup(array, FROM_INDEX, TO_INDEX);
        benchmark(array, FROM_INDEX, TO_INDEX);
    }

    private static void warmup(int[] array, int fromIndex, int toIndex) {
        System.out.println("Warming up...");
        run(array, fromIndex, toIndex, true);
        System.out.println("Warming up done.");
    }

    private static void benchmark(int[] array, int fromIndex, int toIndex) {
        run(array, fromIndex, toIndex, false);
    }

    private static void run(int[] array,
                            int fromIndex,
                            int toIndex,
                            boolean silent) {
        int[] array1 = array.clone();
        int[] array2 = array.clone();

        long startTime = System.nanoTime();
        Arrays.sort(array1);
        long endTime = System.nanoTime();

        if (!silent) {
            System.out.printf("Arrays.sort in %.1f milliseconds.\n",
                              (endTime - startTime) / 1e6);
        }

        startTime = System.nanoTime();
        LogQuicksort.sort(array2);
        endTime = System.nanoTime();

        if (!silent) {
            System.out.printf("LogQuicksort.sort in %.1f milliseconds.\n",
                              (endTime - startTime) / 1e6);
            System.out.println("Algorithms agree: " +
                               (Arrays.equals(array1, array2)));
        }
    }

    private static int[] getRandomIntArray(int size, Random random) {
        int[] array = new int[size];

        for (int i = 0; i < size; ++i) {
            array[i] = random.nextInt();
        }

        return array;
    }
}

Output

Seed = 129202891498907
Warming up...
Warming up done.
Arrays.sort in 7119.2 milliseconds.
LogQuicksort.sort in 7786.4 milliseconds.
Algorithms agree: true

Critique request

Please tell me anything that comes to mind.


texts: Converting vector of bytes to base64 string and back


texts: Random date gen class. Returns a tuple of a start date and end date

texts:
Just interested in any comments about the way the code is written. I am very new to python and programming. I did think about a func with a generator, but thought this approach was better.

from datetime import date
from datetime import timedelta

import calendar
import random

class rand_dates(object):
    '''
        returns a date range as tuple of a random start date in the current year and an end date + random.randint(term) param.
    the end date can exceed the current year.
        my usage: i want a random reservation date for a hotel stay.
    A base year can also be passed as a param if another year is required other than the current year
    '''

    def __init__(self, term = 5, year=None):
        self.term = term
        self.year = year

    def __iter__(self):
        return self

    def next(self):
        td = date.today()
        if self.year == None:
            y = td.year
        else:
            y = self.year

        m = random.randint(1,12)
        d_in_month = calendar.monthrange(y,m)[1]
        d = random.randint(1,d_in_month)
        sd = date(y,m,d)
        ed= sd + timedelta(days=random.randint(1,self.term))
        return (sd,ed)


texts: Checking if there are no numbers from cellular services

texts:
I have this piece of code, which raises an exception if there are no numbers from 3 services. I really don't like how it looks at the moment.

no_numbers = False
if use_verizon_sms:
  if not Api.check_avalible_credits():
    no_numbers = True
elif use_verizon:
  if not buy_verizon_number():
    no_numbers = True
else:
  if not check_count_numbers():
    no_numbers = True

if no_numbers:
  raise Exception("THERE IS NO AVAILABLE NUMBERS")

A shorter version looks even more ugly to me and less clear:

if (use_verizon_sms and not Api.check_avalible_credits()) or \
  (use_verizon and not buy_verizon_number()) or \
  not check_count_numbers():
  raise Exception("THERE IS NO AVAILABLE NUMBERS")

Do you have any ideas how to rewrite it?


texts: Project Euler # 21 amicable numbers Python

texts:
Let \$d(n)\$ be defined as the sum of proper divisors of \$n\$ (numbers less than \$n\$ which divide evenly into \$n\$).
If \$d(a) = b\$ and \$d(b) = a\$, where \$a ≠ b\$, then \$a\$ and \$b\$ are an amicable pair and each of \$a\$ and \$b\$ are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284.
The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000. Here's my implementation in Python. I need your feedback on how this can be improved.

Note: I'm a beginner in programming.

from time import time

def get_divisors(n):
    """Yields divisors of n."""
    divisor = 2
    while divisor * divisor <= n:
        if n % divisor == 0 and n // divisor != divisor:
            yield divisor
            if n // divisor != divisor:
                yield n // divisor
        divisor += 1
    yield 1

def get_sum_amicable(n, divs={2:1}):
    """Yields amicables below n."""
    for number1 in range(n):
        for number2 in range(number1):
            try:
                if divs[number2] == number1 and divs[number1] == number2:
                    yield number1
                    yield number2
            except KeyError:
                divs[number1] = sum(get_divisors(number1))
                divs[number2] = sum(get_divisors(number2))
                if divs[number2] == number1 and divs[number1] == number2:
                    yield number1
                    yield number2

if __name__ == '__main__':
    start = time()
    print(sum(get_sum_amicable(10000)))
    print(f'Time: {time() - start} seconds.')


texts: Grouping and displaying people by political demographics

texts:
I have a function that sorts and groups items inside an array and then adds a corresponding jsx element to the page.

I've already refactored it from 100 lines of code to 44, but I'm sure that its still unreadable pile of spaghetti code. I've tried filtering individuals and groups separately but that just bloats my code to some unbelievable extent so im looking for ways to reduce bloat and improve readability.

// array - array im sorting
// ageStart - minimal age of person
// ageEnd - minimum age of person
// activity & time - specific to the jsx elements inside(dont really     play a role here)
//
function group(array, ageStart, ageEnd, activity, time = '') {
// filtering by political views and age.
    const polViewsLib = array.filter(item => item.polViews === 'Liberal'
        && item.age >= ageStart
        && item.age <= ageEnd)
       //grouping items inside an array using  reduce(groups people     whose age difference is less than 5)
       .reduce((acc, curr, ind, arr) => {
        if (
            !ind
            || curr.age - arr[ind - 1].age > 5
        )acc.push([]);
        acc[acc.length - 1].push(curr);
        return acc;
        }, []);
    const polViewsConservative = array.filter(item => item.polViews === 'Conservative'
        && item.age >= ageStart
        && item.age <= ageEnd).reduce((acc, curr, ind, arr) => {
        if (
            !ind
            || curr.age - arr[ind - 1].age > 5
        )acc.push([]);
        acc[acc.length - 1].push(curr);
        return acc;
    }, []);

 // returning data sorted by age and mapping them to corresponding jsx elements
 return [polViewsLib, polViewsConservative].sort((a,b) => {
 a[0].age - b[0].age;
 }).map((item, index) => {
        const res = item.length > 1 ? (
            <PersonContainer
                key={item[index].id}
                data={item}
                visibility={activity}
                timePeriod={time}
            />
        )
        : (
            <Person
                key={item.id}
                data={item[0]}
                visibility={activity}
                timePeriod={item}
            />
        );
        return res;
    });
}

Typical item inside array that I process:

  {
     id:151324,
     name: 'John',
     age: 45,
     polViews: 'Liberal',
  }


texts: Finding the longest Collatz sequence cycle

texts:
I wrote a program to calculate Collatz sequences for initial numbers between 1 and a given integer i, then find the one with the largest cycle length.  My code is pretty fast, but I want to increase the speed more.  Please have a look at my code and if there are any changes to made in my code to make it faster.

import java.util.Scanner;
class asgn {
public static void main(String args[]){
long i,j,n,max=0, pos=0, x,y;
long count=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the positive integer:");
while(sc.hasNextLong())
{x=System.currentTimeMillis();
 i= sc.nextLong();
long arr[] = new long [50000000];

 for(j=1;j<=i;j++)
{
n=j;
count = 0;
while(n!=1)
{
if(n<50000000)
{if(arr[(int)(n-1)]!=0)
{ count=count+arr[(int)(n-1)];
break;
}}

if(n%2==0)
{n=n/2;
count++;
}
else
{
n = (3*n)+1;
count++;
}
}
if(j<50000000)
arr[(int)(j-1)]=count;
if(count>max)
{max=count; pos=j;}
count=0;
}
y=System.currentTimeMillis();

System.out.println("Maximum cycle length occurs at "+pos+" and the number of steps     involved     "+max+"\n Total time taken is "+(y-x)+"milliseconds");
break;}}}


texts: Calculate total cost of items, based on bulk discount

texts:
I've written a short program for one of my first exercise in C++.... I would like to get better suggestions to solve it, so hope you can help me :) And I hope this is the right session to ask...:)

  Exercise:

  Input: Pieces and price per piece. If pieces > 10, its 5% discount. If pieces>50, 10% discount

  Output: total price

Thank you a lot in advance

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int stk, ep, gesamt;
cout << "Pieces?" << endl;
cin >> stk;
cout << "Price per Piece?" << endl;
cin >>ep;
if (stk>=10)
{
    if (stk>=50)
    //10% discount
    {
    gesamt=stk*ep;
    gesamt=gesamt - (gesamt*10)/100;
    goto stop;
    }
     else   //5% discount
    gesamt=stk*ep;
    gesamt=gesamt - (gesamt*5)/100;
    goto stop;
}

else gesamt=stk*ep;

stop:
    cout << gesamt << endl;

return 0;
}


texts:
I built a Chrome extension. Part of point of the extension is to call a page, parse the page and see how certain values line up. I'm concerned that this could be done in a better way than what I have as far as performance is concerned and readability.

Any suggestions on this front?

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if( request.sfContactURL) {
    var passedContactURL = request.sfContactURL;
    console.info("Contact URL received!");
    console.info(passedContactURL);
    console.info("Requesting Page");
    httpGetAsync(passedContactURL,sender, parseFeed);
    }
  }
);

function parseFeed(incomingText, sendingTab){
console.info("Parsing the Feed");
incomingText = incomingText.slice(incomingText.search("Recruiting Admin"),incomingText.search("Body events"))
console.info(incomingText);
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[0] = checkValue(incomingText);
console.info("Recruiting is " + prodAdmins[0])
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[1] = checkValue(incomingText);
console.info("Onboarding is " + prodAdmins[1])
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[2] = checkValue(incomingText);
console.info("Learning is " + prodAdmins[2])
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[3] = checkValue(incomingText);
console.info("Performance is " + prodAdmins[3])
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[4] = checkValue(incomingText);
console.info("HB is " + prodAdmins[4])
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[5] = checkValue(incomingText);
console.info("Point is " + prodAdmins[5])
incomingText = incomingText.substr(incomingText.indexOf("title")+7)
prodAdmins[6] = checkValue(incomingText);
console.info("Connect is " + prodAdmins[6])

chrome.tabs.sendMessage(sendingTab.tab.id, {"productAdministrators": prodAdmins});
console.info("Product Administrators sent!");
}

function httpGetAsync(theUrl, tab, callback)
{
    console.info("Making HTTP Call");
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText, tab);
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
}

function checkValue(valueString){
    var pattChecked = new RegExp(/^(Checked)\s*\S*/g);
    var pattUnChecked = new RegExp(/^(Not)\s*\S*/g);
    if (pattChecked.test(valueString)){
        return true;
    } else if (pattUnChecked.test(valueString)){
        return false;
    }
}


texts: Compute leaderboard of competitive riders throughout a season

texts:
I have a table in my DB that contains Riders as rows and their points throughout the season as columns. Here are the columns:

['name', 'wwq_id', 'wwq_code', 'year', 'round1_qualy', 'round1_final',
'round1_timed', 'round1_total_qualy', 'round1_total_qualy_position',
'round1_total_final', 'round1_total_final_position', 'round1_total_timed',
'round1_total_timed_position', 'round1_total', 'round1_total_position'...etc

The 'round1_qualy', 'round1_final', 'round1_timed' all come from different tables and are added using another function. Once they are in the DB all of total columns are calculated using generated columns in MySQL.

I need to calculate the position of the rider at different points in the season. I.E. After round one qualy, after round two final, etc.

Here is the code I have right now:

def set_positions():
    """Add positions to the DB for each column in our overall table"""
    engine = sql.create_engine(MYSQL_CON_STRING)
    connection = engine.connect()
    trans = connection.begin()

    # Men, Women, Junior
    for category in CATEGORIES:
        table = category + '_overall'
        df = pd.read_sql('SELECT * FROM {0}'.format(table), engine)
        points_columns_list = [col for col in df.columns
                               if 'total' in col and 'position' not in col]

        # Calculate the rank based on current total points column and
        # insert into current column index + 1
        for points_column in points_columns_list:
            position_index = df.columns.get_loc(points_column) + 1
            position_column = df.columns[position_index]
            current_points = df.groupby('year')
            position = \
                current_points[points_column].rank(ascending=0,
                                                   method='min').astype(int)
            df.loc[:, position_column] = position.values

            # No points awarded in this and/or previous rounds. Everyone is
            # at 0 so everyone is rank 1
            df.loc[(df[points_column] == 0)
                   & (df[position_column] == 1), position_column] = 'NULL'

            # Add rows to the DB
            for row in df.itertuples():
                connection.execute('UPDATE {0} '
                                   'SET {1} = {2} '
                                   'WHERE year = {3} and name = "{4}"'
                                   ''.format(table, position_column,
                                             getattr(row, position_column),
                                             getattr(row, 'year'),
                                             getattr(row, 'name')))
        trans.commit()
    connection.close()

The code works perfectly, it just takes a long time. This function doesn't get executed very often, but considering there are about 8000 rows per table, it takes a bit of time.

Is there any way to get the complexity down?


texts:
I have a class called _NodeProcess. It consists of a mainloop (main function) which is run in a separate process and methods (start and stop) that control the mainloop. Here's the code:

class _NodeProcess:
    def __init__(self, master):
        self.master = master
        self.process = multiprocessing.Process(target=self.main)
        self.is_alive = True
        self.is_dead = False

    def start(self):
        self.process.start()

    def stop(self):
        self.is_alive = False
        while not self.is_dead:
            pass

    def main(self):
        while self.is_alive:
            task = self.master.give_task()
            self.master.grab_result({'header': 'result', 'result': self.master.function(task), 'task': task})
        self.is_dead = True

The part that worries me is the stop function. On each mainloop iteration, I check whether I should continue (self.is_alive == True), and if I shouldn't, I stop and do self.is_dead = True to confirm that i had quit the loop. Meanwile, in the stop function, after setiing self.is_alive to False, and block until self.is_dead == True.

My concern is the way in which I block:

while not self.is_dead:
    pass

I'm afraid it may eat to much resources just iterating over that loop at a very high speed. So, I considered another option, using time.sleep:

import time

while not self.is_dead:
    time.sleep(1)

But it doesn't seem like a best way to block until some condition is met (I need an extra library; I lose 0.5 seconds on average when I call the stop method, if I make the period less, I spend more resources, so it's some kind of a compromise, which has to be made each time I write code like that). Is there a better solution for this particular problem, or maybe it's better to redesign the class in some way that would allow not facing this problem at all?


texts:
I am a huge proponent of self-documenting code (when at all possible).  I prefer to have code be self evident by the very nature of the names of the variables, methods, etc.

For instance:

if (TheSky.IsBlue && TheGrass.IsGreen)
    BeHappy();

I have run into a situation that has defied all attempts to name the method in a way that illustrates what it does.  The problem is that the method is required to do two things.

I have a class that must maintain its own state, however it must have a method that both verifies a condition, and changes the state via a thread safe lock to prevent race conditions.

It basically looks like the code below:

public class TimeWindow
{
    private static object lockObject = new object();
    private DateTime Timestamp;
    private int WindowCounter;

    // What do I call this?  CanWeDoSomething() implies that it is merely
    // calculating a true/false state, not mutating state.
    //
    // I don't want to call it
    // CanWeDoSomethingAndDecrementItIfWeActuallyDoIt() as that is
    // just too annoying, and it messes up the self-documenting nature
    // since if (CanWeDoSomethingAndDecrementItIfWeAcutallyDoIt()) describes
    // two actions, but only one of them is a Boolean condition, so it doesn't
    // really fit in with the if statement.
    public bool CanWeDoSomething(int WindowSeconds) {
        lock(lockObject) {
            if ((DateTime.Now - TimeStamp).TotalSeconds > WindowSeconds) {
               Timestamp = DateTime.Now;
               WindowCounter = 0;
            }
            if (WindowsCounter < 10) {
               ++WindowCounter;
               return true;
            }
            return false;
        }
    }
}

As you can see, I have to perform the test (to retrieve the Boolean) and modify state at the same time.  If I didn't do this, then a race condition is possible where the value can be changed by another thread in between checking it's value and mutating its state.

The naming is important because if it implies no state change, then people call the method multiple times without realizing that it also changes state.

Can anyone suggest a name that adequately documents what the method is doing, without making it overly complex?  The name should indicate that it's mutating the object as well as performing an action that is a Boolean state.

Alternatively, if you can suggest a better way to accomplish this in a thread safe manner that would work better, that would be good too.


texts: What would be the computationally faster way to implement this 2D numerical integration?

texts:
I am interested in doing a 2D numerical integration. Right now I am using the scipy.integrate.dblquad but it is very slow. Please see the code below. My need is to evaluate this integral 100s of times with completely different parameters. Hence I want to make the processing as fast and efficient as possible. The code is:

import numpy as np
from scipy import integrate
from scipy.special import erf
from scipy.special import j0
import time

q = np.linspace(0.03, 1.0, 1000)

start = time.time()

def f(q, z, t):
    return t * 0.5 * (erf((t - z) / 3) - 1) * j0(q * t) * (1 / (np.sqrt(2 * np.pi) * 2)) * np.exp(
        -0.5 * ((z - 40) / 2) ** 2)

y = np.empty([len(q)])
for n in range(len(q)):
    y[n] = integrate.dblquad(lambda t, z: f(q[n], z, t), 0, 50, lambda z: 10, lambda z: 60)[0]

end = time.time()
print(end - start)

Time taken is

212.96751403808594

This is too much. Please suggest a better way to achieve what I want to do. I have read quadpy can do this job better and very faster but I have no idea how to implement the same. Also, I tried to use cython-prange but scipy doesn't work without gil. I tried numba but again it didn't work for scipy. Please help.


texts:
I've played with jQuery for some time now but have never written my own plugin.

A question was asked: "can I blur an image using jQuery?" and I thought this to be a decent candidate to play with.

Here's my code so far:

(function ($) {
    $.fn.blurStuff = function (options) {
        var defaults = {blurRadius:2, deblurOnHover:false};
        var settings = $.extend(defaults, options);

        $(this).wrap('<div data-blurimage />');

        var blurContainers = $(this).closest('[data-blurimage]');

        blurContainers.each(function () {
            var img = $(this).children();

            $(this).css({
                'width': img.width(),
                'height': img.height(),
                'overflow': 'hidden',
                'position': 'relative'
            });

            var clone = img.clone();
            clone.css({
                'opacity': 0.2,
                'position': 'absolute'
            });

            $(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': +settings.blurRadius}));
            $(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': +settings.blurRadius}));
            $(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': -settings.blurRadius}));
            $(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': -settings.blurRadius}));
        });

        if (settings.deblurOnHover == true) {
            blurContainers.hover(function () {
                $(this).children('img:gt(0)').toggle();
            });
        }

        return blurContainers;
    };
})(jQuery);

In action: http://jsfiddle.net/gvee/xvvWj/

Example usage:

$('img').blurStuff({deblurOnHover: true, blurRadius: 2});

My working logic is to wrap the selector in a parent container and then append 4 translucent clones to this, where each clone is positioned slightly off centre.

This works pretty well so far and I'm pleased with my progress but I can conceive a couple of potential bugs that I wanted some opinions on!

Is my approach reasonable? I realise that I'm appending an extra 4 elements to the DOM on each call which is not ideal (I could get away with using just two, laterally or diagonally, but I think 4 produces a better effect)...
What to do if a user passes a fixed position element? This will break existing flow.
Should I bother validating/sanity checking the parameter values? If so, how should I approach this? Previously I had a parameter called blurOpacity but I removed this because I realised that the wrong values (e.g. 1) effectively "breaks" things.


texts: Simulation of Conway's Game of Life with periodic boundary conditions

texts:
This is exercise 2.4.20. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Implement a class that simulates Conway’s Game of Life.
One thing to note: I did not want my grid to have passive edges and so in my program I considered the grid to be an opened torus (for example in a 10-by-10 grid represented by an array: a[9+1][9+1] == a[0][0]). I also tried to make the name of the methods and variables as self-explanatory as possible.
Here is my program:
public class GameOfLife
{
    public static boolean[][] randomGridMaker(int n, double p)
    {
        // n is the number of grid cells in each row or column
        // p is the probability of a cell being alive
        boolean[][] grid = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (Math.random() < p)
                {
                    grid[i][j] = true;
                }
            }
        }
        return grid;
    }
    public static boolean[][] gridEqualizer(boolean[][] a)
    {
        int n = a.length;
        boolean[][] b = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = a[i][j];
            }
        }
        return b;
    }
    public static int liveNeighborCounter(boolean[][] a, int i, int j)
    {
        int counter = 0;
        int n = a.length;
        if (a[(i-1)%n][(j-1)%n]) counter++;
        if (a[(i-1)%n][j%n]) counter++;
        if (a[(i-1)%n][(j+1)%n]) counter++;
        if (a[i%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][(j+1)%n]) counter++;
        if (a[(i+1)%n][j%n]) counter++;
        if (a[(i+1)%n][(j-1)%n]) counter++;
        if (a[i%n][(j-1)%n]) counter++;
        return counter;
    }
    public static boolean[][] gridUpdater(boolean[][] a)
    {
        int n = a.length;
        boolean[][] b = new boolean[n][n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = a[i][j];
            }
        }
        for (int i = 1; i < n; i++)
        {
            for (int j = 1; j < n; j++)
            {
                int liveNeighbors = liveNeighborCounter(a, i, j);
                if (!a[i][j] && liveNeighbors == 3) b[i][j] = true;
                if (a[i][j])
                {
                    if (liveNeighbors == 1) b[i][j] = false;
                    if (liveNeighbors > 3) b[i][j] = false;
                }
            }
        }
        return b;
    }
    public static void gridDrawer(boolean[][] a)
    {
        int n = a.length;
        StdDraw.setXscale(0,n);
        StdDraw.setYscale(0,n);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (a[i][j]) StdDraw.filledSquare(i+0.5,j+0.5,0.47);
            }
        }
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        double p = Double.parseDouble(args[1]);
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        StdDraw.enableDoubleBuffering();
        boolean[][] a = new boolean[n][n];
        boolean[][] b = new boolean[n][n];
        a = randomGridMaker(n, p);
        while (true)
        {
            StdDraw.clear();
            gridDrawer(a);
            StdDraw.show();
            StdDraw.pause(50);
            StdDraw.clear();
            b = gridUpdater(a);
            gridDrawer(b);
            StdDraw.show();
            StdDraw.pause(50);
            a = gridEqualizer(b);
        }
    }
}

StdDraw is a simple API written by the authors of the book. I checked my program and it works. Here are two different instances of it:
Instance 1: n = 20 and p = 0.1:

Instance 2: n = 100 and p = 0.5:

Is there any way that I can improve my program (especially its performance)?
Thanks for your attention.


texts:
I have 2 questions about functions inside object literals.  I have included the workarounds I've been using, but they seem hackish.  Is there a better way to do this?

ns = {
  a: function (x, y) { return x+y; },

  // Problem 1

  // This does not work: Error: ns.b is not a function
  b: this.a,

  // Is this the correct workaround for this?
  c: function (x, y) { return this.a(x, y); },

  // Problem 2

  // I understand why this won't work, because a is not defined in d's scope
  d: function (x, y) {
    function add(n, o) {
      return this.a(n, o);
    }
    return add(3, 4);
  },

  // Is this the correct workaround for this?  It works in Firefox and Chrome.
  e: function (x, y) {
    function add(n, o) {
      return ns.a(n, o);
    }
    return add(3, 4);
  }
};

ns.a(3, 4); //===> 7

ns.b(3, 4); //===> Error: ns.a is not a function
ns.c(3, 4); //===> 7

ns.d(3, 4); //===> Error: no method named a
ns.e(3, 4); //===> 7

EDIT:  Thank you for all your replies.  As missingno pointed out I am using ns to define a module, though I avoided the module pattern because I don't have any private variables.  The following seems to be an elegant solution to my problems.

var ns = {};
ns.a = function (x, y) { return x+y; };
ns.b = ns.a;
ns.c = function (x, y) {
  function add(n, o) {
    return ns.a(3, 4);
  }
  return add(x, y);
}

ns.a(3, 4); //===> 7
ns.b(3, 4); //===> 7
ns.c(3, 4); //===> 7

Since this has been moved to Code Review, I'd welcome any critiques of my implementation of Scheme's SRFI-1.


texts:
Allow for stuff like:

API/ExampleObjects
API/ExampleObjects/SOME_INTEGER_ID/Children
...

with children knowing their owners (aka parents).

Full repo here

Please be brutally honest if something can be improved!
I couldn't add the rest tag as I don't have 150 rep yet.

<?php

class RestApi {

    private
        $id,
        $owner
    ;

    public function __construct( $params = false ) {

        if( $params['request'] ) {
            // grab first piece of the request
            if( strlen($request = trim(strstr($params['request'], '/'), '/')) > 0 ) {
                // php 5.2 compatible
                $pieces = explode('/', $params['request']);

                if( is_numeric($pieces[0]) ) {
                    $this->setId( $pieces[0] );
                    $params['request'] = $request;
                }
                unset( $pieces );
            } else {
                // if the request is numeric, then it's an id
                if( is_numeric($params['request']) ) {
                    $this->setId( $params['request'] );
                    $params['request'] = '';
                }
            }
        }
    }

    public function getInstance( $params ) {
        if( isset($params['owner']) && is_object( $params['owner'] ) ) {
            $this->setOwner( $params['owner'] );
        }

        // if resource starts with "api/", strip it
        if( strpos($params['request'], 'api/' ) === 0 ){
            $params['request'] = substr($params['request'], 4);
        }

        if( $params['request'] ) {
            if( strlen($request = trim(strstr($params['request'], '/'), '/')) > 0 ) {
                // php 5.2 compatible
                $pieces = explode('/', $params['request']);
                $class = $pieces[0];
                unset( $pieces );
            } else {
                $class = $params['request'];
            }

            $class = get_class($this) . $class;

            $instance = new $class(array('request' => &$request));
            $instance->setOwner( $this );

            if( $request ) {
                return $instance->getInstance(array(
                    'request' => $request
                ));
            }

            return $instance;
        }
    }

    public function getOwner() {
        return $this->owner;
    }

    protected function setOwner( $owner ) {
        $this->owner = $owner;
    }

    public function getId() {
        return $this->id;
    }

    protected function setId( $id ) {
        $this->id = (int)$id;
    }

}


texts:
I wrote this script to automatically install the relevant version of MacPorts.
It's supposed to be used in a fashion similar to the official installer for HomeBrew.

FYI: The real reason that I decided to write this script is; I'm not all that confident in every aspect of my bash scripting abilities and I needed a project to practice on.

While I have a decent working knowledge of bash from an REPL standpoint, I haven't been scripting very long; so keep that in mind.

macports-installer.sh

#!/bin/bash
#
urisvn=https://svn.macports.org/repository/macports/trunk/www/includes/common.inc
uridist=https://distfiles.macports.org/MacPorts
#
mpvers=$(curl -s $urisvn | grep -m 1 -e \'*.*.*\' | cut -d \' -f 2)
osmajor=$(uname -r | cut -d . -f 1)
#
case $osmajor in
8)
    osvers=10.4
    osname=Tiger
    ;;
9)
    osvers=10.5
    osname=Leopard
    ;;
10)
    osvers=10.6
    osname=SnowLeopard
    ;;
11)
    osvers=10.7
    osname=Lion
    ;;
12)
    osvers=10.8
    osname=MountainLion
    ;;
13)
    osvers=10.9
    osname=Mavericks
    ;;
14)
    osvers=10.10
    osname=Yosemite
    ;;
15)
    osvers=10.11
    osname=ElCapitan
    ;;
*)
    echo Warning: unknown OS version
    ;;
esac
#
mppkg=MacPorts-${mpvers}-${osvers}-${osname}
mpchk=MacPorts-${mpvers}
echo $mppkg.pkg
echo $mpchk.chk.txt
curl $uridist/$mppkg.pkg -O
curl $uridist/$mpchk.chk.txt -O
sha256=$(shasum -a 256 ./$mppkg.pkg)
#
if grep $sha256 $mpchk.chk.txt;
    then sudo installer -verboseR -allowUntrusted -pkg ./$mppkg.pkg -target /;
fi
#
rm ./$mppkg.pkg
rm ./$mpchk.chk.txt
#
if ! grep -F 'export PATH="/opt/local/bin:/opt/local/sbin:$PATH"' .bash_profile;
    then echo 'export PATH="/opt/local/bin:/opt/local/sbin:$PATH"' >> .bash_profile;
fi
#

Also, don't forget to mention if there's anything good about the script. If there's anything you do like about it; or if it does something well, let me know..


texts:
I've been recently doing classes on the traveling salesman problem. I've been tackling the nearest neighbor heuristic for the problem and seeing that the algorithm was simplistic, I've decided to see how fast would be solutions implemented in different languages. I've implemented several versions of the solution using different lua extensions, of those most importantly, luajit. I've also done the same algorithm in C.

What surprised me is that luajit solution using C data structures actually beats the pure C implementation significantly (5-6 times faster) C was compiled with gcc -o3 and the problem size was such that completion times were on the order of a few seconds.

I'm not very well versed in the ways of the language, so I wonder if I didn't do something right in C code:

#include <math.h>

typedef struct city {double x; double y; double ind;} city;

double tsp(city* cities, int N){
    city current=cities[0];
    double S=0;
    for (int i=N-1; i>0; i--){
        int pos=i;
        city  viewing= cities[i];
        double d2=pow((current.x-viewing.x),2)+pow((current.y-viewing.y),2);
        double ind=viewing.ind;
        for (int j=1; j<i; j++){
            viewing=cities[j];
            double D2=pow((current.x-viewing.x),2)+pow((current.y-viewing.y),2);
            if ((D2 < d2)||((D2==d2)&&(viewing.ind<ind))){
                pos=j;
                d2=D2;
                ind=viewing.ind;
            }
        }
        S+=sqrt(d2);
        current=cities[pos];
        cities[pos]=cities[i];
    }
    return S+sqrt(pow((cities[0].x-cities[1].x),2)+pow((cities[0].y-cities[1].y),2));
}

The function implements the following algorithm: start at city[0], find nearest city, go there, find nearest unvisited city, go there, repeat until no cities left, go to city[0].


texts:
Would like some feedback on a code style exercise motivated by this PythagTriple algorihtm. I started with the Rosetta Code - "efficient C" solution  (not the naive one) and refactored it heavily into modern C++17.

It doesn't quite match their "Task spec". That that was not the focus. However, it could very easily be adopted to do so - just a few changes in main().Performance appears very similar to the C code I started with and the generated ASM seems reasonable.

But the main focus here is style, ease of readability, maintenance and correctness.

Specific feedback points I am looking for:

Use of the lambda to process each triple
Way of constraining the template to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)
Use of initialisers for static data. Also is there a way to get away from the {{ .. {{ .. {},{},{} .. }} .. }}  craziness? 4 extra opening and closing braces.
Use of specific type for vec3 and a using alias for trans
Body of the transform() function. Is there a map() ... splat way?
General function signatures / use of const, constexpr, attributes etc
Use of "by value" vs "by ref" semantics for triples / tranforms etc. There are some "arguably redundant" const T&s in there which were just as fast as "by value" (probably copy elided).
More algorithmic question: The algorithm as implemented is constrained by max_perimeter and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) "weird order". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative .find_XX() methods to do that.

EDIT: There is updated code in a separate answer below, integrating the feedback.

#include <array>
#include <iostream>

namespace pythag {

class triple {
 public:
  const long _a;
  const long _b;
  const long _c;

  template <typename F>
  constexpr void find(long max_perim, F&& proc) {
    if (perimeter() > max_perim) return;
    proc(*this);
    for (auto& T : U) transform(T).find(max_perim, proc);
  }

  [[nodiscard]] constexpr long perimeter() const noexcept { return _a + _b + _c; }

  friend std::ostream& operator<<(std::ostream& stream, const triple t) noexcept {
    return stream << t._a << ", " << t._b << ", " << t._c;
  }

private:
  struct vec3 {  // a strong type to distinguish from triple
    const int _x;
    const int _y;
    const int _z;
  };

  using trans = std::array<vec3, 3>;

  [[nodiscard]] constexpr long dot(vec3 V) const noexcept {
    return V._x * _a + V._y * _b + V._z * _c;
  }

  [[nodiscard]] constexpr triple transform(const trans& T) const noexcept {
    return triple{dot(T[0]), dot(T[1]), dot(T[2])};
  }

  static constexpr auto U = std::array<trans, 3>{{
      // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships
      // clang-format off
      {{{  1, -2,  2},     // vec3 U[0][0]
        {  2, -1,  2},     // vec3 U[0][1]
        {  2, -2,  3}}},   // vec3 U[0][1]

      {{{  1,  2,  2},     // vec3 U[1][0]
        {  2,  1,  2},     // vec3 U[1][1]
        {  2,  2,  3}}},   // vec3 U[1][2]

      {{{ -1,  2,  2},     // vec3 U[2][0]
        { -2,  1,  2},     // vec3 U[2][1]
        { -2,  2,  3}}},   // vec3 U[2][2]
      // clang-format on
  }};
};

} // namespace pythag

int main() {
  // basic usage demo
  long sum_peri = 0;
  long count = 0;

  pythag::triple{3, 4, 5}.find(
      100'000'000, // produces 7'023'027 "primitive" triples in <100ms on i7 2600
      // [](const auto& t) { std::cout << t << "\n"; });  // print option. slow obviously
      [&sum_peri, &count](const auto& t) { sum_peri += t.perimeter(); ++count; });

  std::cout << count << "\n";        // these 2 lines are just a way to prevent
  return (sum_peri ^ count) & 0xff;  // entire programme being optimised away
}


texts:
I am building a JS router and would like to have some help doing it.  It will work like so:

A list of routes is given with a URL pattern attached in each one.

[
  { url : "/home"},
  { url : "/user/:id"}
]

I want a function that will find the appropriate pattern when we pass it a route URL and will return the object of parameters:

getRouteParams("/home");    // {params: {}}
getRouteParams("/user/42"); // {params: {id: "42"}}
getRouteParams("/contact"); // null

I tried to do something with some parts of code I have found on the web and here is what I ended up with:

var routes = [
  { url : "/home"},
  { url : "/user/:id"}
];

function getRouteParams(url) {
  var argsVal = null;
  var x = 0;
  var result = {};
  for(; routes.length; x++){
    var routeMatcher = new RegExp(routes[x].url.replace(/(:\w+)/g, '([\\w-]+)'));
    argsVal = url.match(routeMatcher);
    if(argsVal) {
      argsVal.shift();
      result.params = makeObj(argsVal, routes[x].url);
      break;
    }
  }
  return result;

  function makeObj(vals, url) {
    var routeParts = url.split('/');
    var options = {};
    for(var i=0, j=0; i<routeParts.length; i++) {
      if(routeParts[i].indexOf(":") !== -1) {
        options[routeParts[i].slice(1)] = vals[j++];
      }
    }
    return options;
  }
}

console.log(getRouteParams("/home"));    // {params: {}}
console.log(getRouteParams("/user/42")); // {params: {id: "42"}}
console.log(getRouteParams("/contact")); // null)

This is a bit more sophisticated but the idea is there. Could someone help me improve on what I did?


texts:
So I wrote this fixed timestep & rendering game loop.
I am posting it here to see if there are ways to optimize it/make it more accurate.

    const float updatesRate = 1 / 60.0f;
    const float framesRate = 1 / 308.0f;

    double currentTime = hireTimeInSeconds( );
    double accumulator = 0.0;
    double accumulator2 = 0.0;
    uint32_t frames = 0, updates = 0;
    double timer = hireTimeInSeconds( );

    while ( true ) {

        double newTime = hireTimeInSeconds( );

        if ( newTime - timer >= 1 ) {

            //Printing fps and ups here

            updates = 0;
            frames = 0;
            timer = newTime;
        }

        double frameTime = newTime - currentTime;
        if ( frameTime > 0.25 ) frameTime = 0.25;
        currentTime = newTime;
        accumulator += frameTime;
        accumulator2 += frameTime;

        //Polling input here

        while ( accumulator >= updatesRate ) {

            //Updating here
            accumulator -= updatesRate;
            updates++;
        }

        const double alpha = accumulator / updatesRate;

        while ( accumulator2 >= framesRate ) {
            //Rendering
            frames++;
            accumulator2 -= framesRate;
        }
    }

```


texts: Sending notifications with Django channels

texts:
I have project on Django wich use Django Channels. I use Django Channel for sending notifications to users who are subscribed to articles changes (adding/editing/deleting comments on article).

So I've chosen this way of realization: every group of channels is an article and when changes happen, script sends notification to relevant groups. My code works correctly but I have some doubts if my choice of way of realization is most appropriate for this task. I need advice what is the best practice in my case?

Solution:

consumers.py

from channels.generic.websocket import AsyncJsonWebsocketConsumer
from channels.db import database_sync_to_async
from project.apps.account.models import UserStatus
from .models import CommentSubscribe

class CommentNotificationConsumer(AsyncJsonWebsocketConsumer):

    async def connect(self):
        await self.accept()
        if not self.scope['user'].is_anonymous:
            groups = await database_sync_to_async(self.get_users_subscription)()
            await database_sync_to_async(self.change_user_status)(True)
            await self.add_subscriptions(groups)

    async def add_subscriptions(self, groups):
        for group in groups:
            await self.channel_layer.group_add(
                'article_{0}'.format(group.article_id),
                self.channel_name
            )

    async def receive_json(self, content, **kwargs):
        command = content.get('command', None)
        article_id = content.get('article_id', None)
        if command == 'subscribe':
            await self.subscribe(article_id)
        elif command == 'unsubscribe':
            await self.unsubscribe(article_id)
        else:
            await self.send_json({
                'error': 'unknown command'
            })

    async def disconnect(self, code):
        await database_sync_to_async(self.change_user_status)(False)

    async def send_notification(self, action):
        await self.send_json(action)

    async def subscribe(self, article_id):
        await self.channel_layer.group_add(
            'article_{0}'.format(article_id),
            self.channel_name
        )

    async def unsubscribe(self, article_id):
        await self.channel_layer.group_discard(
            'article_{0}'.format(article_id),
            self.channel_name
        )

    def get_users_subscription(self):
        return CommentSubscribe.objects.filter(
            user=self.scope['user']
        )

    def change_user_status(self, online):
        return UserStatus.objects.filter(
            user=self.scope['user']
        ).update(online=online)

views.py

from .notify import send_comment_notification

class CreateComment(CreateView):

    ...

    def form_valid(self, form):
        ...
        super().form_valid(form)
        send_comment_notification('create', article_id)

class UpdateComment(UpdateView):

    ...

    def form_valid(self, form):
        ...
        super().form_valid(form)
        send_comment_notification('update', article_id)

class DeleteComment(DeleteView):

    ...

    def delete(self, request, *args, **kwargs):
        ...
        send_comment_notification('delete', article_id)

notify.py

...

def send_comment_notification(action, article_id):
    channel_layer = get_channel_layer()
    group_name = 'article_{0}'.format(article_id)
    async_to_sync(channel_layer.group_send)(
        group_name,
        {
            'type': 'send.notification',
            'data': {
                'action': action
            }
        }
    )


texts:
I wrote the following simple 1 producer - 1 consumer problem, in attempt to learn some C++11 threading / generics.

#include <iostream>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <thread>

struct data {
    int x, y;
    std::string s;

    data() : s("test") {
        x = std::rand() % 1000000;
        y = std::rand() % 1000000;
    }

    friend std::ostream& operator<<(std::ostream& os, const struct data d) {
        os << d.x << ", " << d.y << ", " << d.s << "\n";
    }
};

typedef struct data elem_t;

template <typename T>
class Buffer
{
public:
    Buffer(): m_size(1) {}
    Buffer(int s): m_size(s) {}

    void add(T x) {
        while (true) {
            std::unique_lock<std::mutex> locker(m_mtx);
            m_cond.wait(locker, [this](){return m_buffer.size() < m_size;});

            m_buffer.push_back(x);

            locker.unlock();
            m_cond.notify_all();

            return;
        }
    }

    T remove() {
        while (true) {
            std::unique_lock<std::mutex> locker(m_mtx);
            m_cond.wait(locker, [this](){return m_buffer.size() > 0;});

            T x = m_buffer.back();
            m_buffer.pop_back();

            locker.unlock();
            m_cond.notify_all();

            return x;
        }
    }

private:
    std::mutex m_mtx;
    std::condition_variable m_cond;

    std::deque<T> m_buffer;
    unsigned int m_size;
};

template <typename T>
class Producer
{
public:
    Producer() : m_buf(nullptr) {}
    Producer(std::string&& id, Buffer<T> *buf) : m_id(id), m_buf(buf) {}

    void produce() {
        while (true) {
            T x = T();

            m_buf->add(x);
            std::cout << x;

            int sleep = std::rand() % 1000 + 10;
            std::this_thread::sleep_for(std::chrono::milliseconds(sleep));
        }
    }

private:
    Buffer<T> *m_buf;
    std::string m_id;
};

template <typename T = int>
class Consumer
{
public:
    Consumer() : m_buf(nullptr) {}
    Consumer(std::string&& id, Buffer<T> *buf) : m_id(id), m_buf(buf) {}

    void consume() {
        while(true) {
            T x = m_buf->remove();
            std::cout << x;

            int sleep = std::rand() % 1000 + 10;
            std::this_thread::sleep_for(std::chrono::milliseconds(sleep));
        }
    }

private:
    Buffer<T> *m_buf;
    std::string m_id;
};

int main(int argc, char const *argv[])
{
    std::srand(std::time(nullptr));

    Buffer<elem_t> *buffer = new Buffer<elem_t>(std::stoi(argv[1]));
    Producer<elem_t> *p = new Producer<elem_t>("prod", buffer);
    Consumer<elem_t> *c = new Consumer<elem_t>("cons", buffer);

    std::thread pt(&Producer<elem_t>::produce, p);
    std::thread ct(&Consumer<elem_t>::consume, c);

    pt.join();
    ct.join();

    return 0;
}

The main concern I am having with this code is regarding genericity.
I have a generic buffer Buffer<T> (which is basically a std::deque<T>) and the produced value: T x = T();

For now, T = struct data, and everything works because of data(), but if T = int, for example, things start to get ugly.

One idea I have is to define a struct data packing all the needed fields, and then remove templates from classes (i.e. std::deque<struct data> only).

So, are templates an overkill here, and if not what is the / a correct way of expressing this code with them?
Also, are there any other problems / code smells / things to improve?


texts: Calculator that works by compiling and running a .java file

texts:
I wrote this code for a simple calculator. It creates a java file from the term, compiles and executes it. Now my question is : Is there a better way of doing this ? Would it be more efficient to analyze the string and then evaluate it step by step in the program ? Is this the right way of doing java ? Do I have to improve my 'style' ?

class Calculator {
    public static double evaluate(String term) throws IOException {
        String result=term;
        char[] n={'0','1','2','3','4','5','6','7','8','9','+','-','*','/','(',')'};
        boolean number=false;
        boolean add=true;
        int adds=0;
        for (int i=0; i < term.length(); i++) {
            number=false;
            for (int i2=0; i2 < n.length; i2++) {
                if (term.charAt(i)==n[i2]) {
                    number=true;
                    add=true;
                    break;
                } else {
                }
            }
            if (number==false && add==true)  {
                String p1=result.substring(i+adds*5,result.length());
                String p2=result.substring(0,i+adds*5);
                result=p2+"Math."+p1;
                adds++;
                add=false;
            }
        }
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        FileOutputStream terminus = new FileOutputStream("Term.java");
        terminus.write(new String("import java.lang.Math; import java.io.FileOutputStream; import java.io.IOException; public class Term { public static void main(String[] args) {try {FileOutputStream result = new FileOutputStream(\"result.txt\");result.write(Double.toString("+result+").getBytes());} catch (Exception e) {}}}").getBytes());
        compiler.run(System.in, System.out, System.err, "Term.java");
        Runtime.getRuntime().exec("java Term");
        int i=0;
        FileInputStream resu = new FileInputStream("result.txt");
        String r="";
        i=resu.read();
        while(i != -1) {
            r=r+new String(new char[] {(char)(i)});
            i=resu.read();
        }
        return Double.parseDouble(r);
    }
}

And here's how I use it :

          try {
          System.out.println(Calculator.evaluate("cos(1+1)*sin(7+9)/atan(7)"));
          }
          catch (Exception e) {}


texts:
I have a graph which we can think of is representing a network of train tracks. Each node is a station and each edge is a piece of track connecting two stations. Each station node may be connected by more than one track and all tracks are one way (i.e the graph is directed).

My job is to find as many routes as possible connecting one node with a set of destination nodes. Routes may contain cycles to the train track analogy breaks down here, but whatever. I have Python code to perform this task, but it is to slow so I would love to get some help in making it faster. Below is my traversal function:

from collections import deque
from itertools import product

def travel(graph, start, dests, count):
    queue = deque([[(start, None)]])
    paths = []
    while queue:
        path = queue.popleft()
        at = path[-1][0]
        if at in dests:
            pp = [p[1] for p in path[1:]]
            for real_path in product(*pp):
                paths.append(''.join(real_path))
                count -= 1
                if count == 0:
                    return paths
        adj = graph.get(at, {})
        for item in adj.items():
            queue.append(path + [item])
    return paths

Called with a sample graph:

G = {
    1 : {2 : 'mqr', 3 : 't'},
    2 : {3 : 'q'},
    3 : {1 : 'S', 4 : '_'},
    4 : {3 : 't', 1 : 'xUI', 5 : '=+/'},
    5 : {4 : 'q', 6 : '1'},
    6 : {1 : '0'}
}
print(len(set(travel(G, 1, [6], 1000))))

1000 unique strings representing paths through the graph will be generated. Ideas on how to improve the travel function would be greatly appreciated. Also on the format I'm using for representing the graph. It is usually very efficient to store a graph as a dict whose values are themselves dicts, but perhaps there is a better format.


texts: JavaScript function to create HTML select option elements

texts:
I made this function to get rid of writing numerical option values in a HTML-select manually.

From what I have seen so far it works as expected. But hints and suggestions are welcome anyway.

// Trying it out.
var selects = document.querySelectorAll('.drop-down');
selects = Array.prototype.slice.call(selects);

createOptions(selects[0], -9, 9, 8);

for (var i = 1; i < selects.length; i++) {
  createOptions( selects[i],
                 i * (-1 * Math.pow(10, i)),
                 i * Math.pow(10, i));
}

// The actual function ...

// The 1st Parameter is the HTML-element, the
// second is the bottom-limit, the third the
// upper limit.
// The fourth, optional parameter allows to
// define the selected-option.

function createOptions( selectElement,
                        countOptionsStart,
                        countOptionsEnd,
                        preSelected ) {
    var bottom = countOptionsStart + '';
    var top = countOptionsEnd + '';
    var demand; // Count of needed chars.

    preSelected = preSelected || 0;

    var getLeadingZeros = function(demand, value) {
      var chars = value.toString() // Convert to string.
                       .split(''); // Make an array.
      // As long as the count of chars is less then
      // the demanded count iterate ...
      while (chars.length < demand) {
        // If the first element in the array contains
        // an minus ('-') then use splice() for to
        // add a zero at index 1.
        if (chars[0] === '-') {
          chars.splice(1, 0, '0');
        } else {
          // ... otherwise add the zero at the
          // beginning.
          chars.unshift('0');
        }
      }
      // Concat the array-elements to a string and
      // return this string.
      return chars.join('');
    }

    // The longer string is taken.
    demand = bottom.length >= top.length ? bottom.length : top.length;

    // Constructing at adding the option-elements.
   for (var i = countOptionsStart; i <= countOptionsEnd; i++) {
     var option = document.createElement('option');
     var optionInner;
      var innerHTML = i + '';

      if (innerHTML.length < demand)
        innerHTML = getLeadingZeros(demand, innerHTML);

      optionInner = document.createTextNode(innerHTML);
     option.setAttribute('value', i);

     if (i === preSelected) option.setAttribute('selected', 'selected');

     option.appendChild(optionInner);
     selectElement.appendChild(option);
   }
}
<select class="drop-down"></select>
<select class="drop-down"></select>
<select class="drop-down"></select>
<select class="drop-down"></select>


texts:
I'm trying to find patterns of different length in a given string. How can I improve it? Are there problems?

function find(pattern,str) {
   var  arr = [];
   for (i= 0;i<str.length;i++) {
      if(pattern== str.slice(i,pattern.length+i)) {
       arr.push([i,pattern.length-1+i]);
     };
  };
   if(!arr.length) { return false;} else { return arr;};
};

find('abfd','abfdffdabfdfaffab');


texts: Returning search results based off checkboxes

texts:
I use the following code to filter data from SQL and it works fine. However, below code is vulnerable to SQL injection, but all the $post values are checkbox value (it's not user input).  So can I use below code?

Or do I need to use "prepared statement" as per this answer? I can only send number in array.

Conn.php

    try {

    //create PDO connection
    $conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
    //show error
    echo '
' . $e->getMessage() . '
';
    exit;
}

INDEX

     <input type="radio" class="filter_all cate" name="cate" id="car" value="Car">
     Car

script

$(document).ready(function () {
            filter_data();
            function filter_data() {
                $('.filter_data');
                var action = 'fetch_data';
                var cate = get_filter('cate');
                $.ajax({
                    url: "fetch.php",
                    method: "POST",
                    data: {
                        action: action,
                        cate: cate
                    },
                    success: function (data) {
                        $('.filter_data').html(data);
                    }
                });
            }
            function get_filter(class_name) {
                var filter = [];
                $('.' + class_name + ':checked').each(function () {
                    filter.push($(this).val());
                });
                return filter;
            }
            $('.filter_all').click(function () {
                filter_data();
            });
        });

fetch.php

if (isset($_POST["action"])) {

 $query = "SELECT * FROM allpostdata WHERE sts = '1'";

if (isset($_POST["cate"])) {
    $cate = implode("','", $_POST["cate"]);
    $query .= "AND sca IN('" . $cate . "')";
}

$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
    foreach ($result as $row) {
    $output .= '' . $row['link']. '
 }
} else {
    $output = '
No Data Found
';
}
echo $output;
}