texts: Increasing performance of OpenMP based advection equation solver for Xeon Phi

texts:
I am solving linear advection equation in order to learn parallel programming. I am running this code on Xeon Phi co processor. Below is a plot of how it scales up with increasing number of threads. I am still in learning process and this is my first "parallel" code. I am also not very familiar with architecture specific optimization.

Comments on how to improve the performance of this code and what other stuff should I look into will be great. Also link for writeup or further tutorials to follow will be really helpful.

The plot is for nx=100000.

#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
#include <sys/time.h>
#include <unistd.h>

int64_t TimeInMicros() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec*1000000 + tv.tv_usec;
}

struct Grid{
  int nx;
  double *u, *f, *res;
  double a, cfl, dx, tf;
};

struct ThreadData{
  int tid, maxthreads;
  struct Grid *grid;

};

void *solver(void *args){

  struct ThreadData *td = (struct ThreadData *)args;

  int tid = td->tid;

  struct Grid *grid = td->grid;

  double *u = grid->u;
  double *f = grid->f;
  double *res = grid->res;

  int nx = grid->nx;
  double tf = grid->tf;
  double cfl = grid->cfl;
  double a = grid->a;
  double dx = grid->dx;

  double dt = cfl*dx/a;
  double t = 0.0;

  int chunk = nx/(td->maxthreads);
  int start = tid*chunk;

  int rc;

  while(t < tf){
    // sync here
#pragma omp barrier

    if(start == 0){
      f[start+1:chunk] = a*u[start:chunk];
    }
    else{
      f[start:chunk+1] = a*u[start-1:chunk+1];
    }

    // sync here
#pragma omp barrier

    if(start == 0){
      f[start] = f[nx-1];
    }

    res[start:chunk] = -(f[start+1:chunk] - f[start:chunk])/dx;
    u[start:chunk] += res[start:chunk]*dt;
    t+=dt;
  }
  return NULL;
}

int main(int argc, char*argv[]){
  int nx=atoi(argv[1]);
  int nthreads=atoi(argv[2]);

  if(nx%nthreads != 0){
    printf("ERROR: Number of cells should be integral multiple of number of threads \n");
    exit(1);
  }

  double *u = new double[nx]();
  double *res = new double[nx]();
  double *f = new double[nx+1]();

  double dx = 1.0/nx;
  double cfl = 0.9;
  double a = 1.0;
  double tf = 1.0;
  int i;

  // initialize
  u[0:nx] = 0.0;
  u[nx/4:nx/2] = 1.0;
  f[0:nx+1] = 0.0;
  res[0:nx] = 0.0;

  struct Grid grid;
  grid.nx = nx;
  grid.a = a;
  grid.cfl = cfl;
  grid.dx = dx;
  grid.u = u;
  grid.res = res;
  grid.f = f;
  grid.tf = tf;

  int64_t t1 = TimeInMicros();

  #pragma omp parallel num_threads(nthreads)
  {
    struct ThreadData td;

    td.tid = omp_get_thread_num();
    td.grid = &grid;
    td.maxthreads = omp_get_num_threads();
    if(nthreads != omp_get_num_threads()) {
      if(td.tid == 0) {
        printf("ERROR: Number of cells should be integral multiple of number of threads \n");
        exit(-1);
      }
    }
    else {
      solver(&td);
    }
  }

  int64_t t2 = TimeInMicros();
  printf("Execution time: %.10f\n", (t2-t1)*1e-6);

  FILE * outfile;
  outfile = fopen("results.txt", "w+");
  for(i = 0; i < nx; i++){
    fprintf(outfile, "%.10f %.10f\n", i*dx, grid.u[i]);
  }
  fclose(outfile);

  delete[] u;
  delete[] res;
  delete[] f;

}


texts: Pandas filter dataframe on multiple columns wrt corresponding column values from another dataframe

texts:
I have a pandas dataframe, df1:
a b c d e f
1 1 1 x 1 5
1 1 1 x 1 6
1 1 1 y 1 5
1 1 1 y 1 7

and another dataframe, df2:
a b c d e f
1 1 1 x 1 5

Now I want to filter df1 on columns a, b, c, d if it is present in respective columns of df2. This is what I tried:
mask = df1['a'].isin(df2['a']) & df1['b'].isin(df2['b']) & df1['c'].isin(df2['c']) & df1['d'].isin(df2['d'])
df_new = df1[mask]

so df_new finally contains:
a b c d e f
1 1 1 x 1 5
1 1 1 x 1 6

I am looking for a better approach as there are a lot of columns to compare and a lot of rows, both in df1 and df2.


texts:
I am new to c# and decided to write a classic todo app. The implementation of my application now is like this: there is a Task class that describes the task. The List class acts simultaneously as a storage and has methods for creating, deleting, and displaying tasks. How good is this approach, how can you do better (if possible)? I would like a full code review.
There is Program.cs:
using System;

namespace ToDo
{
    class Program
    {
        static void Main(string[] args)
        {
            List list = new List();
            list.AddTask("Task №1");
            list.AddTask("Task №2");
            list.AddTask("Task №3");
            list.AddTask("Task №4");
            list.AddTask("Task №5");
            list.WriteTasks();
            list.RemoveTask(2);
            list.WriteTasks();
        }
    }
}

List.cs:
using System;
using System.Collections.Generic;
using System.Text;

namespace ToDo
{
    class List
    {
        private List<Task> tasks = new List<Task>();
        public void AddTask(string body)
        {
            tasks.Add(new Task() { Body = body });
        }
        public void WriteTasks()
        {
            for (int i = 0; i < tasks.Count; i++)
            {
                Console.WriteLine($"[{i+1}]: {tasks[i].Body}");
            }

            Console.ReadKey();
        }
        public void RemoveTask(int number)
        {
            for (int i = 0; i < tasks.Count; i++)
            {
                if (number == i + 1)
                {
                    tasks.RemoveAt(i);
                }
            }
        }
    }
}

Task.cs:
using System;
using System.Collections.Generic;
using System.Text;

namespace ToDo
{
    class Task
    {
        public string Body { get; set; }
    }
}


texts:
I have a binary file with alternating uint8 and uint64 data stamps.
I read those in by using the following line:

clicks = np.fromfile(filename, dtype=[('time','u8'),('channel','u2')])

This works well and fast enough. Now i want to go though the array and set the time values to the time difference with respect to the last 'click' seen on channel 7 (the so called gate clicks). The array is sorted by time. In C I would do this with a simple for loop going over the array (and this works extremly fast). When I implement this in python i get a data rate of only 2 mb/s. The best solution i came up with looks like this:

    ''' create an array with the indices of the channel-7 clicks '''
    gate_clicks = clicks['channel']==7
    gate_ind = np.array(range(len(gate_clicks)))
    gate_ind = gate_ind[gate_clicks]
    gate_ind_shift = np.delete(gate_ind,0,0)

    ''' slice out the clicks between to gate clicks and set the time stamps '''
    for start,end in zip(gate_ind,gate_ind_shift):
        start_time = data[start]['time']
        slice = data[start:end]
        slice['time'] = slice['time']-start_time
        data[start:end] = slice

This gives a data rate of about 4.


texts:
This was my second project as a beginner in Java programming. Please provide feedback/ tips on my program.

import java.util.Scanner;

public class Area {
    public static void main(String[] args) {

        Scanner Area = new Scanner (System.in);

        double length, width,totalArea, height;
        String shape, unit;
        int loop = 0;

        while (loop == 0){

        System.out.println("Which shape do you want to find the area?");
        shape = Area. next();

        switch (shape) {

        case "rectangle":
            System.out.println("Please enter the leghth of the rectangle: ");
            length = Area. nextDouble ();
            System.out.println("Please enter the width of the rectangle: ");
            width = Area. nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = length*width;
            System.out.println(totalArea+unit);
            break;

        case "square" :
            System.out.println("Please enter the leghth of the square: ");
            length = Area. nextDouble ();
            System.out.println("Please enter the width of the square: ");
            width = Area. nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = length*width;
            System.out.println(totalArea+unit);
            break;

        case "triangle" :
            System.out.println("Please enter the base of the triangle: ");
            length = Area. nextDouble ();
            System.out.println("Please enter the height of the triangle: ");
            width = Area. nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = ((length*width)/2);
            System.out.println(totalArea+unit);
            break;

        case "parallelogram" :
            System.out.println("Please enter the base of the parallelogram: ");
            length = Area. nextDouble ();
            System.out.println("Please enter the height of the parallelogram: ");
            width = Area. nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = length*width;
            System.out.println(totalArea+unit);
            break;

        case "circle" :
            System.out.println("Please enter the radius of the circle: ");
            length = Area. nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = 3.14*(Math.pow(length, 2));
            System.out.println(totalArea+unit);
            break;

        case "rhombus" :
            System.out.println("Please enter the first diagonal of the rhombus: ");
            length = Area. nextDouble();
            System.out.println("Please enter the second diagonal of the rhombus: ");
            width = Area. nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = ((length*width)/2);
            System.out.println(totalArea+unit);
            break;

        case "trapezoid" :
            System.out.println("Please enter the first base of the trapezoid: ");
            length = Area. nextDouble();
            System.out.println("Please enter the second base of the trapezoid: ");
            width = Area. nextDouble();
            System.out.println("Please enter the height of the trapezoid: ");
            height = Area.nextDouble();
            System.out.println("What is the unit of the shape?");
            unit = Area.next();
            totalArea = (((length+width)*height)/2);
            System.out.println(totalArea+unit);
            break;

        default:
            System.out.println("The shape you entered is not recongnized");
            }
        }
    }
}


texts:
In a C project I want to reuse curl easy handles. The flow of program is like:

Client --> C Application --> Call URL1, do something, Call URL2, do something, Call URL3...

In short, for each client request, the same set of URLs are called.

I initially create the curl easy handle when the program starts. The main program creates a configurable number of child, so each child gets its own easy handle.

static int child_init(int rank) {
    LM_NOTICE("init_child [%d]  pid [%d]\n", rank, getpid());

    pid = my_pid();

    curl_global_init(CURL_GLOBAL_ALL);
    // initialize curl handle
    curl = curl_easy_init();
    if (!curl) {
        LM_ERR("Child %d: Curl initialization failed.\n", rank);
        return -1;
    }
    //create some connections before actual requests come.
    curl_head(URL);
    return 0;
}

I created a C file where the functions are created to handle GET/POST/PUT etc requests:

int curl_head(const char* url) {
    if (!url) {
        LM_ERR("URL not provided. Returning with error.\n");
        return -1;
    }
    CURLcode res;
    int http_code = 0;
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "charsets: utf-8");

    /* set URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
    curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);

    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        LM_ERR("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    LM_DBG("HTTP return CODE %d\n", http_code);
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return http_code;
}

int curl_post(const char* url, char *postdata) {
    if (!url) {
        LM_ERR("URL not provided. Returning with error.\n");
        return -1;
    }

    CURLcode res;

    int http_code = 0;
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charsets: utf-8");

    /* set URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");

    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        LM_ERR("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return http_code;
}

When somewhere in the program I want to call the WS I call the desired function as curl_post(url).

Am I doing this correctly or are there any flaws in this implementation?


texts: Is this code thread-safe - Singleton Implementation using Concurrent Dictionary

texts:
class Connection
{
    private string param1;
    private string param2;
    private static readonly ConcurrentDictionary<Tuple<string, string>, Connection>
        connections = new ConcurrentDictionary<Tuple<string, string>, Connection>();
    private Connection()
    {
    //Prevent instantiation
    }

    private Connection(string param1, string param2)
    {
        this.param1 = param1;
        this.param2 = param2;
    }

    public static Connection getInstance(string param1, string param2)
    {
        Connection conn = activeConnections.GetOrAdd(new Tuple<string, string>
            param1,param2), new Connection (param1, param2));
        return conn;
    }
}


texts:
I'm working on this problem, and any advice on performance improvement, bugs or code style issues are appreciated.

Problem

  Description

  There are N gas stations on a straight, M kilo-meters long highway.
  The i-th gas station is Ai kilometers away from the beginning of the
  highway. (It is guaranteed that there is one gas station at each end
  of the highway.)

  Now the mayor can build K more gas stations. He wants to minimize the
  maximum distance between two adjacent gas station. Can you help him?

  Input:

  The first line contains 3 integer N, M, k. (2 <= N <= 1000, 1 <= M, K
  <= 100000)

  The second line contains N integer, A1, A2, ... AN. (0 = A1 <= A2 <=
  ... <= AN = M)

  Output:

  The minimized maximum distance rounded to one decimal place.

  Sample Input

3 10 2
0 2 10

  Sample Output

2.7

My major ideas are:

Calculate lower and upper bound of gas station distance (lower bound 1, higher bound is current max distance between two existing gas stations)
Do a binary search for lower bound and higher bound, to see if we can fit with k gas stations

If we can fit, then try to lower higher bound of binary search
If we cannot fit, then try to higher lower bound of binary search

At the end, the number is minimal of max distance between gas stations
Since it requires one decimal place, I +/- 0.1 other than +/- 1

def max_gas_distance(distances, k):
    max_distance = 0
    for i, v in enumerate(distances):
        if i > 0:
            max_distance = max(max_distance, v - distances[i-1])
    # final result between 1 and max_distance
    l = 1.0
    h = max_distance
    while l <= h:
        mid = l + (h-l)/2.0
        if valid(distances, mid, k):
            h = mid - 0.1
        else:
            l = mid + 0.1
    return l
def valid(distances, mid, k):
    additional_gas_station = 0
    for i,v in enumerate(distances):
        if i > 0 and v - distances[i-1] > mid:
            additional_gas_station += (v - distances[i-1]) / mid
            if additional_gas_station >= k+1:
                return False
    return True

if __name__ == "__main__":
    existing_gas_stations = [0,2,10]
    k = 2.0
    print max_gas_distance(existing_gas_stations, k)


texts:
I've got a lot of links (150+) in an href (here I can only post 2) and I want them to be opened in a new tab or window. I've got this piece of code that works, but before I add it to my website and before I add it to a lot of articles of mine (250+), I want to make sure the syntax of the code is 100% correct. Also, do I need the
?

test

test


texts:
I have made this code to determine the users grade for a quiz. However I've just been thinking that maybe I could shorten the code somehow? as its just a lot of if and elif statements.

if($_SESSION['numberQuestions'] == 10){
        if($_SESSION['score'] == 10){
            $grade = "A+";
        }
        elseif($_SESSION['score'] == 9){
            $grade = "A";
        }
        elseif($_SESSION['score'] == 8){
            $grade = "B";
        }
        elseif($_SESSION['score'] == 7){
            $grade = "C";
        }
        elseif($_SESSION['score'] == 6){
            $grade = "D";
        }
        elseif($_SESSION['score'] <= 5){
            $grade = "F";
        }
    }
    if($_SESSION['numberQuestions'] == 5){
        if($_SESSION['score'] == 5){
            $grade = "A+";
        }
        elseif($_SESSION['score'] == 4){
            $grade = "A";
        }
        elseif($_SESSION['score'] == 3){
            $grade = "B";
        }
        elseif($_SESSION['score'] == 2){
            $grade = "C";
        }
        elseif($_SESSION['score'] == 1){
            $grade = "D";
        }
        elseif($_SESSION['score'] == 0){
            $grade = "F";
        }
    }


texts:
I am trying to write a SynchronizedQueue wrapper class to provide a simple synchronized interface to underlying standard std::queue.
Could you have a review and let me know if any pitfalls and improvements you see ?
Too many mutexes/locks ? I wanted to to use condition variables to wait rather than mutexes for push & pop notifications.
Any insights is highly appreciated as I have rarely written multi-threaded programs.

#pragma once

#include <mutex>
#include <condition_variable>
#include <queue>
#include <cstdint>

template<typename T>
class SynchronizedQueue
{
public:
  SynchronizedQueue(size_t maxItems)
    : synchronizedQueue_()
    , queueMutex_()
    , pushMutex_()
    , popMutex_()
    , pushCV_()
    , popCV_()
    , MAX_ITEMS(maxItems)
  {
  }

  void push(const T& item)
  {
    std::unique_lock<std::mutex> scopedLock(pushMutex_);
    while (isFull())
    {
      std::unique_lock<std::mutex> pushLock(queueMutex_);
      popCV_.wait(pushLock);
    }

    {
      std::unique_lock<std::mutex> scopedLock(queueMutex_);
      synchronizedQueue_.push(item);
      pushCV_.notify_one();
    }
  }

  T pop()
  {
    std::unique_lock<std::mutex> scopedLock(popMutex_);
    while (isEmpty())
    {
      std::unique_lock<std::mutex> scopedLock(queueMutex_);
      pushCV_.wait(scopedLock);
    }

    T t;
    {
      std::unique_lock<std::mutex> scopedLock(queueMutex_);
      t = synchronizedQueue_.front();
      synchronizedQueue_.pop();
      popCV_.notify_one();
    }

    return t;
  }

private:
  bool isEmpty()
  {
    std::unique_lock<std::mutex> scopedLock(queueMutex_);
    return synchronizedQueue_.empty();
  }

  bool isFull()
  {
    std::unique_lock<std::mutex> scopedLock(queueMutex_);
    return synchronizedQueue_.size() == MAX_ITEMS;
  }

  std::queue<T> synchronizedQueue_;
  std::mutex queueMutex_, pushMutex_, popMutex_;
  std::condition_variable pushCV_, popCV_;
  size_t MAX_ITEMS;
};


texts: Force ConcurrentDictionary in a Singleton Registry to Collect Removed Items/Space

texts:
I have the following class which is used in a WebApi AspNetCore application as a singleton instance to store Strategy objects (reference type). The class is

/// <summary>
/// Class to allow singleton access to a common thread safe registry of registered strategies.
/// </summary>
public class StrategyRegister : IStrategyRegister
{
    private ConcurrentDictionary<long, Strategy> _registery;

    public StrategyRegister()
    {
        _registery = new ConcurrentDictionary<long, Strategy>();
    }

    public bool TryAdd(Strategy strategy)
    {
        if (_registery.ContainsKey(strategy.Id))
            throw new SystemException("The registry can never contain two identical strategy ids");
        return _registery.TryAdd(strategy.Id, strategy);
    }

    public bool TryRemove(long id)
    {
        if (!_registery.ContainsKey(id))
            return true;

        //GC.Collect();
        return _registery.TryRemove(id, out _);
    }

    public Strategy TryGet(long id)
    {
        if (_registery.ContainsKey(id))
            return _registery[id];
        return null;
    }

    public IEnumerable<Strategy> GetRegisteredStrategies()
    {
        return _registery.Select(kvp => kvp.Value);
    }
}

The problem is, as the ConcurrentDictionary grows large and items are removed, they are not being collected by the GC. I confirm this by adding the crude and nasty line GC.Collect() after every removal. When this is done, memory does not grow... I could make this "smarter" (still crude), by adding a timer to force collection every n seconds, but is there a better way, or should I be doing something obvious here?


texts: Complex scientific formula for nuclear magnetic resonance

texts:
I've been reading "clean code" tutorials, and I definitely see the value of using good names that "document themselves" to make intent clear. However, what can be done about complex formulas where describing the meaning of a symbol is difficult?

My solution is to include a reference to the math source, and then use names that relate as closely as possible to the published formula. The code would be unintelligible to another programmer, however, if they didn't have access to the source.

For example, I have a Python program that includes this function factory. The returned function is used elsewhere to plot a graph. The code itself looks like a nightmare:

def dnmr_twosinglet(va, vb, ka, wa, wb, pa):
    """
    Accept parameters describing a system of two exchanging, uncoupled nuclei,
    and return a function that requires only frequency as an argurment,
    that will calculate the intensity of the DNMR lineshape at that frequency.

    :param va: The frequency of nucleus 'a' at the slow exchange limit. va > vb
    :param vb: The frequency of nucleus 'b' at the slow exchange limit. vb < va
    :param ka: The rate constant for state a--> state b
    :param wa: The width at half heigh of the signal for nucleus a (at the slow
    exchange limit).
    :param wb: The width at half heigh of the signal for nucleus b (at the slow
    exchange limit).
    :param pa: The fraction of the population in state a.
    :param pa: fraction of population in state a
    wa, wb: peak widths at half height (slow exchange), used to calculate T2s

    returns: a function that takes v (x coord or numpy linspace) as an argument
    and returns intensity (y).
    """
    """
    Formulas for simulating two uncoupled spin-1/2 nuclei are derived from:
    Sandstrom, J. "Dynamic NMR Spectroscopy". Academic Press, 1982, p. 15.
    """

    pi = np.pi
    pi_squared = pi ** 2
    T2a = 1 / (pi * wa)
    T2b = 1 / (pi * wb)
    pb = 1 - pa
    tau = pb / ka
    dv = va - vb
    Dv = (va + vb) / 2
    P = tau * (1 / (T2a * T2b) + pi_squared * (dv ** 2)) + (pa / T2a + pb / T2b)
    p = 1 + tau * ((pb / T2a) + (pa / T2b))
    Q = tau * (- pi * dv * (pa - pb))
    R = pi * dv * tau * ((1 / T2b) - (1 / T2a)) + pi * dv * (pa - pb)
    r = 2 * pi * (1 + tau * ((1 / T2a) + (1 / T2b)))

    def calculate_intensity(v):
        """
        :param v: frequency
        :return: function that calculates the intensity at v
        """
        _Dv = Dv - v
        _P = P - tau * 4 * pi_squared * (_Dv ** 2)
        _Q = Q + tau * 2 * pi * _Dv
        _R = R + _Dv * r
        return(_P * p + _Q * _R) / (_P ** 2 + _R ** 2)
    return calculate_intensity

However, with the referenced formulae (a subset of which are reproduced below), the meaning of the code should be clear:

$$
  \textrm{v} = -C_0\frac{\bigg\{P\bigg[1+\tau\Big(\dfrac{p_B}{T_{2A}}+\dfrac{p_B}{T_{2B}}\Big)\bigg]+Q R\bigg\}}{P^2+R^2}
$$
$$
P=\tau\bigg[\frac{1}{T_{2A} \cdot T_{2B}}-4\pi^2\Delta\nu^2+\pi^2(\delta\nu)^2\bigg]+\frac{p_A}{T_{2A}}+\frac{p_B}{T_{2B}}\\
Q=\tau[2\pi\Delta\nu-\pi\delta\nu(p_A-p_B)]\\
R=2\pi\Delta\nu\bigg[1+\tau\Big(\frac{1}{T_{2A}}+\frac{1}{T_{2B}}\Big)\bigg]+\pi\delta\nu\tau\Big(\frac{1}{T_{2B}}-\frac{1}{T_{2A}}\Big)
+\pi\delta\nu(p_A-p_B)
$$

etc.

Is this practice considered OK, or could this be improved upon?


texts: Optimize setting parameters from query string

texts:
I am currently setting over a hundred global variables by performing individual checks against the URL string.

var Query_MenuTiles = getParameterByName("menutiles")
var Query_Link = getParameterByName("link")
var Query_Speed = getParameterByName("speed")

Unless it would slow things down, I assume that setting keys and properties of an object would be a cleaner way of doing this.

The getParameterByName function is as follows:

function getParameterByName(name, source ) {
    if (typeof source == 'undefined') {
        source = window.location.search
    }
    if ( user_fastquery == '1' ) {
        return search[name] || ''
    }
    else {
      name = name.toLowerCase()
      name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
      var regexS = "[\\?&]" + name + "=([^&#]*)"; //"=([^&#]*)";
      var regex = new RegExp(regexS);
      var query_x = 'back'
      var query_y = 'frame'
      if ( name != query_x ) {
        if ( source.indexOf("&" + query_x + "=") >= 0 ) {
            var array_source = source.split('&' + query_x + '=')
            source = array_source[0]
            var source_tail = array_source[1]
        }
        else if ( source.indexOf("?" + query_x + "=") >= 0 ) {
            var array_source = source.split("?" + query_x + "=" )
            source = array_source[0]
        }
      }
      var results = regex.exec( source );
      if(results == null)
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
}


texts:
This is a simple script which inserts data into a couple of tables. I'm very new to SQL so any feeback, of any kind, would be much appreciated!

DECLARE
      @Model_ID INT
    , @ModelVersion VARCHAR(10)
    , @ExistsInDM INT
    , @IsActive BIT

SET @ModelVersion = '2.46.7' -- new version number
SET @IsActive = '1'

SELECT  @Model_ID = Model_ID
FROM    [sch_AM].[tblDMModelVersion] WITH (NOLOCK)
WHERE   [ModelVersion] = @ModelVersion

IF @Model_ID IS NULL
BEGIN
    INSERT  INTO [sch_AM].[tblDMModelVersion]
            (  [ModelVersion]
                ,[IsActive]
                            )
    VALUES  ( @ModelVersion
                ,@IsActive
                )

    EXECUTE sch_AM.usp_GetActiveModel_ID @ModelVersion, @Model_ID OUTPUT

    SELECT @ExistsInDM = COUNT(Model_ID)
    FROM [sch_AM].[tblDMModelToTable] WITH (NOLOCK)
    WHERE Model_ID = @Model_ID

    IF @ExistsInDM = 0
        BEGIN
            INSERT INTO [sch_AM].[tblDMModelToTable]
            SELECT
                    @Model_ID
                    ,[Table_ID]
                    ,[TableVersion]
                    ,[UserViewable]
                    ,[TableRequiredByModel]
            FROM [sch_AM].[tblDMModelToTable] WITH (NOLOCK)
            WHERE Model_ID = 1
        END
END

SELECT * FROM [sch_AM].[tblDMModelVersion] WHERE Model_ID = @Model_ID
SELECT * FROM [sch_AM].[tblDMModelToTable] WHERE Model_ID = @Model_ID


texts: Splitting std::string based on delimiter using only find and substr

texts:
I have been playing around with these two functions for a bit, dunno if this is practical though. I have only been learning C++ for a couple of days, coming from a Java background.

There we had a function that does this for us; I tried making something similar.

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

using namespace std;

vector<string>parse(string test, string Deli);
int main()
{

vector<string> x = parse("random text to test splitting apart ", " ");
// note , the deliminator have to be after the text not before it.
for (string &e : x)
{
    cout << e << endl;
}
return 0;
}
vector<string>parse(string test, string Deli) {
    int count = 0; int token = 0;
    vector<string>parsed;
    for (size_t i = 0; i <= count; i++)
    {
        string x = (test.substr(token, test.find(Deli, token)-token));
        parsed.push_back(x);
        token += test.find(Deli, token +1) - (token-1);
        test.find(Deli, token) != std::string::npos ? count++ : count;
    }
    return parsed;
}


texts: Unreliable shared memory circular buffer with read-only consumer

texts:
This code is slightly platform dependent but should be pretty easy to port. The goal with this code was to create a circular buffer where the consumer could be limited to read-only access of the buffer (the test uses threads but it could be ported to processes fairly easily.)

I think I probably made at least one mistake in this code and I'm not even sure it is technically possible to implement in a standards compliant way.

#define _GNU_SOURCE

#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <pthread.h>

#include <xmmintrin.h>

#define BUFFER_SIZE 64U
#define PACKET_SIZE 128U

#define CUTOFF 2147483648U

typedef uint32_t seqno;

struct packet_header {
        seqno production_count;
};

struct packet_payload {
        char bytes[PACKET_SIZE - sizeof (struct packet_header)];
};

union packet {
        struct {
                struct packet_header header;
                struct packet_payload payload;
        } format;
        char bytes[PACKET_SIZE];
};

static union packet volatile buffer[BUFFER_SIZE] = {{.format.header.production_count = -1}};

static void *producer(void *foo)
{
        seqno producer_count = 0U;

        for (;;) {
                uint64_t payload_number = random();

                struct packet_payload payload = {0};
                memcpy(payload.bytes, &payload_number, sizeof payload_number);

                __atomic_store_n(&buffer[producer_count % BUFFER_SIZE].format.header.production_count, -1, __ATOMIC_SEQ_CST);

                /* This store needs to be SEQ_CST to prevent the write moving before it (whether via the compiler or the CPU */

                buffer[producer_count % BUFFER_SIZE].format.payload = payload;

                __atomic_thread_fence(__ATOMIC_RELEASE);

                __atomic_store_n(&buffer[producer_count % BUFFER_SIZE].format.header.production_count, producer_count, __ATOMIC_RELEASE);

#if defined LOG
                fprintf(stdout, "production count: %u, payload: %lu, produced\n", producer_count, payload_number);
#endif

                producer_count = (producer_count + 1U) % CUTOFF;
        }
}

static void *consumer(void *foo)
{
        seqno consumer_count = 0U;

        for (;;) {
                seqno count = __atomic_load_n(&buffer[consumer_count % BUFFER_SIZE].format.header.production_count, __ATOMIC_ACQUIRE);

                if ((seqno)-1 == count) {
                        /* the message hasn't been completed yet */
                        _mm_pause();
                        continue;
                }

                __atomic_thread_fence(__ATOMIC_ACQUIRE);

                struct packet_payload payload = buffer[consumer_count % BUFFER_SIZE].format.payload;

                /* Note that the double check needs to be SEQ_CST to prevent the read moving after it (whether via the compiler or the CPU */

                if (count != __atomic_load_n(&buffer[consumer_count % BUFFER_SIZE].format.header.production_count, __ATOMIC_SEQ_CST)) {
                        /* torn read, skip packet */
                        consumer_count = (count + 1U) % CUTOFF;
                        continue;
                }

                if (consumer_count > count) {
                        /* we have incremented the consumer count enough to catch up to the producer */
                        _mm_pause();
                        continue;
                }

                uint64_t payload_number;
                memcpy(&payload_number, payload.bytes, sizeof payload_number);

#if defined LOG
                fprintf(stderr, "production count: %u, payload: %lu, consumed\n", count, payload_number);
#endif

                consumer_count = (count + 1U) % CUTOFF;
        }
}

int main(void)
{
        pthread_t xx;
        pthread_create(&xx, 0, producer, 0);
        pthread_create(&xx, 0, consumer, 0);

        pthread_exit(0);
}


texts:
I'm using the following code to initialise 8 I/O-ports (i.e. GPIO pins on a Raspberry Pi). That's 4 x 2 pins, each duo controls a switch, A to D, and each duo consists of a pin for On and a pin for Off.

def init_switches():
    switch = {
        'A': dict(On = 22, Off = 12),
        'B': dict(On = 19, Off = 11),
        'C': dict(On = 18, Off = 16),
        'D': dict(On = 15, Off = 13)
        }

    # define all individual pins as output
    for ID in switch:
        for pin in switch[ID]:
            GPIO.setup(switch[ID][pin], GPIO.OUT)

    return switch

I chose this way, a set of dicts, because it allows me to say:

switch = init_switches()
switch['A']['On']

The last line makes for nice readable code. However the nested for loop is not so elegant. Isn't there a more concise way?

Edit: I'm deliberately iterating over keys to get to values. Values are pin numbers. Pin numbering is not arbitrary, but has to do with hardware design. It came out this way because it allowed the easiest circuitry to the switch controller. I'm deliberately hiding all that from the coding, because it's a different chapter altogether.


texts: Context managers that also deal with sys.stdin and sys.stdout

texts:
It's pretty typical for Linux command-line utilities that deal with files to accept either a file as input, or stdin. It's also pretty common for them to be able to output to a file or to stdout.

These should be supported:

python myprogram.py input output
cat input | python myprogram.py > output
python myprogram.py input > output

Additionally, I don't like editing files in-place. I'd rather make a tmpfile and then only copy over the tmpfile if the operation is a success, but I'd also rather not deal with tmpfiles every time I write something that has an output file. So both

python myprogram --in-place input
python myprogram filename filename (ie, input is the same as output)

should use a tmpfile.

I wrote this pair of context managers to make this type of interface a little easier to write. They're meant to be used something like this:

with infile(infile_filename) as f:
     for line in f: #do some stuff
with outfile(outfile_filename, infile_name=infile_filename, inplace=inplace) as f:
#get values for these arguments from argparse.
     f.write('blah')

I would love to know what y'all think of it.

#!/usr/bin/python3
import os
import shutil
import sys
import tempfile

class infile(object):
    def __init__(self, file_name=None):
        self.file_name = file_name
    def __enter__(self):
        if self.file_name is None:
             self.f = sys.stdin
        else:
             self.f = open(self.file_name)
        return self.f
    def __exit__(self, etype, value, traceback):
        if self.f is not sys.stdin:
            self.f.close()
    def __getattr__(self, val):
        return getattr(self.f, val) # pass on other attributes to the underlying filelike object

class outfile(object):
    def __init__(self, file_name=None, *, infile_name=None, inplace=False):
        self.file_name = file_name
        self.infile_name = infile_name
        self.inplace = inplace
    def __enter__(self):
        if self.inplace or (self.file_name and self.file_name == self.infile_name):
            self.f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
            self.tmppath = self.f.name
        elif self.file_name is None:
            self.f = sys.stdout
            self.tmppath = None
        else:
            self.f = open(self.file_name, 'w')
            self.tmppath = None
        return self.f
    def __exit__(self, etype, value, traceback):
        # If got no errors...
        if etype is None and self.tmppath:
            self.f.flush()
            shutil.copy(self.tmppath, self.infile_name)
        if self.f is not sys.stdout:
            self.f.close()
        if self.tmppath:
            os.remove(self.tmppath)
    def __getattr__(self, val):
        return getattr(self.f, val)


texts:
I have a Django model User

class Notification(TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
                             related_name='notifications')
    viewed = models.BooleanField(verbose_name=_('has viewed'), default=False)

    def make_viewed(self):
            if self.viewed:
                return
            self.viewed = True
            User.objects.filter(id=self.user.id).update(not_viewed_notifications=F('not_viewed_notifications') - Value(1))
            self.save()

So I think that order methods in model is bad idea and actually
 it's anti-pattern, so next one solution was like this:

class Notification(TimeStampedModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
                             related_name='notifications')
    _viewed = models.BooleanField(verbose_name=_('has viewed'), default=False)

    @property
    def viewed(self):
        return self._viewed

    @viewed.setter
    def viewed(self, value):
        if self._viewed:
            return

        self._viewed = True
        self.user.not_viewed_notifications = F('not_viewed_notifications') - Value(1)
        self.user.save(commit=False)
        self.save()

It looks better, but we have a couple of problems:

1) Model have methods yet

2) Property care side-effect, it doesn't obviously

3) That action require access to instance, so we can't move it to custom field.

What are you thinking about?


texts: Executing asynchronous functions in sequence

texts:
I implemented a function for practice that takes a collection of asynchronous functions and a callback. It executes the functions in sequence then calls
the callback with the results (coming from the callbacks of the async functions). It partially mimics the behavior of series function in the async library

The function

const series = (tasks, cb) => {
    let results = [];
    const iterator = index => {
        if (index === tasks.length) {
            return;
        }
        const task = tasks[index];
        task(val => {
            results.push(val);
            iterator(index + 1);
            if (index === tasks.length - 1) {
                cb(results);
            }
        });
    }
    iterator(0);
}

Usage

const tasks = [
    cb => {
        setTimeout(() => {
            cb('done 1');
        }, 1000);
    },
    cb => {
        setTimeout(() => {
            cb('done 2');
        }, 1000);
    },
    cb => {
        setTimeout(() => {
            cb('done 3');
        }, 1000);
    }
];

series(tasks, results => {
    console.log(results);
});

// outputs ['done 1', 'done 2', 'done 3'] after 3 seconds

What do you think about my approach? How would you implement it? Using plain JavaScript.


texts: Solving the game of 24 recursively in APL

texts:
The "game of 24" as I called it in the title is a maths game in which you are given four numbers and have to combine them in an expression using only the four basic arithmetic operations +, -, × and ÷ (and possibly using parenthesis) to achieve the final result of 24. You must use each digit exactly once.
For example, if the numbers were 1 2 3 4 the answer could be 1×2×3×4 or (1+2+3)×4.
I set to write a solver for this game in APL (which eventually led to this blog post) which I wanted to be general enough to handle any amount of input numbers and any target number (so not necessarily only 24 as target number). The recursive algorithm I used is fairly simple and has a brute-force nature: pick two numbers from the available N numbers in all the different ways I can do that and then combine them with all the available operations, applying the same function recursively to the several sets of N-1 numbers.
I am not only interested in knowing if I can get to a target number but I also want to know how to get there, so while I do all these manipulations, I also keep track of how to get to the available numbers by writing prefix expressions with the numbers used. E.g. if at some point I have the numbers 1 2 3 4, I will have a matching string representation of '1' '2' '3' '4'. If then I use addition to merge 1 and 2, the new set of numbers is 3 3 4 and the matching representation changes to '+ 1 2' '3' '4'.
This is the simple namespace I created:
(edit: as time went by the code evolved a little)
:Namespace GameOf24
    ⍝ Generalized solver for the "game of 24".

    Solve←{
        ⍝ Dyadic function to find ways of building ⍺ with the numbers in ⍵
        (reprs values)←Combine⊂⍵
        mask←⍺=∊values
        (mask/reprs) (mask/values)
    }

    Combine←{
        ⍝ Recursive dyadic function combining the numbers ⍵ which have been obtained by the expressions ⍺
        ⎕DIV←1
        ⍺←⍕¨¨⍵ ⍝ default string representations of input numbers
        1=l←≢⊃⍵: ⍺ ⍵  ⍝ if no more numbers to combine, return
        U ← { ⍝ unpack pairs of nested results
            ⊃{(wl wr)←⍵ ⋄ (al ar)←⍺ ⋄ (al,wl)(ar,wr)}/⍵
        }
        C ← { ⍝ Combine two numbers of ⍵ with the dyadic function in ⍺
            (r v) ← ⍵
            (li ri) ← ↓⍉idx⌿⍨sub← ≠v[idx]
            newv ← v[li] (⍎⍺) v[ri]
            oldv ← v[sub⌿unused]
            values ← ↓newv,oldv
            reprs ← ↓r[sub⌿unused],⍨↓(↑sub/⊂⍺),(↑r[li]),' ',↑r[ri]
            reprs values
        }
        idx ← (~0=(1+l)|⍳l*2) ⌿ ↑,⍳l l
        unused ← idx ~⍨⍤1 1 ⍳l
        (a w) ← U, '+-×÷' ∘.C ↓⍉↑⍺ ⍵
        u←≠w
        a ∇⍥(u∘/) w
    }
:EndNamespace

The Solve function is just a wrapper around the main algorithm I described, filtering for the target value in all the different values I can build with the input numbers. Use it like 24 GameOf24.Solve 1 2 3 4.
Other than all the feedback you can give me, I have particular questions I would like to see addressed:

originally I was using a fair share of each ¨ and used U twice, so I created a dfn for U, which now I only use once. Is it worth keeping it as a separate dfn? Or maybe there is a smarter way of unpacking the results of '+-×÷' ∘.C ↓⍉↑⍺ ⍵ to (a w) which doesn't require the use of U;

I don't think it is very elegant to have a string '+-×÷' with the arithmetic operations I am allowed to use and then later on fixing them with ⍎⍺ but I can't think of a better way of doing this;

is the shape of the data adequate? A vector of vectors for the numbers available and a separate vector of "strings" seems suitable;

should C be adjusted and defined outside of Combine? Currently it's inside Combine because it uses variables defined inside Combine and I think it would be too cumbersome to define those auxiliary variables each time C is called;

the string representations keep getting extra whitespace that I don't know where it comes from; e.g. 100 GameOf24.Solve 1 2 3 4 7 gives ×+3          7          ×+1 4 2    as string representation of the result.


texts: Monitoring and re-establishing a PostgreSQL connection

texts:
Within a complicated Ruby project, I need to monitor the connection to a PostgreSQL database, as answered here. I use a thread for this purpose. Every few milliseconds, I invoke "consume_input" which will raise an exception of the database connection no longer exists. If might have been closed for a number of reasons, but there is no indication from the socket/connection why it is closed. If the server is restarted and is alive again within a certain time-frame, I reconnect and assume everything is fine. Otherwise, I notify another object via a callback that all is not well, and the thread exits normally.

I'm looking for tips and suggestions on following best practices and correctness. I need some general Ruby advice on making my code cleaner and more robust.

PG_MAX_FAILURES=10
PG_SLEEP_QUANTA=0.25
def monitor_start
  log.info("db: #{__method__}")
  _dbconn=nil
  if @monitor.alive?
    @monitor.kill
    sleep PG_SLEEP_QUANTA
  end
  @monitor = Thread.new {
    _failures=0
    while true do
        begin
          if ! _dbconn.is_a?PG::Connection or _dbconn.status() != PG::CONNECTION_OK
            log.info("Reconnecting...")
            _dbconn = PG.connect( @dbconnstr )
            log.info("Reconnected.")
          else
            _dbconn.consume_input()
            _failures=0
          end
          sleep PG_SLEEP_QUANTA
        rescue PG::ConnectionBad => ex
          _failures += 1
          if _failures >= PG_MAX_FAILURES
            @monitor_post_callback.call()
            break # Thread.current.stop ??
          end
          log.warn("Postgresql connection lost. Retry# #{_failures}...")
          sleep PG_SLEEP_QUANTA
          retry
        rescue => ex
          log.warn("Other exception #{ex.class} #{ex.message}")
        end
    end
  }
end


texts: Makefile which only forwards to subdirectories

texts:
I have a Makefile, which should when calling make just call make in a list of subdirectories. The subdirectories should not be automatically detected but are fine to be hard coded (Tool1, Package2, Submodule3 below). Furthermore, if I call make Tool1, Tool1 should be built (i.e. the directory names should be recognised as targets).
At this top level I have no use for dependency checking, the Makefiles in the subdirectories take care of that. My current version looks like this:

subdirs := Tool1 Package2 Submodule3

.PHONY: all clean $(subdirs)

all:

clean:

define makesubdir
$(1):
  make -C $(1)

all: $(1)
endef

define makesubdirclean
$(1)-clean:
  make -C $(1) clean

clean: $(1)-clean
endef

$(foreach SUBDIR,$(subdirs),$(eval $(call makesubdir,$(SUBDIR))))
$(foreach SUBDIR,$(subdirs),$(eval $(call makesubdirclean,$(SUBDIR))))

What I already considered:

I don't want a for loop in the all target, to allow parallel building with make -j. An older version read like:

all:
   for DIR in $(subdirs); do make -C $$DIR ; done
The subdirectories should be defined only in one place, adding a new subdirectory should happen only on one place.
The subdirectories are .PHONY such that make gets called in them, regardless of the directory's timestamp.
I thought all: $(subdirs) would be easier to read than all: $(1) but that way only Tool1 got built.


texts:
I am trying to solve the Dynamic Array problem on HackerRank:

  Create a list, seqList, of N empty sequences, where each sequence is indexed from 0 to N-1. The elements within each of the N sequences also use 0-indexing.
  Create an integer, lastAnswer, and initialize it to 0.
  The 2 types of queries that can be performed on your list of sequences (seqList) are described below:

  Query: 1 x y

  Find the sequence, seq, at index ((x ^ lastAnswer) % N) in seqList.
  Append integer y to sequence seq.

  Query: 2 x y

  Find the sequence, seq, at index ((x ^ lastAnswer) % N) in seqList.
  Find the value of element y % size in seq (where size is the size of seq) and assign it to lastAnswer.
  Print the new value of lastAnswer on a new line.

However, I am getting a “time out error” for very large inputs.

Below is my code in Swift so far:

func dynamicArray(n: Int, queries: [[Int]]) -> [Int] {
    var sequences: [Int: [Int]] = [:]
    var lastAnswer = 0
    var answerlist = [Int]()
    for query in queries {
        let queryType = query[0]
        let x = query[1]
        let y = query[2]
        switch queryType {
        case 1:
            let seq = (x ^ lastAnswer) % n
            if var sequence = sequences[seq] {
                sequence.append(y)
                sequences[seq] = sequence
            } else {
                sequences[seq] = [y]
            }
        case 2:
            let seq = (x ^ lastAnswer) % n
            let index = y % (sequences[seq])!.count
            lastAnswer = sequences[seq]![index]
            answerlist.append(lastAnswer)
        default: break
        }
    }
    return answerlist
}

Can it be further optimised?


texts:
I have a function that reads numbers from a file and constructs a Vector3. Can anyone think of how I can make improvements to this since I am new to C++?

The file has a list of numbers like so:

0.200153
-6.30333
-2.02161
etc...

The function look like this:

//uses 3 vectors to store x,y,z then combines them at the end to make the full PxVec3

void ModelLoader::LoadVertex(std::string fileLocation)
{
    //clears vector so it doesnt break when loading multiple models
    vertexArray.clear();

    std::ifstream file2;
    file2.open(fileLocation);

    if (!file2.is_open())
        std::cout << "Failed to load vertex data" << std::endl;

    //individual x,y,z values for the vertex arrays
    std::vector<float> x;
    std::vector<float> y;
    std::vector<float> z;

    int counter = 0;

    //grabs each line add places them into a vector to be used later
    while (!file2.eof())
    {
        if (counter == 3)
            counter = 0;

        std::string num;
        file2 >> num;

        switch (counter)
        {
        case 0:
            x.push_back(stof(num));  //converts string to float
            break;
        case 1:
            y.push_back(stof(num));
            break;
        case 2:
            z.push_back(stof(num));
            break;
        default:
            break;
        }
        counter++;
    }
    file2.close();

    //adds x,y,z values to the vector to complete to full PxVec3
    for (int i = 0; i < x.size(); i++)
        vertexArray.push_back(PhysicsEngine::PxVec3(x[i], y[i], z[i]));
}


texts:
I've created a simple picker which is going to be used to select the number of rows and columns when constructing a table.

Here's the example: http://jsfiddle.net/tnn3qgvj/8/

HTML

<input type="text" value="1 x 1" class="grid-chooser"/>

JavaScript

$(function () {
    var rows = 5;
    var cols = 5;

    // create the grid
    var grid = '
';
    for (var i = 0; i < rows; i++) {
        grid += '
';
        for (var c = 0; c < cols; c++) {
            grid += '

';
        }
        grid += '
';
    }
    grid += '
';

    var $gridChooser = $('.grid-chooser');
    var $grid = $(grid)
        .insertAfter($gridChooser);

    var $allSquares = $('.square');

    $grid.on('mouseover', '.square', function () {
        var $this = $(this);
        var col = $this.index() + 1;
        var row = $this.parent().index() + 1;
        $allSquares.removeClass('highlight');
        // select all the rows and cols indexed lower than
        // the one under the mouse
        $('.row:nth-child(-n+'+row+') .square:nth-child(-n+'+col+')')
            .addClass('highlight');
        $gridChooser.val(col + ' x ' + row)
    })

});

CSS

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

.grid-chooser + .grid {
    width: 120px;
    height: 120px;
    background: rgba(0,0,0,0.2);
    position: relative;
    padding: 2px;
    display: none;
}

.grid-chooser:focus + .grid {
   display: block;
}

.grid-chooser + .grid .row:first-child .square:first-child .inner {
   background: rgba(0,0,0,0.4);
}

.grid-chooser + .grid .square:first-child {
    margin-top: 0;
}

.grid-chooser + .grid .row {
    height: calc(100%/5);
}

.grid-chooser + .grid .square {
    height: 100%;
    width: calc(100%/5);
    display: inline-block;
    margin: -2px 0;
    padding: 1px;
}

.grid-chooser + .grid .square:hover .inner,
  .grid-chooser + .grid .square.highlight .inner {
    background: rgba(0,0,0,0.4)
}

.grid-chooser + .grid .inner {
    height: 100%;
    width: 100%;
    border-radius: 3px;
    background: rgba(0,0,0,0.2);
}

I'm interested to know if there's a more effective or efficient method of selecting the square elements that appear before the mouseover, or any other improvements!


texts:
I am very new to python (probably too new to consider efficiency etc.). But I am bit confused about which method to use while reading a file for post-processing.
Here I am reading it line-by-line. There is other methods also for reading the file(e.g infile.read()), one of them is to load the complete file in memory.
Can someone kindly discuss this?

My code in current condition is:

#!/usr/bin/python
import sys,math,re
try:
  inf=sys.argv[1]
except:
    print "usage:", sys.argv[0], "argument"; sys.exit(1)

infile=sys.argv[1]; oufile=sys.argv[2]
ifile=open(infile, 'r'); ofile=open(oufile, 'w')
pattern=r'species,subl,cmp=\s{4}(.*)\s{4}(.*)\s{4}(.*)\s{3}s1,torque=(.{12})(.{12})'

ssc1=[];ssc2=[];ssc3=[]; s1=[]; t=[]
for line in ifile:
  match = re.search(pattern, line)
  if match:
    ssc1.   append(int(match.group(1)))
    s1.     append(float(match.group(4)))
    t.      append(float(match.group(5)))

for i in range(len(t)):
  print('%g %12.5e %12.5e' % (ssc1[i], s1[i], t[i]))

ifile.close(); ofile.close()


texts:
Considering that two bitsets are provided in the form of strings, char a[] and char b[], as in the code below. And the task of add that bitsets is given. I take it and wrote the following to sum the two bitsets:

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

int carry = 0;
char result(char r, int c) {
    char R = '0';
    if (carry) {
        if (c) {
            R = '0';
            carry = 1;
        } else {
            R = r == '0' ? '1' : '0';
            carry = R == '0' ? 1 : 0;
        }
    } else {
        if (c) {
            R = '0';
            carry = 1;
        } else {
            R = r;
            carry = 0;
        }
    }
    return R;
}

char sum(int x, int y) {
    char r = '0';
    if (x ^ y)
        r = result('1', 0);
    else if (x & y)
        r = result('0', 1);
    else
        r = result('0', 0);
    return r;
}

int main() {
    char a[] = "01";
    char b[] = "01";
    char c[] = "00";
    for (int i = strlen(c)-1; i > -1; i--)
        c[i] = sum(a[i] == '0' ? 0 : 1, b[i] == '0' ? 0 : 1);
    printf("%s\n", c);
}

Is it possible to make it simpler?


texts: Activating Lightbox on HTML elements with the has-lightbox class

texts:
I'm in the process of trying to do "object oriented thinking", as to improve my code skill.

I've the following method that creates a lightbox for every item with the class .has-lightbox. Is this something that would benefit from being a class? A LightboxCollection class for example? That has an array Lightbox?

import * as basicLightbox from 'basiclightbox';

var lightboxableImages = document.getElementsByClassName("has-lightbox");
for (let image of lightboxableImages) {
    image.addEventListener('click', openLightbox);
}

function openLightbox(e) {
    const target = e.target;
    const src = target.dataset['lightbox-src'] ? target.dataset['lightbox-src'] : target.src;

    if (!src) {
        return false;
    }

    const instance = basicLightbox.create(`<img src="${src}">`);
    instance.show();
}


texts:
I'm a C++ programmer and thought I'd revisit the roots, so I scribbled something really quickly. I would appreciate input on how my C code is looking!

slist.h

#ifndef SLIST_H
#define SLIST_H

#include <stddef.h>
#include <stdbool.h>

struct slist_s
{
    int key;
    struct slist_s* next;
};

typedef struct slist_s slist_t;

slist_t* slist_push_front(slist_t*, int);
slist_t* slist_push_back(slist_t*, int);

slist_t* slist_pop_front(slist_t*);
slist_t* slist_pop_back(slist_t*);

_Bool    slist_empty(const slist_t* const);
slist_t* slist_clear(slist_t*);

size_t   slist_size(const slist_t*);

void     slist_print(const slist_t*, const char*);

slist_t* slist_for_each(slist_t* const, void(*)(int*));

#endif

slist.c

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>

#include "slist.h"

slist_t* slist_push_front(slist_t* root, int val)
{
    slist_t* node = malloc(sizeof(slist_t));
    if (!node) {
        return NULL;
    }
    node->key = val;
    node->next = !root ? NULL : root;

    root = node;
    return root;
}

slist_t* slist_push_back(slist_t* root, int val)
{
    slist_t* node = malloc(sizeof(slist_t));
    if (!node) {
        return NULL;
    }
    node->key = val;

    if (!root)
    {   /* list is empty */
        node->next = NULL;
        root = node;
    }
    else
    {   /* need to walk to end of list */
        slist_t* temp = root;
        while (temp->next) {
            temp = temp->next;
        }
        node->next = NULL;
        temp->next = node;
    }
    return root;
}

slist_t* slist_pop_front(slist_t* root)
{
    if (!root) {
        return NULL;
    }
    if (!root->next)
    {
        free(root);
        return NULL;
    }
    slist_t* todel = root;
    root = root->next;
    free(todel);
    return root;
}

slist_t* slist_pop_back(slist_t* root)
{
    if (!root) {
        return NULL;
    }
    if (!root->next)
    {
        free(root);
        return NULL;
    }
    slist_t* todel = root;
    while (todel->next->next) {
        todel = todel->next;
    }
    free(todel->next);
    todel->next = NULL;
    return root;
}

_Bool slist_empty(const slist_t* const root)
{
    return root;
}

slist_t* slist_clear(slist_t* root)
{
    while (root) {
        root = slist_pop_front(root);
    }
    return root;
}

size_t slist_size(const slist_t* root)
{
    size_t size = 0;
    const slist_t* temp = root;
    while (temp)
    {
        temp = temp->next;
        ++size;
    }
    return size;
}

void slist_print(const slist_t* root, const char* format)
{
    const slist_t* temp = root;
    while (temp)
    {
        printf(format, temp->key);
        temp = temp->next;
    }
}

slist_t* slist_for_each(slist_t* const root, void(*fun)(int*))
{
    slist_t* temp = root;
    while (temp)
    {
        fun(&temp->key);
        temp = temp->next;
    }
    return root;
}


texts:
I have an application which polls a bunch of servers every few minutes. To do this, it spawns one thread per server to poll (15 servers) and writes back the data to an object:

import requests
import threading
import time

servers = ['1.1.1.1', '1.1.1.2']

class CallThreads(threading.Thread):
    """
    Auxiliary class used to provide arguments to threads
    """

    def __init__(self, target, *args):
        self.target = target
        self.args = args
        threading.Thread.__init__(self)

    def run (self):
        self.target(*self.args)

class ServerResults(object):
    def __init__(self):
        self.results_list = []

    def add_server(some_argument):
        self.results_list.append(some_argument)

def poll_server(server, results):
    response = requests.get(server, timeout=10)
    results.add_server(response.status_code);

def process_results(results):
    # Do something with the results

def main():
    while True:
        results = ServerResults()
        for s in servers:
            t = CallThreads(poll_server, s, results)
            t.daemon = True
            t.start()
        time.sleep(300)
        process_results(results.results_list)

if __name__ == '__main__':
    main()

This is my first non-trivial Python application, so I would appreciate any critique, comments, or suggestions. Thank you!


texts:
I have been reading this thread on Stack Overflow about simulating enums in PHP and it seems that the most common approach is to use class constants. My problem with that is I can't use it for type hints, so I have added a static function that checks if a value is defined as one of the constants.

class DataType
{
    const BIT = 'BIT';
    const TINYINT = 'TINYINT';
    const SMALLINT = 'SMALLINT';
    const MEDIUMINT = 'MEDIUMINT';
    const INT = 'INT';
    const INTEGER = 'INTEGER';
    const BIGINT = 'BIGINT';
    const FLOAT = 'FLOAT';
    const DECIMAL = 'DECIMAL';
    const NUMERIC = 'NUMERIC';
    const DATE = 'DATE';
    const TIME = 'TIME';
    const TIMESTAMP = 'TIMESTAMP';
    const DATETIME = 'DATETIME';
    const YEAR = 'YEAR';
    const CHAR = 'CHAR';
    const VARCHAR = 'VARCHAR';

    static public function Defines($const)
    {
        $cls = new ReflectionClass(__CLASS__);
        foreach($cls->getConstants() as $key=>$value)
        {
            if($value == $const)
            {
                return true;
            }
        }

        return false;
    }
}

Any thoughts on improving the code are welcome.


texts: JavaScript making http(s) request: requiring modules within a function

texts:
This JavaScript code is being used as part of a reporting tool that makes http(s) GET requests to an API, bundles responses and uploads them as files to an AWS S3 bucket. It's a script that runs periodically to save changes in our API over time. This particular function getResponse (name pending) returns a promise, that makes the actual requests with either node's http or https library, depending on the passed in url string.

const DEBUG = process.env.DEBUG;

const getResponse = url => {
  return new Promise((resolve, reject) => {
    (() => url.startsWith('https://') ? require('https') : require('http') )().request(url, (resp) => {
      let data = '';
      resp.setEncoding('utf8');
      resp.on('data', chunk => data += chunk);
      resp.on('error', err => { if (DEBUG) console.log('fucked up'); return reject(err); });
      resp.on('end', () => { if (DEBUG) console.log(url + ' resolved'); return resolve(data); });
    }).end();
  });
};

Originally I had both the http and https module declared as constants on top of the file and use the variable names in the ternary operation as listed below:

// top of the file
const http = require('http');
const https = require('https');

// later in the method getResponse...
    const r = url.startsWith('https://') ? https : http;
    r.request(url, (resp) => {
// and so on...

When this script is run, the urls that get passed to the function in question are either all starting with https:// or http://, depending which environment we're hitting. Therefore requiring both http and https for the lifetime of the node script is unnecessary. I'm wondering though if my new variation using an anonymous function and requiring in the ternary operation has any disadvantages.


texts: Similar but slightly different JavaScript functions

texts:
I have two very similar functions that exist mainly for syntactic sugar.

deactivate = (el, seek) -> el.find(seek).removeClass("active")
activate = (el, seek) -> el.find(seek).addClass("active")

This allows me to write, for example:

activate $("#something"), ".child"

Using the above purely as an example, ignoring any logical errors with the JavaScript itself… how could this be refactored to be more dry?


texts:
I have a data.frame of people broken into households where I have a set of mostly unique keys (for household, and then person within household), but sometimes it looks like 2 (or possibly more) households were given the same key.

small_example <- tibble::tribble(
  ~hh_id, ~per_id, ~ref,
  1,       1,       "a",
  1,       2,       "b",
  1,       3,       "c",
  2,       1,       "d",
  2,       1,       "e",
  2,       2,       "f",
  2,       2,       "g",
  2,       3,       "h",
  2,       4,       "i"
)

In this example, the first household is ok, but I want to split the second into 2 households randomly, but to preserve as much of the original structure as possible. In particular, I want persons "d" and "f" to stay together and "e"/"g" to stay together and then persons "h" and "i" to be added to one of these 2 households.

Here's my first attempt at this, but my code is pretty slow. I can tell I'm over-using the tidyverse, but am not sure what a better alternative is.

library(dplyr)
library(purrr)
assign_extra_id <- function(per_grp_id) {
  all_pers_df <- data_frame(orig_id = per_grp_id) %>%
    group_by(orig_id) %>%
    mutate(order_num = row_number(), total_num = n())

  max_dup_pers <- max(all_pers_df$total_num)

  if (max_dup_pers == 1) return(1)
  multi_pos_order <- accumulate(
    seq(max_dup_pers, 2, -1),
    ~sample(.x, .y - 1),
    .init = sample(seq_len(max_dup_pers), max_dup_pers)
  ) %>%
    set_names(seq(max_dup_pers, 1, -1)) %>%
    map_df(~data_frame(order_num = seq_along(.), new_id = .), .id = "total_num") %>%
    mutate(total_num = as.numeric(total_num))

  out <- left_join(all_pers_df, multi_pos_order, by = c("total_num", "order_num"))
  out$new_id
}

small_example %>%
  group_by(hh_id) %>%
  mutate(extra_id = assign_extra_id(per_id))

#> # A tibble: 9 x 4
#> # Groups:   hh_id [2]
#> hh_id per_id   ref extra_id
#> <dbl>  <dbl> <chr>    <dbl>
#> 1     1      1     a        1
#> 2     1      2     b        1
#> 3     1      3     c        1
#> 4     2      1     d        2
#> 5     2      1     e        1
#> 6     2      2     f        2
#> 7     2      2     g        1
#> 8     2      3     h        1
#> 9     2      4     i        1

And here's a timing:

bigger_example <- map_df(seq_len(100), ~mutate(small_example, hh_id = hh_id + (2 * .)))

microbenchmark::microbenchmark(
  my_attempt = bigger_example %>%
    group_by(hh_id) %>%
    mutate(extra_id = assign_extra_id(per_id)),
  times = 10
)

Unit: seconds
       expr      min       lq     mean   median       uq      max neval
 my_attempt 2.297449 2.305819 2.327998 2.312012 2.354128 2.381427    10

I want to randomly sample from the 4 sets of households I consider valid for what is currently hh_id = 2:

Set 1: hh1 = d, f, h, i;   hh2 = e, g
Set 2: hh1 = d, f;         hh2 = e, g, h, i
Set 3: hh1 = e, g;         hh2 = d, f, h, i
Set 4: hh1 = e, g, h, i;   hh2 = d, f

The logic for this when there are 3 households with the same hh_id gets even more complicated, because if there's only 1 person with a given person id, I want to sample from the households that were available when there were 2 (and so on). This is why there's the kind of hairy purrr::accumulate call.


texts: Print routes on the stairway when only 1 or 2 steps are possible

texts:
Given a staircase with N steps, you can go up with 1 or 2 steps each
  time.  Output all possible ways you go from bottom to top.

I'm looking for code review, best practices, optimizations etc. Complexity: O(2n)

    public final class StairRoutes {

        private StairRoutes() {}

        /**
         * Given a staircase with N steps, you can go up with 1 or 2 steps each time.
         * Output all possible way you go from bottom to top.
         *
         * @param stepCount     The number of steps in the stairway
         * @return              A list containing all possible routes.
         */
        public static List<List<Integer>> stairClimbingRoutes(int stepCount) {
            if (stepCount <= 0) throw new IllegalArgumentException("The step count: " + stepCount + " should be positive.");

            /* a container containing all the possible routes */
            final List<List<Integer>> stairRoutes = new ArrayList<List<Integer>>();
            calcAllRoutes(stepCount, new LinkedList<Integer>(), stairRoutes);

            return stairRoutes;
        }

        private static void calcAllRoutes(int stepCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
            if (stepCount <= 1) {
                populateRoute (stepCount, tempList, stairRoutes);
                return;
            }

            processSteps(stepCount, 1, tempList, stairRoutes);
            processSteps(stepCount, 2, tempList, stairRoutes);
        }

        private static void populateRoute (int numStairs,  LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
            if (numStairs == 0) {
                stairRoutes.add(new ArrayList<Integer>(tempList));
                return;
            }
            if (numStairs == 1) {
                tempList.add(1);
                stairRoutes.add(new ArrayList<Integer>(tempList));
                tempList.removeLast();
                return;
            }
        }

        private static void processSteps(int numStairs, int hopCount, LinkedList<Integer> tempList, List<List<Integer>> stairRoutes) {
            tempList.add(hopCount);
            calcAllRoutes(numStairs - hopCount, tempList, stairRoutes);
            tempList.removeLast();
        }

        public static void main(String[] args) {
            List<List<Integer>> stairRoutes = stairClimbingRoutes(5);
            for (List<Integer> route : stairRoutes) {
                for (Integer stair : route) {
                    System.out.print(stair + ":");
                }
                System.out.println();
            }
        }

}


texts:
I am using this code to get images to load only if they are visible. However, it seems to be slow with thousands of images, even if they are not rendered.

function getViewportHeight() {
    if(window.innerHeight) {
        return window.innerHeight;
    }
    else if(document.body && document.body.offsetHeight) {
        return document.body.offsetHeight;
    }
    else {
        return 0;
    }
}
function inView(elem, nearThreshold) {
    var viewportHeight = getViewportHeight();
    var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    var elemTop = elem.offset().top;
    var elemHeight = elem.height();
    nearThreshold = nearThreshold || 0;
    if((scrollTop + viewportHeight + nearThreshold) > (elemTop + elemHeight)) {
        return true;
    }
    return false;
}

function loadVisibleImages() {
    jQuery('img[data-src]').each(function() {
        if(jQuery(this).is(':visible')) {
            if(inView(jQuery(this), 100)) {
                this.src = jQuery(this).attr('data-src');
            }
        }
    });
}

jQuery(window).scroll(function() {
    loadVisibleImages();
});

I am using this code to render images:

<img src="" data-src="http://placehold.it/400x400" alt="" width="400" height="400">

Everything works, but how can I optimize it?


texts: Format double to 3 decimal places without decimal separator to a certain length

texts:
I need to format a double value to three decimal places to a string with length of 9 with leading spaces and no decimal separator.

My approach is this

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "a";
nfi.NumberGroupSeparator = "";

double a = 334.44554;

Console.WriteLine($"{a.ToString("####0.000", nfi).Replace("a", ""), 9}");

Is there a more elegant way to do this?


texts: Decorator to return default argument values

texts:
I'm using Python 3.6. This code, used as a decorator to a python function, will cause the function to return a dict of POSITION_OR_KEYWORD arguments.

I used this to create a standard interface to a factory function.

Inspired by this Stack Overflow post, and implemented using a dictionary-flattening function from this previous post.

Eg.

def example(one=1, two=2):
    return {'one':one, 'two':two}

is equivalent to:

@return_kwargs
def example(one=1, two=2):
    pass

import inspect
from functools import wraps
from itertools import chain, starmap

def flatten_dict(dictionary):
    """Flatten a nested dictionary structure"""

    def unpack(parent_key, parent_value):
        """Unpack one level of nesting in a dictionary"""
        try:
            items = parent_value.items()
        except AttributeError:
            # parent_value was not a dict, no need to flatten
            yield (parent_key, parent_value)
        else:
            for key, value in items:
                yield (key, value)

    # Put each key into a tuple to initiate building a tuple of subkeys
    dictionary = {key: value for key, value in dictionary.items()}

    # Keep unpacking the dictionary until all value's are not dictionary's
    dictionary = dict(chain.from_iterable(starmap(unpack, dictionary.items())))
    return dictionary

def return_kwargs(func):
    """Cause the wrapped function to return a dict of keyword arguments"""
    @wraps(func)
    def wrap(*args, **kwargs):
        bound_arguments = inspect.signature(func).bind(*args, **kwargs)
        bound_arguments.apply_defaults()
        return flatten_dict(dict(bound_arguments.arguments))
    return wrap

Let me know how you would implement the idea, whats ugly, corner cases I have missed.


texts:
I am learning Java as my first programming language and have written a bit of code. I would love to read expert reviews on this code and suggestions to improve right from naming conventions to logic. Please let me know if there is any kind of mistake.

public class Sudoku {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        int[][] array = { { 0, 2, 0, 5, 0, 0, 0, 9, 0 },
                          { 5, 0, 0, 0, 7, 9, 0, 0, 4 },
                          { 3, 0, 0, 0, 1, 0, 0, 0, 0 },
                          { 6, 0, 0, 0, 0, 0, 8, 0, 7 },
                          { 0, 7, 5, 0, 2, 0, 0, 1, 0 },
                          { 0, 1, 0, 0, 0, 0, 4, 0, 0 },
                          { 0, 0, 0, 3, 0, 8, 9, 0, 2 },
                          { 7, 0, 0, 0, 6, 0, 0, 4, 0 },
                          { 0, 3, 0, 2, 0, 0, 1, 0, 0 } };
        solve(array);
        System.out.println("Solution is ");
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                System.out.print(" " + array[row][col] + " ");
            }
            System.out.println();
        }
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println("Time taken (in MilliSeconds)= " + totalTime);
    }

    public static boolean solve(int[][] array) {
        if (isSum45(array)) {
            return true;
        }
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                if (array[row][col] == 0) {
                    for (int num = 1; num <= 9; num++) {
                        if (noConflict(array, row, col, num)) {
                            array[row][col] = num;
                            if (solve(array)) {
                                return true;
                            }
                        }
                        array[row][col] = 0;
                    }
                    return false;
                }
            }
        }
        return false;
    }

    // This method edited is after taking suggestions from this forum
    public static boolean noConflict(int[][] array, int row, int col, int num) {
        for (int k = 0; k < 9; k++) {
            if (array[row][k] == num) {
                return false;
            }
            if (array[k][col] == num) {
                return false;
            }
        }
        int m = row - (row % 3);
        int n = col - (col % 3);
        for (int p = m; p < m + 3; p++) {
            for (int q = n; q < n + 3; q++) {
                if (array[p][q] == num) {
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isSum45(int[][] array) {
        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                int sum = 0;
                int m = row - (row % 3);
                int n = col - (col % 3);
                for (int p = m; p < m + 3; p++) {
                    for (int q = n; q < n + 3; q++) {
                        sum = sum + array[p][q];
                    }
                }
                if (sum != 45) {
                    return false;
                }
            }
        }
        return true;
    }
}


texts:
I wrote a script to test how long it takes to make requests against a url.  It takes a list of urls, an array of concurrent requests, and a number of times to attempt the test.  How could I improve on this?

//https://www.nuget.org/packages/RestSharp

string baseUrl = "http://localhost";
void Main()
{
    var urls = new string[] {
        "/some/end/point",
    };

    var concurrentRequests = new int[]{ 1, 5, 25, 50, 100, 500, 1000};
    var numberOfTurns = 10;
    RunTests(urls, concurrentRequests, numberOfTurns);

}

private void RunTests(string[] urls, int[] concurrentRequests,  int numberOfTimes = 1)
{
    for(var i = 0; i < numberOfTimes; i++)
    {
        RunFor(urls, concurrentRequests);
    }
}
private void RunFor(string[] urls, int[] concurrentRequests)
{
    concurrentRequests.ToList().ForEach( e =>
    {
         RunTest(urls, e);
    });
}
private void RunTest(string[] sites, int iterations, string description = "")
{
    var action = GetAction();

    var watch = new Stopwatch();
   // Construct started tasks
   Task<bool>[] tasks = new Task<bool>[sites.Count()];
   watch.Start();

   for(int j = 0; j < iterations; j++)
   {
        for (int i = 0; i < sites.Count(); i++)
        {
            tasks[i] = Task<bool>.Factory.StartNew(action, sites[i]);
        }
   }
   try
   {
       Task.WaitAll(tasks);
   }
   catch (AggregateException e)
   {
       Console.WriteLine("\nThe following exceptions have been thrown by WaitAll()");
       for (int j = 0; j < e.InnerExceptions.Count; j++)
       {
           Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
       }
   }
   finally
   {
    watch.Stop();
    Console.WriteLine("\"{0}|{1}|{2}\", ",sites.Count(), iterations, watch.Elapsed.TotalSeconds);
   }
}
private Func<object, bool>  GetAction()
{
    baseUrl = baseUrl.Trim('/');
    return (object obj) =>
   {
        var str = (string)obj;
        var client = new RestClient(baseUrl);
        client.Authenticator = new NtlmAuthenticator();
        var request = new RestRequest(str, Method.GET);
        request.AddHeader("Accept", "text/html");
        var response = client.Execute(request);
        return (response != null);
   };
}


texts: Coding Challenge Solution - Find Number of Elements in a range in \$O(1)\$ with preprocessing

texts:
Overview

This is my solution to the following Coding Challenge - Find Num of Elements in a Range in \$O(1)\$ with Preprocessing -

  Given an array and max element in the array, find the number of elements present
  between a given range in \$O(1)\$. You can do one-time processing of an array.

Solutions

Solution1

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

class Solution
{
    public:
    Solution(vector<int>& v)
    {
        sort(v.begin(), v.end());

        for(unsigned int i=0; i<v.size(); ++i) m[v[i]] = i;
    }

    unsigned int count(const int a, const int b)
    {
        if(!(a < b)) throw runtime_error("Wrong Order");
        if( (m.find(a) == m.end()) || (m.find(b) == m.end()) ) throw runtime_error("Not Found");
        return m[b] - m[a] + 1;
    }

    private:
    unordered_map<int, unsigned int> m;
};

int main() {
    // your code goes here
    int N;
    cin >> N;
    vector<int> data;
    for(int i=0; i<N; ++i)
    {
        int temp;
        cin >> temp;
        data.push_back(temp);
    }

    Solution sol(data);
    const auto left = 1;
    const auto right = 3;
    const auto res = sol.count(left, right);
    cout << "Left = " << left << ", Right = " << right << " --> Res = " << res << endl;
    return 0;
}

Input

10
1 3 5 7 9 6 2 8 12 22

Notes

Even if typically for Algorithmic Coding Challenges a free function is good enough and using a class is over-engineering, in this specific I went for the class on purpose in order to possibly amortize the pre-processing cost by multiple calls to the count() method.

Solution2

This is an Edit in order to propose an alternative solution based on @peter-taylor comment about the range

This solution does not throw an exception in case the values in the input range are not in the array and it is still $O(1)$ in time, just added more space complexity

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

class Solution
{
    public:
    Solution(vector<int>& v)
    {
        sort(v.begin(), v.end());
        start = v[0];
        end = v[v.size()-1];

        unsigned int count=1;
        unsigned int j=1;

        for(int i=start; i<end; ++i)
        {
            if(i==v[j])
            {
                count++;
                j++;
            }

            m[i] = count;
        }
    }

    unsigned int count(const int a, const int b)
    {
        if(!(a < b)) throw runtime_error("Wrong Order");
        return get_num(b) - get_num(a);
    }

    private:
    unordered_map<int, unsigned int> m;
    int start;
    int end;

    unsigned int get_num(const int a)
    {
        if(a < start) return 0 ;
        if(a >= end) return m.size();
        return m[a];
    }
};

int main() {
    // your code goes here
    int N;
    cin >> N;
    vector<int> data;
    for(int i=0; i<N; ++i)
    {
        int temp;
        cin >> temp;
        data.push_back(temp);
    }

    Solution sol(data);
    const auto left = 0;
    const auto right = 3;
    const auto res = sol.count(left, right);
    cout << "Left = " << left << ", Right = " << right << " --> Res = " << res << endl;
    return 0;
}

Notes

In this implementation the number of elements is computed in a (a,b] range (so first not counted) as this is not violating anything in the specs


texts: FizzBuzz implementation in Java without modulus operator

texts:
I was trying to implement FizzBuzz without modulus operator.

Areas of concern: inner for loop maybe not needed? seq[] array maybe not needed?

class FizzBuzzWithoutModulus{
    public static void main(String[] args){

    int[] fizzbuzz = new int[101];
    int[] buzz = new int[101];
    int[] fizz = new int[101];

    int[] seq = new int[101];
    for(int i=1; i<=100; i++){
      seq[i] = i;
    }

    for(int i=1; i<=100; i++){
      for(int j=1; j<seq.length; j++){
        if((i/15.0) == seq[j]){
          fizzbuzz[i] = i;
        }
        else if((i/5.0) == seq[j]){
          buzz[i] = i;
        }
        else if((i/3.0) == seq[j]){
          fizz[i] = i;
        }
      }
    }
    for(int i=0; i<=100; i++){
      if(fizzbuzz[i]!=0){
        System.out.println(fizzbuzz[i] + " fizzbuzz");
      }
      else if(buzz[i]!=0){
        System.out.println(buzz[i] + " buzz");
      }
      else if(fizz[i]!=0){
        System.out.println(fizz[i] + " fizz");
      }
    }
  }
}


texts:
I have an HTML form where I need to do the following

when value of Select Box changes to initial "Not Selected" value (where values of the option is 0), I am to highlight the select box, when it's non-0, restore the original coloring of the select
when I submit the form, and the Select box value is 0, do not submit the form, and highlight the box

Doing all of this left me with code duplication.  See highlight and restore

How do I get rid of the duplication?  Can I?

highlight("kit_model");
$('#kit_submit').prop("disabled", true);

$("#kit_model").change(function() {

    if ($("#kit_model").val() == 0)
    {
        highlight("kit_model");
        $('#kit_submit').prop("disabled", true);
    }
    else
    {
        restore("kit_model");
        $('#kit_submit').prop("disabled", false);
    }

});
$("#custom_kit_form").submit(function() {
    if ($("#kit_model").val() == 0)
    {
        highlight("kit_model");
        return false;
    }

    $.post(
            "web.php
            $("#custom_kit_form").serialize(),
            $("#main").load('main.php')
         );

    return false;
});

Form

<form action="" id="custom_kit_form" method="post" name="custom_kit_form">

            FS Kit

            <select id="kit_model" name="kit_model">
                    <option value="0">-- SELECT --</option>

                    <option value="573">TUBING</option>
            </select>

            <input id="kit_submit" name="kit_submit" type="submit" value="Save">

</form>


texts: Invoke-WebRequest in a loop until NotFound

texts:
I'm using SAP's Raylight RESTful SDK to get a list of universes from the BusinessObject Enterprise repository.

To get all of the universes, the request needs to be called repeatedly, incrementing the offset parameter until the request returns a Not Found [404] error.

Current approach:

$baseUrl = 'http://<server>:6405/biprws/raylight/v1'

$headers = @{}
$headers.Add("Accept", "application/json")
$headers.Add("Content-Type", "application/json")
$headers.Add("x-sap-logontoken", $Token)

$offset = 0
$limit = 50

try {
    do {

        $Path = "/universes?offset=$offset&limit=$limit"

        $response = Invoke-WebRequest "$baseUrl$Path" -Headers $headers
        ($response | ConvertFrom-Json).universes.universe

        $offset += $limit

    } until ( $response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound )
}
catch {
    # catches 404 too
    Write-Debug "StatusCode: $($_.Exception.Response.StatusCode.Value__)"
}

While the code returns the expected results, I not sure that I like how the code will always exit via the catch.  I could remove the try/catch, but that will leave the code exposed to other errors.

Is there a way to improve this?


texts:
I've recently assembled some jQuery that allows a user to build out a bulleted list in MS Word with hyperlinks and turn that into a HTML unordered list.  Ideas for uses are website menu systems where the user may not have a clue about HTML. You can also extend this with jQuery UI plugins for effects.  Looking for edge cases.

/*
    The following will read in a bullet list from in a MS Word XML file and turn it into a
    unordered list with hyperlinks. Perhaps to use as a menu.
*/
$.ajax({
    type: "GET",
    async: false,
    url: "Menu.xml",
    dataType: "xml",
    success:function(results){
        var currentDepth = 0;
        $("#menu").append('

');
        $(results).find("[nodeName=w:p]").each(function(){
            if($(this).find("[nodeName=w:pStyle]").attr('w:val') == 'ListParagraph'){
                var liValue = $(this).find("[nodeName=w:t]").text();
                var hyper = $(this).find("[nodeName=w:hyperlink]").attr('r:id');
                var placeAtDepth = parseInt($(this).find("[nodeName=w:ilvl]").attr('w:val'), 10);

                if(placeAtDepth > currentDepth){
                    $(".menuLvl"+ currentDepth).append('
');
                }

                currentDepth = placeAtDepth;

                //Determine if we have an hyperlink
                if(hyper != null){
                    var link = $(results).find('Relationship[Id='+hyper+']').attr('Target');
                    liValue = ''+ liValue +'';
                }

                $(".menuLvl"+currentDepth).last().append('
'+ liValue +'
');
            }
        });
    }
});


texts: Is there better way of writing these IF checks?

texts:
This is what I have, But I think I can write it in a sohrter and more efficient way too, what do you suggest?

    string actionString= string.Empty;

    if (auditAction == DSRHelper.SaveStatusEnum.Save)
    {
        actionString = Properties.Resources.SAVE_ACTION_MESSAGE;
    }

    if (auditAction == DSRHelper.SaveStatusEnum.Complete && model.Dirty)
    {
        actionString = "Save'NComplete";
    }
    else if(auditAction == DSRHelper.SaveStatusEnum.Complete)
    {
        actionString = "OnlyComplete.";
    }

EDIT: Ok I changed it a little bit, better now?

    string actionString= string.Empty;

    if (auditAction == DSRHelper.SaveStatusEnum.Save)
    {
        actionString = Properties.Resources.SAVE_ACTION_MESSAGE;
    }
    else if (auditAction == DSRHelper.SaveStatusEnum.Complete )
    {
        if (model.Dirty)
        {
            actionString = "Save'NComplete";
        }
        else
        {
            actionString = "OnlyComplete";
        }
    }


texts: Best way to structure PHP AJAX handlers?

texts:
I'm just getting started with AJAX and am unsure of the best way to structure a PHP AJAX handler. I created a PHP file, ajax_handler.php, and the way I have it structured now is just a bunch of if-else statements (one for each AJAX event), like the following.

First, I make sure there's actually a request being made:

if(isset($_GET['req']))
{
    $req = $_GET['req'];
}
else
{
    die('No request.');
}

Then I process the request like this:

if($req == 'doSomething')
{
    // do something
}
else if($req == 'doSomethingElse')
{
    // do something else
}
else if($req == 'doSomethingDifferent')
{
    // do something different
}
else if($req == 'doSomethingMore')
{
    // do something more
}

The above method works, but it becomes a little difficult to navigate when there are dozens upon dozes of cases. Is there a better method?


texts: Implement test which tries function with diferent params and expected results

texts:
What could I improve in the following code? The goal is to test a function againts a table of input parameters and compare to some expected results with some tolerance (as there are random variables involved in the computations).

This is how I am doing it right now. Note that I cannot use any C++11 features.

void test() throw (const char *) {

    const double TOLERANCE = 0.01;

    const double EXPIRY_TESTS[] = {0.0, more values...};
    const double STRIKE_TESTS[] = { 0.0, more values... };
    const double SPOT_TESTS[] = { 0.0, more values... };
    const double VOL_TESTS[] = { 0.0, more values... };
    const double R_TESTS[] = { 0.0, more values... };
    const unsigned long NPATHS_TESTS[] = { 1, more values... };
    const double EXPECTED_RESULTS[] = { 0.0, more values... };

    int i_result = 0;
    for (int i0 = 0; i0 < sizeof(EXPIRY_TESTS) / sizeof(double); i0++) {
        for (int i1 = 0; i1 < sizeof(STRIKE_TESTS) / sizeof(double); i1++) {
            for (int i2 = 0; i2 < sizeof(SPOT_TESTS) / sizeof(double); i2++) {
                for (int i3 = 0; i3 < sizeof(VOL_TESTS) / sizeof(double); i3++) {
                    for (int i4 = 0; i4 < sizeof(R_TESTS) / sizeof(double); i4++) {
                        for (int i5 = 0; i5 < sizeof(NPATHS_TESTS) / sizeof(long); i5++) {

                            double result = SimpleMonteCarlo1(EXPIRY_TESTS[i0],
                                                              STRIKE_TESTS[i1],
                                                              SPOT_TESTS[i2],
                                                              VOL_TESTS[i3],
                                                              R_TESTS[i4],
                                                              NPATHS_TESTS[i5]);
                            if (abs(EXPECTED_RESULTS[i_result] - result) >= TOLERANCE) {
                                throw "Test failed!";
                            }
                            i_result++;

                        }
                    }
                }
            }
        }
    }

}


texts:
I have a very large data file full of movie ratings that I am looking at for work. I wanted to do this in a clean and very effective manner. The ratings file contains on a per column by column basis:

userID, movieID, rating...

I have parsed the files, and I am now trying to compute cosine similarity of all 100,000 ratings for each movie. Thus, I'm using an ADT Hashmap to store the values of the ratings of each movie as follows HashMap. For each 1000 or so movie, I'm to compute the cosine Similarity. This is what i have done so far, what do you guys think?

import java.util.*;
import java.io.*;

public class MovieRatingParser {
    static HashMap<String, Double> ratings = new HashMap<>();

    public void parseMovieFile() throws FileNotFoundException, IOException {
        //Create an ArrayList to store movies
        ArrayList<Movie> movies = new ArrayList<Movie>();
        try {
        //Create a buffered file reader for FileReader to read in movies.dat
            BufferedReader br = new BufferedReader(new FileReader("movies.dat"));

            String readFile = br.readLine();
            while (readFile != null) {
                //Use String split delimiter to load each movie one by one
                //File delimiter is “\\|"
                String[] tokenDelimiter = readFile.split("\\|");
                String movieID = tokenDelimiter[0];
                String movieTitle = tokenDelimiter[1];

                Movie movieToAdd = new Movie(movieID, movieTitle);
                movies.add(movieToAdd);
                readFile = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            System.out.println("file was not Found!");
        }
        System.out.println("==============================================");

    }

    public static void parseRatingFile() throws FileNotFoundException, IOException{

        try {
            BufferedReader br = new BufferedReader(new FileReader("ratings.dat"));
            String readFile = br.readLine();
            while (readFile != null) {
                String[] tokenDelimiter = readFile.split("\\|");
                String userID = tokenDelimiter[0];
                String movieID = tokenDelimiter[1];
                double rating = Double.parseDouble(tokenDelimiter[2]);

                ratings.put(movieID, rating);
                readFile = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            System.out.println("File was not Found!");
        }
    }

    public static double computeCosineSimilarity(HashMap<String, Double> movieA, HashMap<String, Double> movieB) {

        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;
        parseRatingFile();
        for (int j = 0; j < ratings.size(); j++) {
            movieA.put(ratings.get(3), ratings.values());
        }

        for (int i = 0; i < movieA.size(); i++) {
            dotProduct += movieA[i] * movieB[i];
            normA += Math.pow(movieA[i], 2);
            normB += Math.pow(movieB[i], 2);
        }

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }

}

What can I do to improve the code? It looks very sloppy.


texts: Which pattern could help to refactor this controller code?

texts:
I know I should use services and patterns to refactor this controller action, but I can't imagine one that could fit/be appropriate for this problem.

It seems a strategy or template, but a strategy is supposed to be changed if needed; in my case, it should be always the same:

Get the customer

If doesn't exist store the error key (and dispatch/redirect)
Otherwise continue

Get current agent permission

If special privileges, just continue
Otherwise, check customer agent against current logged agent. In case of error, store the errore key (and dispatch/redirect)

Check if customer is enabled, otherwise store the error key (and dispatch/redirect)
Get customer users

If there are no users, store the error key (and dispatch/redirect)
Otherwise continue

Pick the first user and check his privileges

In case of errors, store the error key  (and dispatch/redirect)
Success, redirect

Actual code:

public function impersonateAction($id, Request $request)
{
    $referer = $this->redirect($request->headers->get('referer'));

    /** @var \CommonBundle\Model\CustomerInterface $customer */
    $customer = $this->get('common.repository.customer')
        ->find($id);

    /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */
    $dispatcher = $this->get('event_dispatcher');

    $error = false;

    // Customer doesn't exist
    if (!$error && empty($customer)) {
        $error = Impersonate::CUSTOMER_NOT_FOUND_ERROR;
    }

    // Check current agent privileges
    if (!$error && !$this->isGranted(AgentInterface::ROLE_SUPER_AGENT)
        && $customer->getAgent() !== $this->getUser()) {
        $error = Impersonate::DENIED_ERROR;
    }

    // Customer is disabled
    if (!$error && !$customer->isEnabled()) {
        $error = Impersonate::CUSTOMER_DISABLED_ERRROR;
    }

    // There are no users for this customer
    /** @var \CommonBundle\Entity\Repository\UserRepositoryInterface $repository */
    $repository = $this->get('common.repository.user');
    if (!$error && !($users = $repository->findByCustomer($customer))) {
        $error = Impersonate::NO_USERS_ERROR;
    }

    // We have a candidate, forward the check to Symfony user checker
    if (!$error) {
        try {
            $this->get('security.user_checker')->checkPreAuth(current($users));
        } catch (\Exception $e) {
            $error = Impersonate::USER_UNKOWN_ERROR;

            if ($e instanceof LockedException) {
                $error = Impersonate::USER_LOCKED_ERROR;
            }

            if ($e instanceof DisabledException) {
                $error = Impersonate::USER_DISABLED_ERROR;
            }

            if ($e instanceof AccountExpiredException) {
                $error = Impersonate::USER_ACCOUNT_EXPIRED;
            }
        }
    }

    // Dispatch the error and redirect to referer
    if ($error) {
        $dispatcher->dispatch(
            AgentEvents::CUSTOMER_IMPERSONATE_ERROR,
            new ImpersonateEvent($this->trans($error))
        );
    }

    // Success
    $this->loginUser(
        $user,
        $this->container->getParameter('agent.impersonate.firewall_name')
    );

    return $this->redirect($this->generateUrl(
        $this->container->getParameter('agent.impersonate.target_path')
    ));
}