texts:
I have the following Ruby code, which parses an XML document sax style (it's a very simplified version):

require 'nokogiri'

class ParsingError < RuntimeError; end

class Parser
  def initialize mapper, collector, error_collector
    @error_collector = error_collector
    @sax_handler = Handler.new(collector, @error_collector, mapper)
  end

  def process io_stream
    parser = Nokogiri::XML::SAX::Parser.new(@sax_handler)
    parser.parse_io(io_stream, 'UTF-8')
  rescue ParsingError => e
    @error_collector << "ParsingError: #{e.message}"
  end
end

class Handler < Nokogiri::XML::SAX::Document
  def initialize collector, error_collector, mapper
    @mapper = mapper
    @collector = collector
    @error_collector = error_collector
  end

  def start_element name, attrs=[]
    return if name=='nodes'
    @current_element = @mapper.new(name)
  end

  def end_element name, attrs=[]
    return if @current_element.nil?
    data = @current_element.get_errors
    if data[:errors].empty?
      @collector << @current_element.result
    else
      @error_collector << data
    end
    @current_element = nil
  end

  def characters string
    @current_element.record(string) if @current_element
  end

  def error message
    raise ParsingError, message
  end
end

class Mapper
  def initialize name
    @data = ""
    @name = name
  end

  def record str
    @data << str
  end

  def result
    {name: @name, data: @data} # here are more properties
  end

  def get_errors
    arr = []
    if @data.index("Error 123")
      arr << "Error Code 123"
    elsif @data.index("Error 456")
      arr << "Error Code 456"
    elsif @data.index("Error 789")
      arr << "Error Code 789"
      # and a lot more validations
    end
    {name: @name, errors: arr}
  end
end

# Example usage
xml = %{<?xml version="1.0" encoding="UTF-8"?>
  <nodes>
    <node1>some more data</node1>
    <node2>data Error 123</node2>
    <malformed xml
  </nodes>
}
collector = []
error_collector = []
mapper = Mapper
parser = Parser.new(Mapper, collector, error_collector)
parser.process(StringIO.new(xml))
puts "Data:"
puts collector
puts
puts "Errors:"
puts error_collector

My problem is the data collection and error handling.

I'm passing two arrays around, collector and error_collector, which doesn't seem right. I want to collect data and errors in one place, but the collector itself should simply implement a << method (like an Array). Any advice how to improve it?
Generally, the error handling feels weird. I need it in two places: Logging parsing errors and validations on items. To identify the items I also need the name of a node, except when it's a parsing error. So there are two kinds of errors: Parsing and node validation errors. How could I improve this code and remove the code smells?
Any other advice how to improve the code above?


texts:
In my Uni, my scientific professor asked me to make some researches about the extreme points of polyhedrals. And I did them. I found that there is still no code in public for searching extreme points for polyhedral with n dimensions (n - x's), but polyhedrons are everywhere (CV, game theories, etc.). I wrote a function for this task and made a python library (also there are matrix and array combination maker functions).

All I want is to make this code more optimal and compatible for all python versions (I have some troubles that some times happen when I install it by "pip install lin", but other times no). I want to make the life of people easier and make it more comfortable.

I am asking for you to test this function on your computer and write if you have any bugs, fails or thoughts on how to make it better. I am open to constructive criticism and non-constructive too (it will help to understand if somebody needs it or that is just a waste of time).

All the examples, instructions and code on my GitHub: https://github.com/r4ndompuff/polyhedral_set

import numpy as np
import itertools as it
import math
import re

def permutation(m,n):
    return math.factorial(n)/(math.factorial(n-m)*math.factorial(m))

def matrix_combinations(matr,n):
    timed = list(map(list, it.combinations(matr, n)))
    for i in range(n):
        timed[i][i][i] = np.asscalar(timed[i][i][i])
    all = np.array(list(timed))
    return all

def array_combinations(arr,n):
    timed = list(map(list, it.combinations(arr, n)))
    for i in range(n):
        timed[i][i] = np.asscalar(timed[i][i])
    all = np.array(list(timed))
    return all

def check_extreme(matr, arr, x, sym_comb, m):
    sym_comb = sym_comb.replace(']', '')
    sym_comb = sym_comb.replace('[', '')
    sym_comb = re.split("[ ,]", sym_comb)
    for i in range(m):
        td_answer = sum(matr[i]*x)
        if sym_comb[i] == '>':
            if td_answer <= arr[i]:
                return 0
        elif sym_comb[i] == '>=':
            if td_answer < arr[i]:
                return 0
        elif sym_comb[i] == '<':
            if td_answer >= arr[i]:
                return 0
        elif sym_comb[i] == '<=':
            if td_answer > arr[i]:
                return 0
        elif sym_comb[i] == '=':
            if td_answer != arr[i]:
                return 0
        elif sym_comb[i] == '!=':
            if td_answer == arr[i]:
                return 0
        else:
            return 0
    return 1

def extreme_points(m,n,A,b,sym_comb):
    # Input
    A = np.array(A).reshape(m,n)
    b = np.array(b).reshape(m,1)
    # Proccess
    ans_comb = np.zeros((1,n))
    arr_comb = array_combinations(b,n)
    matr_comb = matrix_combinations(A,n)
    for i in range(int(permutation(n,m))):
        if np.linalg.det(matr_comb[i]) != 0:
            x = np.linalg.solve(matr_comb[i],arr_comb[i])
            ans_comb = np.vstack([ans_comb,x])
    ans_comb = np.delete(ans_comb, (0), axis=0)
    j = 0
    for i in range(len(ans_comb)):
        if check_extreme(A, b, ans_comb[j], sym_comb, m):
            ans_comb = ans_comb
            j = j + 1
        else:
            ans_comb = np.delete(ans_comb, (j), axis=0)
    # Output
    return ans_comb

And I am uploading some more tests. https://imgur.com/mjweDyy


texts: Handling null exception when having multiple variables

texts:
I have a lot of variables that I need to check for exceptions and output the empty field in case of a null returned value (I am reading a calender list from Sharepoint and my program is supposed to send email notifications if some of the conditions are met).

I surrounded my variables with a try-catch with a generic output "variable not found". Here is an example;

try
{
var name = item["Name"].ToString();
var dueDate= item["Due Date"].ToString();
.
.//more variables
.
var Title= item["Title"].ToString();
}
catch (Exception ex)
                        {
                            Console.WriteLine();
                            Console.WriteLine(ex.Message); //generic message for now
                            Console.WriteLine();
                        }

Is there is a way to handle this better? I know that going to each individual line and adding an exception is an option but it would save me a lot of time if I can just output something like the variable name.


texts:
I am new to Node.js and Socket.io. I implemented a realtime chat service that has a chatroom feature. When the actual product is launched, there will be at least 200 concurrent users with 50 groups of 4 people. I would appreciate any advice on its performance and any recommendations.

Server (remote server)

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static(__dirname + '/'));

//setup IO
io.on('connection', function(socket){
    console.log("A user is connected");
    var notice = {'content' : 'Hello World'};
    socket.emit("notice", notice);
    //listen for reply
    socket.on("reply",function(data){
        //extract group id, make sure the msg is sent to the particular group
        var groupid = data.group;
        var groupname = groupid + "chat";
        socket.emit(groupname, data);
        console.log("got msg");
        //save the data into mongo db
    });

    socket.on('disconnect', function(){
        console.log("A user is disconnected");
    });
});

//Open server
http.listen(3000, function(){
    console.log('listening on *:3000');
});

Client

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>WebSockets Demo</title>

WebSockets Test

Entry

            <input id="entry" type="text">
            <input id="button" type="submit" value="Enter">


texts: Generating an HTML table with colspan and rowspan from a one-dimensional array

texts:
I will be given the following input:

const input = [
  { value: "a1", colspan: 1, rowspan: 1 },
  { value: "a2", colspan: 1, rowspan: 1 },
  { value: "a3", colspan: 1, rowspan: 3 },

  { value: "b1", colspan: 1, rowspan: 1 },
  { value: "b2", colspan: 1, rowspan: 1 },

  { value: "c1", colspan: 1, rowspan: 1 },
  { value: "c2", colspan: 1, rowspan: 2 },

  { value: "d1", colspan: 1, rowspan: 1 },
  { value: "d3", colspan: 1, rowspan: 1 },

  { value: "e1", colspan: 1, rowspan: 1 },
  { value: "e2", colspan: 2, rowspan: 1 },
];
const width = 3;

And from such, I need to construct an HTML table, taking into account colspan and rowspans. The resulting table would look like:

*----+----+----*
| a1 | a2 | a3 |
+----+----+    |
| b1 | b2 |    |
+----+----+    |
| c1 | c2 |    |
+----+    +----+
| d1 |    | d2 |
+----+----+----+
| e1 | e2      |
*----+---------*

This works, but I'm not sure if it's the best approach or if it could be tackled better:

// Define the total possible cell count
// This poorly assumes no gaps
const totalCellCount = reduce(input, (sum, c) => sum + (c.colSpan * c.rowSpan), 0);

// Fill a 2d array with placeholders so the below section
// can find the next available "spot". Chunk is being
// used to create the 2d array
const grid = chunk(fill(new Array(totalCellCount), -1), columnCount);

each(input, cell => {
    // A default "not found" state.
    let start = { x: -1, y: -1 };

    // Search for the next available spot working from
    // left to right, top to bottom
    outerLoop: for(let y = 0; y < grid.length; y++) {
        for(let x = 0; x < columnCount; x++) {
            if(grid[y][x] === -1) {
                // Found our starting position, save
                // it and exit out
                start = { x, y };
                break outerLoop;
            }
        }
    }

    // No more spots. There is no scenario where it
    // could only be -1 on x or y, so just check
    // the `x`
    if(start.x === -1) {
        return false;
    }

    // Fill area with null basically saying, don't
    // do anything in this area when we access
    // the grid later for processing
    for(let y = 0; y < cell.rowSpan; y++) {
        for(let x = 0; x < cell.colSpan; x++) {
            grid[start.y + y][start.x + x] = null;
        }
    }
    // Except the upper left spot, that is the actual
    // cell. The final result for a cell of 2 x 3
    // would look like:
    //
    //   +------+------+
    //   | cell | null |
    //   | null | null |
    //   | null | null |
    //   +------+------+
    //
    grid[start.y][start.x] = cell;

});

// At this point, we now have a grid populated
// with workable data - cells and null based
// on the surface area of each. Lets convert
// this to html table td's + tr's. This,
// imo, is the "easy" bit
let trs = [];
let tds = [];

for(let y = 0; y < grid.length; y++) {
  for(let x = 0; x < grid[y].length; x++) {
    // Fetch the cell at this location. If
    // it is null, its the consumed space
    // of a colspan or a rowspan, so we
    // can just ignore it
    const cell = grid[y][x];
    if(cell) {
      const { value, rowspan, colspan } = cell;
      tds.push(''+value+'	');
    }
  }

  // End of this row, assemble and push into
  // the tr array
  trs.push('
'+tds.join('')+'
');
  // Reset the td array for the next row
  tds = [];
}

// Simple join and attach to screen
$(".table").append(trs.join(''));

JS Bin

I'm using ES6/ES2015, although I could use template strings. Ignore them for now because it seems to freak out jsbin.

The data set is reasonably small, so although performance improvements are welcome, stability and edges cases would be preferred.


texts:
I am getting used to how things should be written/thought about in (idiomatic) Haskell. I wrote a FizzBuzz program that prints to the console. I wanted to generate things from the core info of the divisors and the strings that go with them, and an array of such rules to be processed. This is in some sense a port of my original Purescript question here (deleted), but I'm interested in Haskell conventions independently, especially when they might differ from Purescript.

All improvements are welcome, but I am focusing primarily on "is this a reasonable way a user of Haskell might organize things?". One thing I'm looking to understand is when/why I might prefer making something like Fizzrule a type or newtype of (Int, String) instead of the brand new datatype here. And honestly, mapMaybe is just a carryover from how I'm used to writing things in modern Wolfram Language, so I'm curious if it's the right thing here (maybe it's a special case of something more general I should be thinking about?). Finally, is mapM_ the most natural thing to use for a task like this?

module Main where
import Data.Foldable(fold)
import Data.List(null)
import Data.Maybe(mapMaybe)

data Fizzrule = Fizzrule {divisor :: Int, yell :: String}
rule3 :: Fizzrule
rule3 = Fizzrule 3 "Fizz"
rule5 :: Fizzrule
rule5 = Fizzrule 5 "Buzz"
rule7 :: Fizzrule
rule7 = Fizzrule 7 "Quux"

processrule :: Int -> Fizzrule -> Maybe String
processrule int rule = if int `mod` (divisor rule) == 0
  then Just (yell rule) else Nothing

fizzbuzz :: [Fizzrule] -> Int -> String
fizzbuzz rules int = if null strings then show int else fold strings
  where strings = mapMaybe (processrule int) rules

main :: IO()
main = mapM_ (putStrLn . fizzbuzz [rule3, rule5, rule7]) [1..100]


texts: Am I sufficiently cleaning incoming $_GET parameters, especially in the array?

texts:
I'm trying to clean some incoming $_GET parameters.  I've not done this before, so I'd love feedback.

I'm especially concerned with the array.  While all the other parameters control simple logic, the array will be saved into the database and potentially output to users.

Please also feel free to point out any redundancies.

<?php
// int: only want a positive value
// array: wont know what this could be but it could be anything urlencoded
// string: three possible outcomes: foo, bar, fudge

( isset( $_GET["val1"] ) ? (bool) $val1 = true                              : (unset) $val1 );
( isset( $_GET["val2"] ) ? (int) $val2 = sanitize_absint( $_GET["val2"] )   : (unset) $val2 );
( isset( $_GET["val3"] ) ? (array) $val3 = sanitize_array($_GET["val3"])        : (unset) $val3 );
( isset( $_GET["val4"] ) ? (string) $val4 = sanitize_string($_GET["val4"])  : (unset) $val4 );

// further refine val4 string
val4_strip($val_4);

// sanitize
function gfahp_sanitize_absint( $int ) {
    $int = filter_var( $int, FILTER_SANITIZE_NUMBER_INT );
    $int = abs( intval( $int ) ); // positive number
    return $int;
}
function gfahp_sanitize_string( $string ) {
    // is this enough to prevent anything icky?
    $string = filter_var( $string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW );
    return $string;
}
function gfahp_sanitize_array( $array ) {
     $array = array_walk_recursive( $array, "gfahp_sanitize_string" );
     return $array;
}

function val4_strip($val_4){
// strip down val4
    if (!empty($val4){
        switch ($val4) {
            case 'foo':
                $val4 = 'foo';
            break;
            case 'bar':
                $val4 = 'bar';
            break;
            case 'fudge':
                $val4 = 'fudge';
            break;
            default:
            $val4 = (unset) $val4
            break;
        }
    }
    return $val4;
}


texts:
This R code separates the values in rData. They are classified according to the class in rClass.

To do that, ClassifiedrData is a named list, where each element in the list (a class), should be a vector with all the elements in that class.

It is slow, and I had read that I should not use for in R, but I have no clue on how to vectorize it.

(I do not necessarily need a dictionary, so I welcome another data structure to store the classified numbers if it is more practical.)

I made random data (rData and rClass) as an example, but my real data is not random (so I simply creating the data classified is not a solution)

CreateEmptyDictionary <- function(names) {
    mylist.names <- names
    mylist <- vector("list", length(mylist.names))
    names(mylist) <- mylist.names
    return(mylist)
}

#Random integers
rData <- sample(x = as.integer(c(1:100)), size = 100)

#Random class
rClass <- sample(x = c(1:10), size = 100, replace = TRUE)

#Separate rData according to his class in rClass
i <- 0
ClassifiedrData <- CreateEmptyDictionary(names <- sort(unique(rClass)))

for (a in rData) {
    i <- i + 1
    #ClassifiedrData[[rClass[i]]] <-  append(ClassifiedrData[[rClass[i]]], a)
    ClassifiedrData[[rClass[i]]][length(ClassifiedrData[[rClass[i]]])+1] <- a
}


texts:
Below comes a Value Object to represent UserId in ASP.NET application. It implements Value Identity, so equality is defined by matching of the state calculated at the moment of comparison. It depends on

public interface IAuthenticator
{
    int CurrentUserId { get; }      // may be impersonated
    int InteractiveUserId { get; }  // "real" user, may impersonate
}

which extracts state from ClaimIdentity.

Here is a definition:

public struct UserId
{
    public static IAuthenticator Authenticator { get; set; }

    public static readonly UserId Anonymous =
        new UserId(() => 0);

    public static readonly UserId Current =
        new UserId(() => Authenticator?.CurrentUserId ?? 0);

    public static readonly UserId Interactive =
        new UserId(() => Authenticator?.InteractiveUserId ?? 0);

    public UserId(int value)
        : this(() => value)
    {
    }

    UserId(Func<int> getValue)
        : this()
    {
        GetValue = getValue;
    }

    public bool Authenticated => this == Current && this != Anonymous;
    public bool Impersonated => this == Current && Current != Interactive;
    public bool Impersonating => this == Interactive && Current != Interactive;

    Func<int> GetValue { get; }
    int Value => GetValue?.Invoke() ?? 0;

    public static implicit operator int(UserId id) => id.Value;

    public static bool operator ==(UserId left, UserId right) =>
        left.Value == right.Value;

    public static bool operator !=(UserId left, UserId right) =>
        left.Value != right.Value;

    // Equals, GetHashCode are omitted for brevity
}

We can do the following now:

   if(UserId.Current.Authenticated) ...
   if(UserId.Current.Impersonated) ...
   if(UserId.Interactive.Impersonating) ...

Also:

   var uid = new UserId(33);
   if(uid.Authenticated) ...
   if(uid.Impersonated) ...
   if(uid.Impersonating) ...

And provide overloads in extension methods:

   interface IAuthorizer
   {
      void Authorize<TResource, TAction>(int resourceId, UserId userId);
   }

   static class AuthorizerExtensions
   {
      public static void Authorize<TResource, TAction>(
           this IAuthorizer authorizer, int resourceId) =>
           authorizer.Authorize<TResource, TAction>(resourceId, UserId.Current);
   }

It is intended to be used here. GitHub repository (just a sketch).

Do these terms (Anonymous, Current, Interactive, Authenticated, Impersonated, Impersonating) properly used here and look understandable? Do they have an expected behavior?


texts:
I have coded binary search in shell, just for practice.

Input

Input data is already sorted set of numbers streamed to the script. $1 is the sought number.

for i in {1..1000000}; do
    echo $RANDOM
done | sort -n | ./binsearch.ksh 10

Code

I use ksh as the fastest shell against bash, zsh and other bash clones, and as an interpreter that maintains lists - against dash.

Variables: puppy is the sought number; swamp is a sorted set of numbers.

#!/bin/ksh

puppy=$1; [ -z "$puppy" ] && {
    echo "@@@ No args specified."
    exit
}
size=0

while IFS= read -r line; do
    ((++size))
    swamp[${#swamp[*]}]=$line
done

echo

left=0
right=$(($size - 1))
while   [ $left -le $right ] ; do
    mid=$((($left + $right) >> 1))
#   echo "$left $mid(${swamp[$mid]})    $right"
    if      [ $puppy -eq ${swamp[$mid]} ]; then
        echo "$puppy    $mid"
        exit
    elif    [ $puppy -lt ${swamp[$mid]} ]; then
        right=$(($mid - 1))
    else
        left=$((mid + 1))
    fi
done
echo '</not found>'

Could you please tell what you think of this code and how can I improve it?

Note

I would care about POSIX compatibility if it was a chance to have lists in dash, but as far as there's none, I would have to use namespaces with eval and get my memory filled with 1e6 swamp_43254-like variables.


texts: Project Euler problem 92 in Scala, square digit chains

texts:
Here is a summary of the problem:
"A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before... How many starting numbers below ten million will arrive at 89?" The site also gives an example at https://projecteuler.net/problem=92.

I have a solution which arrives at the correct answer but takes ~24 seconds on my computer to complete. I used an array to record as true the index of each value which resolves to 89 through the chain described above. I used an array so that updating and checking values would take constant time. I believed that recording all numbers that resolved to 89 would save time so that the checkAll function could avoid redundant calls of chain for these values.

However, I tested this assumption and wrote a version in which chain would simply recurse until resolving to true or false without recording the chain, so that checkAll would check every single value from 1 until 10 million but perhaps save time from not recording values. Despite the change, this version took almost the exact same amount of time, although at least it's more concise.

For the above reason I now suspect that the chain of method calls used to produce the next variable in the chain function is the main bottleneck, but I am not sure whether this is possible to implement in a faster way.

object euler92 {
  def main(args: Array[String]): Unit = {
    val t0 = System.nanoTime()

    val blank = new Array[Boolean](10000000)
    def chain(number: Int, links: List[Int] = List()): Unit = {
      val next = number.toString.toList.map(_.toString).map(_.toInt).map(x => x * x).sum
      if (next == 89) for (i <- number :: links) blank(i) = true
       else if (next == 1) ()
      else {
        chain(next, number :: links)
      }
    }
    def checkAll(num: Int, counter: Int = 0): Unit = {
      if (num == 10000000) println("Answer: " + counter)
      else if (blank(num) == true) checkAll(num + 1, counter + 1)
      else {
        chain(num)
        if (blank(num) == true) checkAll(num + 1, counter + 1)
        else checkAll(num + 1, counter)
      }
    }
    checkAll(1)

    val t1 = System.nanoTime()
    println("Elapsed time: " + (t1 - t0) + " ns")
  }
}

Here is the implementation without an array:

def chain(number: Int, links: List[Int] = List()): Boolean = {
      val next = number.toString.toList.map(_.toString).map(_.toInt).map(x => x * x).sum
      if (next == 89) true
      else if (next == 1) false
      else {
        chain(next, number :: links)
      }
    }

def checkAll(num: Int, counter: Int = 0): Unit = {
  if (num == 10000000) println("Answer: " + counter)
  else {
    val ans = chain(num)
    if (ans) checkAll(num + 1, counter + 1)
    else checkAll(num + 1, counter)
  }
}
checkAll(1)

I am hoping for insight on how to improve the performance of this solution.


texts: Threadsafe static initialization of ExecutorService

texts:
I am trying to create a threadsafe singleton class based on Initialization-on-demand holder idiom . Here is my code

public class Check{
        private Check(){  }
        private static class Provider {
            static final ExecutorService INSTANCE = new ThreadPoolExecutor(5, "read this val from file", 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
        }
        public static ExecutorService getInstance() {
            return Provider.INSTANCE;
        }
    }

My expectation is to initialize ExecutorService in threadsafe manner and only one instance should be there (static). Is it good or do i need to change something here ..


texts:
I am fairly new to Python but I have been improving, and I wanted to try writing a simple program that simulates locker with multiple chambers (4) for storing "objects".
I recently used lockers at a theme park with a similar functionality.

A chamber can be reserved by simply typing a unique PIN. In the real world, the PIN would be a unique ID like a credit card track, a finger print, a barcode, or RFID.

If the PIN is already associated with a chamber, the chamber is released and made available and the user is destroyed.

If the PIN is unique, and there are chambers available (not reserved),
a chamber is reserved for the user under the unique PIN.

I hope the explanation makes sense.
I am looking for some pointers and critique on code organization and flow, best practices, and use of classes, methods, etc.

You can see the code in action here.

class Locker(object):

    def __init__(self, capacity):
        self.chambers = {}

        print 'Locker Initialized.'
        for n, chamber in enumerate(range(0, capacity)):
            self.chambers[n] = Chamber(n)
        print 'Locker Created: ', self

    def find_chamber_by_pin(self, pin):
        for chamber in self.chambers.values():
            if pin == getattr(chamber.user, 'pin', None):
                return chamber
        return None

    def find_available_chamber(self):
        for chamber in self.chambers.values():
            if chamber.occupied is False:
                return chamber
        return None

    def count_available(self):
        counter = 0
        for chamber in self.chambers.values():
            if chamber.occupied is False:
                counter += 1
        return counter

    def __len__(self):
        return len(self.chambers.keys())

    def __repr__(self):
        return '<LOCKER: {} of {} Available>:'.format(self.count_available(), len(self))

class Chamber(object):

    def __init__(self, uid):
        self.uid = uid
        self.occupied = False
        self.user = None
        print 'Chamber Initialized: ', self

    def reserve(self, user):
        self.occupied = True
        self.user = user
        print 'Chamber Reserved: ', self

    def release(self):
        self.occupied = False
        user = self.user
        del user
        self.user = None

        print 'Chamber Released: ', self

    def __repr__(self):
        return '<CHAMBER {}:{}>:{}'.format(self.uid, self.occupied,
                                             self.user)

class User(object):

    def __init__(self, pin):
        self.pin = pin

        print 'User Created: ', self

    def __repr__(self):
        return '<USER PIN: {}>'.format(self.pin)

locker = Locker(4)

while True:

    pin = raw_input('Locker Idle. Enter Unique PIN:')

    chamber = locker.find_chamber_by_pin(pin)

    if chamber:
        chamber.release()

    else:
        chamber = locker.find_available_chamber()
        if chamber:
            user = User(pin)
            chamber.reserve(user)
        else:
            print 'Chambers Full. Wait for relase.'

    print 'New Status: ', locker


texts: Nested loop to transform MongoDB results

texts:
I have the following structure returned from MongoDB:

[Class]
    0:Class // -> this.data.userInfo as seen below in the code
        _id: "ksihHTAjdhsA9"
        createdAt:Tue Mar 29 2016 13:03:45 GMT-0400 (EDT)
        weightData: Array[3]
            0: Class
                name: "my name 1"
                value: "myval1"
                weight: 154
            1: Class
                name: "my name 2"
                value: "myval2"
                weight: 191
            2: Class
                name: "my name 3"
                value: "myval3"
                weight: 210

I need to loop through the weightData nested array and store the name and value in a dictionary variable to be used in a dropdown later. I have it working, however, I feel like this could be more efficient.

var dict = [];
_.each(this.data.userInfo, info => {
  if (info) {
    _.each(info.weightData, weightInfo => {
      dict.push({
          "name": weightInfo.name,
          "value": weightInfo.value,
          "weight": weightInfo.weight
      });
    });
  }
});

console.log(dict);

/*
[Object, Object, Object]
    0:Object
        name: "my name 1"
        value: "myval1"
        weight: 154
    1:Object
        name: "my name 2"
        value: "myval2"
        weight: 191
    2:Object
        name: "my name 3"
        value: "myval3"
        weight: 210
*/


texts: Elegant way of making a List of an attribute from a list of objects containing that attribute

texts:
If this is my class:

class Something
{
    UUID id;
    // Other members
}

Given a List<Something> things and I want to get a List<UUID> ids, this is what I usually do:

List<UUID> ids = new ArrayList<UUID>
for(Something thing : things)
{
     ids.add(thing.getId());
}
return ids;

Is there a more elegant way of doing this in Java 6?

[I googled for this pattern, however, didn't find much as I think I lacked the right keywords]


texts: Create a tree from a list of nodes with parent pointers only

texts:
I want you to pick my code apart and give me some feedback on how I could make it better or more simple.

class TreeNode {
    private TreeNode left;
    private TreeNode right;
    private TreeNode parent;
    int item;

    public TreeNode (TreeNode left, TreeNode right, TreeNode parent, int item) {
        this.left = left;
        this.right = right;
        this.parent = parent;
        this.item = item;
    }

    public int getItem() {
        return item;
    }

    public void setItem(int item) {
        this.item = item;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    public TreeNode getParent() {
        return parent;
    }

    public void setParent(TreeNode parent) {
        this.parent = parent;
    }
}

public class Ebay {

    private TreeNode root;

    public Map<TreeNode, List<TreeNode>> getMap (List<TreeNode> listOfTreeNodes) {
        final Map<TreeNode, List<TreeNode>> map = new HashMap<TreeNode, List<TreeNode>>();
        for (TreeNode treeNode : listOfTreeNodes) {
            if (map.get(treeNode.getParent()) != null) {
                map.get(treeNode.getParent()).add(treeNode);
            } else {
                List<TreeNode> list = new ArrayList<TreeNode>();
                list.add(treeNode);
                map.put(treeNode.getParent(), list);
            }
        }
        return map;
    }

    public void soStuff (List<TreeNode> listOfTreeNode)  {

        final Map<TreeNode, List<TreeNode>> map = getMap (listOfTreeNode);
        root = map.get(null).get(0);

        constructTree ( map , root);
    }

    public TreeNode constructTree (Map<TreeNode, List<TreeNode>> map, TreeNode node) {
        if (map.containsKey(node)) {
            List<TreeNode> list = map.get(node);
            node.setLeft(constructTree(map, map.get(node).get(0)));
            if (list.size() == 2) {
                node.setRight(constructTree(map, map.get(node).get(1)));
            }
        }
        return node;
    }


texts: Turning an Integer into an array of ints

texts:
My goal here is pretty simple, I want to turn a number like 12435987234 into an array of integers in reverse order.  So that would look like:

[4,3,2,7,8,9,5,3,4,2,1]

I want to do this without changing the number to a string and back.  Really, I don't want to convert it at all but I'm open to hearing ideas around this.

I've found one way to do in ruby via #divmod but suspect there is a more perfomant way.

# turns 1234 into
# [4,3,2,1]
def reversed_digits(val)
  quot = val
  results = []
  while quot > 0 do
    quot, remainder = quot.divmod(10)
    results << remainder
  end
  results
end

puts reversed_digits(1234)
=> [4,3,2,1]


texts: Attempting to make my properties an enum based singleton

texts:
I was attempting to implement my first singleton using an enum, was a bit of a struggle for me and I'm not sure if its right and more importantly thread safe?

Property provider enum:

public enum PropertyProvider implements CanProvideProperties {

    INSTANCE;
    private final HashMap<String, String> properties;

    PropertyProvider() {
        properties = buildSettingsMap();
    }

    @Override
    public HashMap<String, String> getAllProperties() {
        return properties;
    }

    @Override
    public String getProperty(Property prop) {
        return properties.get(prop.toString());
    }

    @Override
    public HashMap<String, String> buildSettingsMap() {
        HashMap<String, String> temp = new HashMap<>();
        Properties prop = new Properties();
        try {
            prop.load(readFile("src/test/resources/framework.properties"));
        } catch (IOException ignore) {
            throw new RuntimeException("Framework properties file non accessible");
        }

        Enumeration<Object> KeyValues = prop.keys();
        while (KeyValues.hasMoreElements()) {
            String key = (String) KeyValues.nextElement();
            String value = prop.getProperty(key);
            temp.put(key, System.getProperty(key, value));
        }
        return temp;
    }

    @Override
    public FileInputStream readFile(String file) throws FileNotFoundException {
        return new FileInputStream(new File(file));
    }

}

Which implements the following interface:

public interface CanProvideProperties {
    String getProperty(Property prop);
    HashMap<String, String> getAllProperties();
    HashMap<String, String> buildSettingsMap();
    FileInputStream readFile(String file) throws FileNotFoundException;

}

and lastly another enum to hold some settings:

public enum Property {
    BROWSER {
        @Override
        public String toString() {
            return "browser";
        }
    },

    TESTENVIRONMENT {
        @Override
        public String toString() {
            return "env.baseurl";
        }
    },

    GRIDADDRESS {
        @Override
        public String toString() {
            return "grid.endpoint";
        }
    },

    LOCALORGRID    {
        @Override
        public String toString() {
        return "grid.or.local";
    }
    },

    PLATFORM {
        @Override
        public String toString() {
            return "platform";
        }
    },

    LANGUAGE {
        @Override
        public String toString() {
            return "application.language";
        }
    },

    PRODUCTNAME {
        @Override
        public String toString() {
            return "product.name";
        }
    },

    DATABASEURL {
        @Override
        public String toString() {
            return "database.url";
        }
    },

    BASEADMINACCOUNT {
        @Override
        public String toString() {
            return "base.admin.account";
        }
    },

    BASEADMINUSERNAME {
        @Override
        public String toString() {
            return "base.admin.username";
        }
    },

    BASEADMINPASSWORD {
        @Override
        public String toString() {
            return "base.admin.password";
        }
    },
}


texts:
This code takes id, name and marks of 3 subjects for 5 students from user base, calculates the total of 3 subjects per student, and then takes a criteria level with which to sort; level 1 sorting does sorting based on 1 criteria only, while level 2 will sort based on criteria 1 and if similar occurs (like if select level 1 criteria marks and if marks of two student are same) sorting of that pair will be done based on criteria 2, if either user have selected level 2 and criteria 2.

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

struct student
{
int id;
 int sub[3];
int total;
char name;
}s[5];
void sort1(struct student *[],int,int,int);
main()
{       int i,j,ch,c1,c2,t;
    char choice;
for(i=0;i<5;i++)
{
    s[i].total=0;
printf("Enter the id of s[%d]\n",i+1);
scanf("%d",&s[i].id);
printf("Enter the name:\n");
scanf("%s",&s[i].name);
    for(j=0;j<3;j++)
    {
    printf("Enter the marks of sub[%d] of s[%d]\n",j+1,i+1);
    scanf("%d",&s[i].sub[j]);
    s[i].total+=s[i].sub[j];
    }
}
struct student *p[5];
for(i=0;i<5;i++)
{
    p[i]=&s[i];
}
printf("You wanna sort or not?\n");
scanf("%c",&choice);
if((choice == 'y') || (choice == 'Y'))
{
    printf("Which level sorting 1 or 2 ?\n");
    scanf("%d",&ch);
    if(ch==2)
    {
        t=1;
        printf("Criteria:\t1)By name\n2)By Id\n3)By total\nEnter level1 &level 2criteria:\n");
        scanf("%d%d",&c1,&c2);
        sort1(p,t,c1,c2);
    }
    else
    {   t=0;
        printf("Enter the level 1 criteria:\n");
        scanf("%d",&c1);
        sort1(p,t,c1,10);
    }
}
}
void sort1(struct student *p[5],int t,int cri1,int cri2)
    {
int i,j;

struct student *pt;

for(i=0;i<5;i++)
{
    for(j=0;j<5;j++)
    {
        if((t==1)&&(cri1==1) && (strcmp(&p[i]->name,&p[i+j]->name)>0))
        {
            pt=p[i];
            p[i]=p[i+j];
            p[i+j]=pt;
        }
        else if((t==1) &&(cri2==2)&& (strcmp(&p[i]->name,&p[i+j]->name)==0))
        {
            if(p[i]->id<p[i+j]->id)
            {
                pt=p[i];
                p[i]=p[i+j];
                p[i+j]=pt;
            }
        }
        else if((t==1)&&(cri2==3)&&(strcmp(&p[i]->name,&p[i+j]->name)==0))
        {
            if(p[i]->total<p[i+j]->total)
            {
                pt=p[i];
                p[i]=p[i+j];
                p[i+j]=pt;
            }
        }
        else if((t==0)&&(cri1==1) && (strcmp(&p[i]->name,&p[i+j]->name)>0))
        {
            pt=p[i];
            p[i]=p[i+j];
            p[i+j]=pt;
        }
        else if((t==0) &&(cri1==2)&& (strcmp(&p[i]->name,&p[i+j]->name)>0))
        {
            if(p[i]->id<p[i+j]->id)
            {
                pt=p[i];
                p[i]=p[i+j];
                p[i+j]=pt;
            }
        }
        else if((t==0)&&(cri1==3)&&(strcmp(&p[i]->name,&p[i+j]->name)>0))
        {
            if(p[i]->total<p[i+j]->total)
            {
                pt=p[i];
                p[i]=p[i+j];
                p[i+j]=pt;
            }
        }

    }
}
for(i=0;i<5;i++)
{
    printf("Id\tName\tS1\tS2\tS3\tTotal\n\n%d\t%s\%d\t%d\t%d\t%d\n",p[i]->id,p[i]->name,p[i]->sub[0],p[i]->sub[1],p[i]->sub[2],p[i]->total);
}
}


texts:
I've been using this code for quite some time, but am wondering if there's any improvements I can make to it. Basically it's just code that runs when the page loads or if the code is run after page load, it will run right away. Do you see any cross browser compatibility issues or any more efficient ways of writing this? ol() is a predefined function to be run.

(document.readyState=='complete') ?
  ol():(window.addEventListener&&window.addEventListener("load",ol,false)||
        window.attachEvent&&window.attachEvent("onload",ol));


texts:
I'm making a web application for a restaurant kind of type. The idea is to administrate  the orders and customers.

For selecting one of the orders and showing more specific data about it, I have this PHP script. As you can see I am using prepared statements to prevent SQL injection.

<?php

try {
    $connection = new PDO('mysql:host=localhost;dbname=broodjes-service;charset=utf8mb4', 'root', 'password');
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if (!empty($_GET['order_id'])) {
        $order_id = $_GET['order_id'];

        $order_data = $connection->prepare("SELECT c.first_name, c.last_name, c.email_adress, c.customer_info, o.order_info, o.total_price, o.location, o.created FROM customers AS c LEFT JOIN orders AS o ON c.id = o.customer_id WHERE o.id = :order_id LIMIT 1");
        $order_data->bindParam(":order_id", $order_id, PDO::PARAM_INT);
        $order_data->execute();

        $query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`" . "INNER JOIN `products` ON `orders-items`.`products_id` = `products`.`id`" . "WHERE order_id = :ordero_id LIMIT 1";
        $order_items = $connection->prepare($query);

        $order_items->bindParam(":ordero_id", $order_id, PDO::PARAM_INT);
        $order_items->execute();

        $orderObject = array();
        $orderObject['header'] = $order_data->fetch();
        $orderObject['items'] = array();
        while ($orderedItem = $order_items->fetch()) {
            $orderObject['items'][] = $orderedItem;
        }

        header('Content-type: application/json');
        echo json_encode($orderObject);

        $connection = null;
    }
} catch (PDOException $e) {
    echo $e->getMessage();
    die();
}

The parameters for the 2 queries are both the same. But I don't know how to use only one line for them.

The first query is for selecting the specific data about the order.
The second query is for selecting the items inside the order.

Both queries should be run, to get all results.

Problems

It's messy that I actually have 2 queries.
It's messy that I'm using 2 lines for the same parameter

Explanation; why there are 2 queries

Whenever I use one query like this:

SELECT c.first_name,
        c.last_name,
        c.email_adress,
        c.customer_info,
        o.order_info,
        o.total_price,
        o.location,
        o.created,

        p.name,
        ot.quantity

FROM customers AS c
LEFT JOIN orders AS o ON c.id = o.customer_id
LEFT JOIN `orders-items` AS ot ON o.id = ot.order_id
LEFT JOIN `products` AS p ON ot.products_id = p.id

WHERE order_id = :order_id;

I get 3 times the results of the specific data from the customer. Then I don't know how to get back the orders-items separately. Also, whenever there are no results, I have no idea how to 'not select them' within MySQL.

Also, when using that query, when a customer doesn't have any orders_items no result is given.


texts:
I am creating a true or false quiz game and when the user chooses an answer a tick or cross will appear on the screen telling the user whether they are right or wrong and then automatically bring the next question in.

Currently I am using 2 almost identical functions that draw the next question from my question array (one for each button). It appears to work but seems very cluttered and illogical. Is there a more elegant way to code the logic to this?

Also, the concept of a previous question button has caused a lot of issues. Through a lot of research I am still not sure how I would incorporate one into the program.

@IBAction func trueButton(sender: AnyObject) {
    delay(2) {
        nextQuestionTrue()
    }
}

@IBAction func falseButton(sender: AnyObject) {
    delay(2) {
        nextQuestionFalse()
    }
}

func nextQuestionTrue() -> QuizQuestion {
    // initialize current question

    var currentQuestion: QuizQuestion = QuizQuestion(question: "", answer: false, explanation: "")

    if currentIndex < questions.count {
      currentQuestion =  questions[currentIndex]
    }

    if currentQuestion.answer == true {
        answerLabel.text = "correct"

    } else if currentQuestion.answer == false {
        answerLabel.text = "Incorrect"
    }

    questionLabel.text = currentQuestion.question
    currentIndex++
    return currentQuestion
}

func nextQuestionFalse() -> QuizQuestion {
    // initialize current question

    var currentQuestion: QuizQuestion = QuizQuestion(question: "", answer: false, explanation: "")

    if currentIndex < questions.count {
        currentQuestion =  questions[currentIndex]
    }

    if currentQuestion.answer == false {
        answerLabel.text = "correct"

    } else if currentQuestion.answer == true {
        answerLabel.text = "Incorrect"
    }

    questionLabel.text = currentQuestion.question
    currentIndex++
    return currentQuestion
}


texts: Basic Entity Framework Repository implementation

texts:
Here is simple repository pattern that I use to access data in my database. I would like some advice on how to improve this code. Commenting on my code quality is also welcome too!

public static class ProdRepository
{
    private static Entities context = null;

    public static Entities Context
    {
        get
        {
            if (context == null)
            {
                return new Entities();
            }
            else
                return context;

        }
    }

    /// <summary>
    /// Getting Outbound list in selected period of dates
    /// </summary>
    /// <param name="dateFrom">begin date</param>
    /// <param name="dateTo">end date</param>
    /// <returns>Outbound List</returns>
    public static List<OutboundModel> GetOutboundsByDate(DateTime dateFrom, DateTime dateTo)
    {
        var q = from o in Context.wms_Outbound
                where o.CreateDT <= dateTo && o.CreateDT >= dateFrom
                select new OutboundModel
                {
                    Id = o.Id,
                    Code = o.Code,
                    CreationDate = o.CreateDT,
                    RootQuantity = o.RootQuantity
                };

        return q.ToList();

    }

}


texts:
I just made my first registration form with password confirmation, hashing with BCRYPT and PDO. As a beginner, looking around on StackExchange, I seem to miss a lot.

To keep it simple for myself, I coded PHP and HTML on the same page. Hence I'm just into PHP for 3 days now.

if (isset($_POST['register'])) {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $cPassword = $_POST['cPassword'];

    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];

    $host = 'localhost';
    $db = 'loginform';
    $user = 'root';
    $pass = '';
    $charset = 'utf8mb4';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";

    try {
        $pdo = new PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }

    if ($password != $cPassword)
        $msg = "Wachtwoord komt niet overeen!";

    else {

        $hash = password_hash($password, PASSWORD_BCRYPT);

        $sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $hash]);

        $msg = "U bent geregistreerd!";
        header( "Refresh:3; url=/Login2/inloggen.php", true, 303);

    }
}


texts:
I was wondering if someone could help critique this code I put together. It is supposed to delete all temp files and folders and then empty the recycle bin. I had to make some adjustments because using Pyinstaller, I wanted the console to stay open and have the user proceed after reading.

import os
file_size = os.path.getsize('C:\Windows\Temp')
print(str(file_size) + "kb of data will be removed")
import os, subprocess
del_dir = r'c:\windows\temp'
pObj = subprocess.Popen('rmdir /S /Q %s' % del_dir, shell=True, stdout =
subprocess.PIPE, stderr= subprocess.PIPE)
rTup = pObj.communicate()
rCod = pObj.returncode
if rCod == 0:
    print('Success: Cleaned Windows Temp Folder')
else:
    print('Fail: Unable to Clean Windows Temp Folder')
import winshell
winshell.recycle_bin().empty(confirm=False, show_progress=False,
sound=False)
from random import randint
from time import sleep
sleep(randint(4,6))
input("Press any key to continue")


texts:
I am trying to write some string algorithms which I want to work for any kinds of strings and/or locale. I managed to get some results that do work, but I am not sure that what I am doing is idiomatic or anything. Here is a function:

template<typename String>
auto upper(String str,
           const std::ctype<typename String::value_type>& f =
           std::use_facet<std::ctype<typename String::value_type>>(std::locale{}))
    -> String
{
    f.toupper(&str[0], &str[0]+str.size());
    return str;
}

I have problems getting around the way C++ works with locales and UTF-8. This algorithm is intended to take a string (well, a range of characters with a standard string interface) and returning a copy of it with all the characters converted to uppercase according to a given locale. If no locale (ctype facet) is given, the last used locale is used.

Is there anyway to improve this code (taking locale vs facet) for examples so that it would be the most useful?


texts:
state object - a state or scene from the game. When the start function is called, the state starts rendering, shutting down any other state using the renderer, and calling the specified functions (init, update, etc.) as necessary.

state constructor - given an object definitions, it overrides the object's default settings and functions with the ones specified in definitions. the autostart parameter, usually true in the first state, determines whether the state automatically starts rendering, or whether start must be called.

This abstraction is meant to make managing multiple states much easier when using ThreeJS, and it also makes pausing and bootstrapping the game easier.

'use strict';

var State = function (definitions, autostart) {
  var keys = Object.keys(definitions);
  for (var i = 0, l = keys.length; i < l; i++) {
    this[ keys[i] ] = definitions[ keys[i] ];
  }

  var paused = false;
  Object.defineProperty(this, 'isPaused', {
    get: function () {
      return paused;
    },

    set: function (value) {
      paused = !!value;

      if (paused) { this.paused();   }
      else        { this.unpaused(); }
    }
  });

  if (autostart) { this.start(); }
};

State.prototype = {
  camera:   null,
  renderer: null,
  scene:    null,
  fps:      60,

  init:     function () {},
  update:   function () {},
  shutdown: function () {},

  paused:   function () {},
  unpaused: function () {},
  resize:   function () {},

  start: function () {
    var that = this;

    if (!this.renderer || !this.renderer.hasOwnProperty('render')) { throw 'Renderer must implement a \'render\' function.'; }
    if (typeof this.renderer.__stateId === 'undefined') { this.renderer.__stateId = 0; }

    var myId = (this.renderer.__stateId += 1);

    this.init();

    function tick() {
      if (that.renderer.__stateId === myId) {
        that.renderer.render(that.scene, that.camera);
        requestAnimationFrame(tick);
      }
    } requestAnimationFrame(tick);

    var time = Date.now(), interval = 1000 / this.fps;
    function instance() {
      if (that.renderer.__stateId === myId) {
        if (!that.isPaused) { that.update(); }
      } else { return that.shutdown(); }

      time += interval;
      setTimeout(instance, interval + time - Date.now() );
    } setTimeout(instance, interval);

    function resizeListener() {
      if (that.renderer.__stateId === myId) {

        that.resize( that.renderer.domElement.clientWidth,
                     that.renderer.domElement.clientHeight );

      } else { window.removeEventListener('resize', resizeListener, false); }
    }          window.addEventListener   ('resize', resizeListener, false);

    return this.renderer.domElement;
  }
};

Sorry for posting so much code, but I have a few questions.

Is the isPaused variable declaration style bad practice? Is there a better way?
Should renderer.render be merged into the normal update loop rather than using requestAnimationFrame?
Is there an alternative to renderer.__stateId ? It looks pretty bad from a 'only modify your own objects' perspective.


texts:
I'm reading CLRS, and to practice, I rolled my version of radix sort and counting sort. I was looking at some reference implementations, particularly the LSD one from Rosetta Code, and mine performs significantly better (~10 times), especially on 64 bit inputs and if the maximum input range is known.

I think one place that could be improved is the creation of res inside counting sort. It'd be faster if I could somehow use reserve as right now I default initialize everything and then assign over them. However, I can't grow it using push_back since in the following loop, res is grown randomly, rather than linearly as required by push_back. I don't know of any data structure that can have a runtime set size with unintialized values that also gets optimized nicely in the copy line after the loop.

I experimented with variable length arrays such as T res[n] and it works up to the stack limit. However, limiting input size to the size of my stack is not acceptable. Anyway, this change did not have a noticeable impact on performance.

Suggestions for improvements would be appreciated.

Repository of algorithms

Counting sort

// counting sort, assumes each input is integral between 0 to k
// O(n) if k = O(n)
template <typename Iter, typename Op>
void cnt_sort(Iter begin, Iter end, size_t k, Op op) {
    vector<int> counts(k);   // init to 0
    for (auto i = begin; i != end; ++i) // count # elems == i
        ++counts[op(*i)];
    for (size_t i = 1; i < k; ++i)
        counts[i] += counts[i-1];   // turn into # elems <= i
    vector<typename Iter::value_type> res(distance(begin, end)); // doing useless initialization here
    for (auto j = end;;) {
        --j;
        res[--counts[op(*j)]] = *j;
        if (j == begin) break;
    }
    copy(res.begin(), res.end(), begin); // compiler optimizes this out
}

Radix sort

// radix sort, more practical than counting sort
// O(d(n + k)) running time where d is # digits, k is size of digit
class Digit_cmp {   // functor for comparing a "digit" (particular bits)
    const long long mask; // 0..63 bitfield to test against
    const size_t to_shift;
public:
    Digit_cmp(long long m, size_t ts) : mask(m), to_shift(ts) {}
    template <typename T>
    T operator()(T n) const {
        return (n & mask) >> to_shift; // mask then shift to unit digit ex. 0xfab20000 >> 16
    }
};

template <typename Iter>
void rdx_sort(Iter begin, Iter end, int bits) {
    // bits is # bits to consider up to if a max val is known ahead of time
    // most efficent when digits are base n, having lg(n) bits
    size_t r {static_cast<size_t>(log2(end - begin))};   // # bits in digit
    size_t k {static_cast<size_t>(pow(2, r))};           // range of digit
    size_t d {0};                   // current digit num
    for (long long mask = ~(~0 << r);; // ex. 0x000000ff for setting lower 8 bits on 32 bit num
        mask <<= r) {
        cnt_sort(begin, end, k, Digit_cmp(mask, r*d));
        ++d;
        if (mask & (1 << (bits-1))) break; // finished masking most significant digit
    }
}
template <typename Iter>   // range of input not known, just use max ex. 32 bits for ints
void rdx_sort(Iter begin, Iter end) {
    int bits {sizeof(typename Iter::value_type)*CHAR_BIT};
    rdx_sort(begin, end, bits);
}


texts: Seeking 5 primes such that concatenating any two of them produces another prime

texts:
I have a program which solves Project Euler problem 60:

The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.

Unfortunately the program is too slow. For finding the result of 792 in the question it takes around 20 seconds. And for five primes it takes 12 hours, which is - although I was very happy that it printed the answer around 20:00 today after I started it 08:00 - too slow.
For the solution I was helped tremendously by the Stack Overflow community. Especially the users Neil Slater, Renzo and Chris Jester-Young who answered questions regarding the algorithm, the creation of a fast prime checker and the generation of prime pairs (see: 1, 2, 3, 4, 5). I find it great that although I know no one in real life who could help me with this I was helped so much anyway. Thanks for that!
Now for the performance: after generating all primes and pairs relatively quickly, the execution spends most of the time in a function get-all-combinations-that-satisfy-constraints. This function takes as input a list of primes and a list of allowed-pairs that consist of possible combinations of primes that combined lead to a new prime.
get-all-combinations-that-satisfy-constraints tries to create sets of primes with satisfy the constraints of the question. It starts a set with a prime in the list of primes and then checks if other primes can be concatenated to the front and back of every prime in the set so far (i.e., the resulting pairs are both in the list of pairs). Once it finds a prime it is added to a resulting set and the search is continued to try add a next prime, if this is not possible the previous prime is discarded and the next prime of the list is tried. This stops once we went through all starting primes. The result is a list of all combinations of 5 primes for which any concatenation of two results in new prime.
Disclaimer: I am not completely sure if the program does what I describe above.
Here is the function:
(define (get-all-combinations-that-satisfy-constraints allowed-pairs primes)

  (define (can-be-added? prime set)
    (cond ((null? set) #t)
          ((and (contains? allowed-pairs (list (car set) prime))
                (contains? allowed-pairs (list prime (car set))))
           (can-be-added? prime (cdr set)))
          (else #f)))

  (define (get-combination start-prime)
    (let loop ((primes (delete start-prime primes))
               (acc (list start-prime)))
      (cond ((null? primes) acc)
            ((can-be-added? (car primes) acc)
             (loop (cdr primes) (cons (car primes) acc)))
            (else (loop (cdr primes) acc)))))

  (let loop ((primes primes)
             (result '()))
    (if (null? primes) result
        (let ((combo (get-combination (car primes))))
          (if (= 4 (length combo))
              (loop (cdr primes) (cons combo result))
              (loop (cdr primes) result))))))

The results:

The program which uses this function and finds the smallest sum of four primes which concatenate to a new prime for each combination takes ~ 20 seconds. It tries combining primes up to 1.000. Full code: 4primes-20seconds.scm.

The program which uses this function and finds the smallest sum of five primes which concatenate to a new prime for each combination takes ~ 12 hours. It tries combining primes up to 10.000. Full code:  5primes-12hours.scm. (The memory limit needs to be set to 1024 MB.)

Why is the code so slow and is there any way execution time can be improved?
Note: general remarks on my Scheme style are very welcome as well!


texts: Quora upvotes trends Hackerrank challenge

texts:
The following code is my solution to an old problem I found today.

  Input Format

  Line 1: Two integers, N (1 ≤ N ≤ 106) and window size K (1 ≤ K ≤ N)
  Line 2: N positive integers of upvote counts, each integer less than or equal to 109

  Output Format

  Line 1..: N - K + 1 integers, one integer for each window's result on each line

  Sample Input

5 3
1 2 3 1 1

  Sample Output

3
0
-2

  Explanation

  For the first window of [1, 2, 3], there are 3 non-decreasing subranges and 0 non-increasing, so the answer is 3. For the second window of [2, 3, 1], there is 1 non-decreasing subrange and 1 non-increasing, so the answer is 0. For the third window of [3, 1, 1], there is 1 non-decreasing subrange and 3 non-increasing, so the answer is -2.

I could solve the problem's logic and the initial test cases passed. But for the longer test cases, it gives timeout.

Are there any ways I can optimize parts of the following code?

def window_result(arr, size):
    num_inc = 0
    count = 0
    for elem in arr:
        if elem == 'i' or elem == 'e':
            count += 1
        else:
            num_inc += (count*(count+1))/2
            count = 0
    num_inc += (count*(count+1))/2
    num_dec = 0
    count = 0
    for elem in arr:
        if elem == 'd' or elem == 'e':
            count += 1
        else:
            num_dec += (count*(count+1))/2
            count = 0
    num_dec += (count*(count+1))/2

    return num_inc-num_dec

conf = raw_input().strip().split()
num_days, window_size = int(conf[0]), int(conf[1])
data = [int(i) for i in raw_input().strip().split()]

begin = 0
end = window_size - 1

while end < num_days:
    diff_array = []
    for i in xrange(begin + 1, end + 1):
        if data[i] > data[i - 1]:
            diff_array.append('i')
        elif data[i] == data[i - 1]:
            diff_array.append('e')
        else:
            diff_array.append('d')
    print window_result(diff_array, window_size-1)
    begin += 1
    end += 1


texts: Exposing WCF Service with dynamic search operation

texts:
I have this WCF service providing search functionality - to be used by our client in his web application. There can be any number of search parameters and possible nesting of AND/OR operations.

Could you please have a look and share some ideas on if I can make it more client-friendly?

  <con:Search>
     <con:clientID>xxx</con:clientID>
     <con:propertyQueries>
        <wil:PropertyQuery Id="0">
            <wil:PropertyID>DocumentType</wil:PropertyID>
            <wil:Value>Statement</wil:Value>
            <wil:Operator>EQUALS</wil:Operator>
        </wil:PropertyQuery>
        <wil:PropertyQuery Id="1" AND="0">
            <wil:PropertyID>BANK</wil:PropertyID>
            <wil:Value>HSBC</wil:Value>
            <wil:Operator>EQUALS</wil:Operator>
        </wil:PropertyQuery>
        <wil:PropertyQuery Id="2" OR="1">
            <wil:PropertyID>BANK</wil:PropertyID>
            <wil:Value>BARCLAYS</wil:Value>
            <wil:Operator>EQUALS</wil:Operator>
        </wil:PropertyQuery>
        <wil:PropertyQuery Id="3" AND="0">
            <wil:PropertyID>Date</wil:PropertyID>
            <wil:Value Start="1">11/01/2014</wil:Value>
            <wil:Value End="1">11/02/2014</wil:Value>
            <wil:Operator>BETWEEN</wil:Operator>
        </wil:PropertyQuery>
    </con:propertyQueries>
  </con:Search>

The values in AND and OR attribute indicates the Id of PropertyQuery to which the condition to be added. For example:

<wil:PropertyQuery Id="2" OR="1">

performs an OR operation between Property Queries with ID of 1, 2.

Any better ideas out there to improve the interface?


texts:
I have been using a slightly modified Hamming Distance algorithm for approximate String Matching for patterns and wondering if there is something better out there. The t being the length of the text and p being the length of the pattern the worst case is roughly O(t*p). Which from looking at other Fuzzy String matching seems to be in norm.

    final int mismatches = 1;
    final String text = "bubbles";
    final String pattern = "bu";

    for(int iter = 0; iter < text.length() - pattern.length() + 1; iter++)
    {
        int missed = 0;
        int ator = 0;

        do
        {
            if(text.charAt(iter + ator) != pattern.charAt(ator))
            {
                missed++;
            }
        }while(++ator < pattern.length() && missed <= mismatches);

        if(missed <= mismatches)
        {
            System.out.println("Index: " + iter + " Pattern: " + text.substring(iter, iter + pattern.length()));
        }
    }

The output being indexes 0 bu, 2 bb, and 3 bl. The last two being mismatches with the tolerance of 1.


texts:
Being completely new to the world of C, I started off with the excercise of building a singly linked list of integers:

/*
  Single linked list test
*/
#include <stdlib.h>
#include <stdio.h>

typedef struct ListElement {
    int         value;
    struct ListElement  *next;
} ListElement;

void printList(ListElement *root) {
    ListElement *current;
    current = root;

    while (current->next) {
        printf("Value: %i\n", current->value);
        current = current->next;
    }

    printf("Value: %i\n", current->value);
}

int freeLast(ListElement *root) {
    int retval;
    retval = 1;
    ListElement *previous;
    ListElement *current;
    current = root;

    while (current->next) {
        previous = current;
        current = current->next;
    }

    if (current == root) {
        retval = 0;
    }

    previous->next = NULL;
    printf("Freeing %i\n", current->value);
    free(current);
    return retval;
}

void freeList(ListElement *root) {
    while(freeLast(root));
}

ListElement * createList(int size) {
    ListElement *root;
    ListElement *current;
    root = malloc(sizeof(ListElement));

    if (root != NULL) {
        root->value = 0;
        current = root;
        int i;

        for (i = 1; i < size; i++) {
            current->next = malloc(sizeof(ListElement));

            if (current->next != NULL) {
                current->next->value = i;
                current = current->next;
            } else {
                freeList(root);
                return NULL;
            }
        }

        return root;
    } else {
        return NULL;
    }
}

int main() {
    ListElement *root = createList(100);
    printList(root);
    freeList(root);
}

While the code compiles and runs as intended I'd like to have some feedback on the coding style, program structure and possibly existing quirks with the memory handling in C, which I hope I got right.


texts:
My coding skill is pretty rusty and moreover, I have never paid much attention to writing elegant code. I want to start on this. Problem is to merge 2 sorted linked list. Algorithmically this is trivial, but looks a good problem to practice coding.

struct node
{
 char *data;
 struct node *nextp;
}

typedef struct node node;
typedef struct node list; //I do 2 typedefs here to signify when conceptually I
//mean a whole list and when just a single node.is this a good practice? or only
//one that confuses.

node * add(node *listp, char *data)
{
 node * newp=(node *)malloc(sizeof(node));
 assert(newp != NULL);
 newp->data=(char *)malloc(sizeof(strlen(data));
 assert(newp->data != NULL);
 strcpy(newp->data,data); // allocate space in newp->data . should there be +1?
 newp->next=NULL;
 if(listp==NULL)
  listp=nextp ;
 else
  listp->nextp=newp;
 return newp;
}

list *mergelist(list * list1p, list *list2p)
{
// initialize mergedlistp;
node dummy;
node* mergedlistendp=&dummy;
list* leftlistp = NULL;

if (list1p == NULL) leftlistp=list2p;
if(list2p == NULL) leftlistp = list1p;

if(list1p != NULL && list2p!= NULL)
{
while(1)
{

 if(strcmp(list1p -> data,list2p -> data) <=0)
 {
  mergedlistendp=add (mergedlistendp,list1p->data);
  list1p=list1p -> next;
  if(list1p == NULL)
  {leftlistp=list2p; break;}
 }
 else
 {
  mergedlistendp=add (mergedlistendp,list2p->data);
  list2p=list2p -> next;
  if(list2p == NULL)
  {leftlistp=list1p; break;}
 }

}

for(leftlistp!=NULL;leftlistp = leftlistp->next)
add(mergedlistendp,leftlistp->data);

return mergedlistendp; // I have to return mergedlistp here (i.e. head of list)
//. How to store address of mergedlistendp the first time it is assigned a value?
}

I would like my code to be reviewed.Any feedback on naming, program flow, correctness, better code, indenting, idioms etc is appreciated. Please advise on how corner cases are handled more elegantly.


texts:
This is a script I've written to deploy the Elastic Stack.

Can you help me improve it? Especially the parts called out with *** markings.

deploy.sh:

#!/usr/bin/env bash
sudo sysctl -w vm.max_map_count=262144
#use the elastic utility to gen certs
docker-compose -f create-certs.yml run --rm create_certs
# Start the stack initially per Elastic documentation
docker-compose up -d
#run a password gen script to make some passwords
docker exec elasticsearch /bin/bash -c "bin/elasticsearch-setup-passwords \
auto --batch \
--url https://elasticsearch:9200" | tee es_passes.txt
#sub generated kibana and es passes into .env -> *** This could be better ***
cat es_passes.txt  | grep 'PASSWORD kibana' | awk '{print $4}' | xargs -I {} sed -r -i 's/(KIBANA_PASS=)\w/\1{}/gip' .env
cat es_passes.txt  | grep 'PASSWORD elastic' | awk '{print $4}' | xargs -I {} sed -r -i 's/(ES_PASS=)\w/\1{}/gip' .env
#eliminate duplicate lines -> *** How can I do this better ***
awk '!seen[$0]++' .env > .env_dedup
mv .env_dedup .env
#show the contents of .env
cat .env
#restart the stack after setting the passwords
docker-compose stop
docker-compose up -d

.env:

KIBANA_PASS=some_supersecure_kibana_pass
ES_PASS=some_supersecure_elasticsearch_pass

other files:

docker-compose.yml
create-certs.yml

update:
I have fixed the substitution lines. They now read:

cat es_passes.txt  | grep 'PASSWORD kibana' | awk '{print $4}' | xargs -I {} sed -r -i 's/^KIBANA_PASS=.*$/KIBANA_PASS={}/' .env
cat es_passes.txt  | grep 'PASSWORD elastic' | awk '{print $4}' | xargs -I {} sed -r -i 's/^ES_PASS=.*$/ES_PASS={}/' .env


texts:
Here I made a program in batch that detects all files with the .user extension. Then it allows the user to pick a username by entering the number associated with that username.

The code is messy, so I will explain.

@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
:login_menu
cls
set x=1
set users=
cd "users"
for %%A in (*.user) do (
echo !x!. %%~nA
set users=%%~nA:!x!,!users!
set /a x=!x!+1
)
echo.
set /p ch=Select User:
if "%ch%" == "" (goto login_menu)

for %%B in (%users%) do (
    for /f "tokens=1,2 delims=:" %%C in ("%%B") do (
    set userNumber=%%D
    set userN=%%C
    if !ch! == %%D goto password
    echo BDEV: %%B
    pause
)
)
echo.
echo That user doesn't exist!
pause
goto login_menu

:password
cls
cd "users"
for /f "tokens=1,2 delims=:" %%E in (!userN!.user) do (set password=%%F)
echo Enter your password, !userN!
echo.
set /p password1=Password:

if %password1% == %password% goto menu
echo.
echo That password is invalid!
pause
goto password

:menu
echo Hey! You're logged in as !userN!
pause

The variable x is going to be the number which the username will be associated with. The variable users Makes sort of a 'map' to usernames to the number associated with that username

In the first for loop, it gets all the files in the folder users. It echo's out all the usernames that the user can pick.

The second for loop goes into the variable users and separates the usernames with their respective numbers. For example: if I have the usernames admin:4,steve:3,john:2,jane:1 it will separate them into admin:4 and steve:3 and john:2 and jane:1.

The third for loop (which is in the second for loop) separates each username to number into separate variables. For example, if we have the username Collins with the number 3, it will put the username Collins in the userN variable and the number 3 into the variable userNumber.

It then checks what number the user selected.

The final for loop goes into the user file that the user has selected. So if the user selected admin it will go to the user file admin.user and find the password.

If the password is invalid, it rejects access. If it correct it allows access.

Is there any way to make it less like spaghetti code?

If you need more explanation, I will be happy to provide more information.


texts:
Hi I have a simple tcp server, and that server receives messages with specific length so basically i need to wait for TcpClient to fill buffer with that amount of data, and it works.

But I am not sure if this should look like it looks as I am writing this in f# and still learning:

let private WaitForData (client : TcpClient, dataLength : int) : Async<bool>=

    async {

        let mutable loopBreaker : bool = true
        let mutable result : bool = false

        while loopBreaker do
            let isConnectionAlive : bool = IsConnectionEstablished client && client <> null

            if isConnectionAlive && client.Available >= dataLength then
                result <- true
                loopBreaker <- false

            if isConnectionAlive = false then
                result <- false
                loopBreaker <- false

            Task.Delay(500)
            |> Async.AwaitTask
            |> ignore

        return result
    }

So as you see I use mutables to exit while loop and set result value, and have some if there.

Is this OK or maybe there is some more elegant way to write this


texts: Idiomatic approach to applying a keyword replace algorithm to a Java 8 Stream

texts:
I have an approach that seems to work though I feel like I must be misusing something to achieve it.  I am implementing a keyword matching algorithm to a Java 8 IntStream.  The goal is to walk over a stream of char values (created by calling .chars() on an input string called sentence).  If a keyword matches it is returned with its replacement value otherwise the original characters are returned unmodified.  The code I have written so far looks like this:  The Replacer is implemented as a Consumer<Character> with some stateful properties:

class Replacer implements Consumer<Character> {
    StringBuffer out;
    StringBuffer buffer;
    KeywordTrieNode current_keyword_trie_node;
    KeywordTrieNode keyword_trie_root;

    public Replacer(KeywordTrieNode keyword_trie_root) {
        this.keyword_trie_root = keyword_trie_root;
        this.current_keyword_trie_node = keyword_trie_root;
        this.out = new StringBuffer();
        this.buffer = new StringBuffer();
    }

    @Override
    public void accept(Character c) {
        KeywordTrieNode node = current_keyword_trie_node.get(c);
        if (node != null) {
            buffer.append(c);
            current_keyword_trie_node = node;
        } else {
            String keyword = current_keyword_trie_node.get();
            if (keyword != null) {
                out.append(keyword);
            } else {
                out.append(buffer);
            }
            out.append(c);
            buffer = new StringBuffer();
            current_keyword_trie_node = this.keyword_trie_root;
        }
    }

    @Override
    public String toString() {
        // Flush the buffer
        String keyword = current_keyword_trie_node.get();
        if (keyword == null) {
            out.append(buffer);
        } else {
            out.append(keyword);
        }
        return out.toString();
    }
}

Then to use this I have this function:

public String replace(String sentance) {
    return replace(sentance.chars());
}
public String replace(IntStream stream) {
    Replacer replacer = new Replacer(this.keyword_trie_root);

    stream.mapToObj(c -> (char) c).forEachOrdered(replacer);

    return replacer.toString();
}

Here the String is converted into a IntStream, the stream is then mapped into a stream of char values (which are autoboxed into Character which is needed for the underlying Map inside the keyword_trie_root).  Then the replacer is passed to forEachOrdered allowing it to see each character and build a bigger and bigger StringBuffer until it's toString() is invoked (performing one final buffer flush).  This doesn't feel like the correct use of Java streams but I'm hitting a bit of a wall when trying to reimagine this as a Combiner which I think is the correct way to solve this problem.  Any ideas?


texts:
I'd had a hard time getting this to work. I’d like to parse a file containing data and copy this data into a struct.

The data file (test.dat) looks like this:

1,"Tom","Smith"
2,"Peter","Perth Junior"
3,"Cathy","Johnson"

I use the following function.

func parseDataFile() {

    struct person {
        var id: Int
        var first: String
        var last: String
    }

    var friends: [person] = []
    let filePath = Bundle.main.path(forResource: "test", ofType: "dat")
    guard filePath != nil else { return }
    let fileURL = URL(fileURLWithPath: filePath!)
    do {
        let file = try String(contentsOf: fileURL, encoding: .utf8)
        let arrayOfLines = file.split { $0.isNewline }
        for line in arrayOfLines {
            let arrayOfItems = line.components(separatedBy: ",")
            let tempPerson = person(id: Int(arrayOfItems[0])!,
                                    first: arrayOfItems[1].replacingOccurrences(of: "\"", with: ""),
                                    last: arrayOfItems[2].replacingOccurrences(of: "\"", with: "")
            )
            friends.append(tempPerson)
        }
    } catch {
        print(error)
    }
}

I read the data into a string, split it up into an array (every line is a record). The records are copied into the struct person. This works fine, but I'm sure this is far from optimum.

I was testing a lot with PropertyListDecoder().decode(), but this seems to accept only dictionary formatted data (not sure though ?!).

Next, is it necessary to use an array record, as intermediate step, prior putting the line into a struct?

Last, is there no method to copy all comma separated strings to an array, without filling every property of the struct individually (like I did)?

Besides that, I believe that there is also a much more efficient way to get rid of the string delimiting quotes than using replacingOccurrences(of:with:)?

Any comments would be appreciated.


texts: Check if array is monotonic i.e either monotone increasing or monotone decreasing

texts:
An array A is monotone increasing if for all i <= j, A[i] <= A[j].  An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
public class MonotonicArray {

    public boolean IsMonotonic(int[] numbers) {
        if (numbers == null  || numbers.length == 0) {
            return false;
        }

        if (numbers.length == 1) {
            return true;
        }

        boolean increasing = false;
        boolean decreasing = false;

        for (int index = 0; index < numbers.length - 1; index++) {

            if (numbers[index + 1] == numbers[index]){
                continue;
            }

            if (numbers[index + 1] > numbers[index]) {
                if (!decreasing) {
                    increasing = true;
                } else {
                    return false;
                }
            }

            else  {
                if (!increasing) {
                    decreasing = true;
                } else {
                    return false;
                }

            }

        }
        return increasing || decreasing;
    }
}

Test cases:
class MonotonicArrayTest extends MonotonicArray {

@org.junit.jupiter.api.Test
void isMonotonic1() {

    int[] array =  new int[]{1,2,3};
   assertEquals(true,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic2() {

    int[] array =  new int[]{-1,-2,-3};
    assertEquals(true,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic3() {

    int[] array =  new int[]{1,2,1};
    assertEquals(false,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic4() {
    int[] array =  new int[]{-1,2,-9};
    assertEquals(false,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic5() {

    int[] array =  new int[]{9,3,2};
    assertEquals(true,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic6() {
    int[] array =  new int[]{};
    assertEquals(false,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic7() {
    int[] array =  new int[]{1};
    assertEquals(true,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic8() {
    int[] array =  new int[]{9,7,5,4,8,10};
    assertEquals(false,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic9() {
    int[] array =  new int[]{1,1,2,3};
    assertEquals(true,IsMonotonic(array));
}

@org.junit.jupiter.api.Test
void isMonotonic10() {
    int[] array =  new int[]{1,1,0,-1};
    assertEquals(true,IsMonotonic(array));
}

}


texts: Updating a textarea label with the number of characters inside the field itself

texts:
How would you improve and shorten this small piece of code? It basically update a textarea label with the number of characters inside the field itself. It saves the original label and restores it when characters count is 0.

jsFiddle here while sprintf is from here.

$('#send_sms_content').keyup(function() {

    // The label and characters count of textarea
    var label = $(sprintf('label[for="%s"]', $(this).attr('id'))),
        count = $(this).val().length;

    // Make backup of label original html into "data-original-value" attribute
    if($.type(label.attr('data-original-value')) === 'undefined') {
        label.attr('data-original-value', label.html());
    }

    // When empty textarea then restore the orignal label
    if(count == 0) {
        label.html(label.attr('data-original-value'));
        return;
    }

    // Regular expression to match any digit in the label
    var digit = new RegExp("[0-9]+")

    // If there are no digits in the label append the count
    if(!digit.test(label.html())) {
        label.html(label.html() + ' ' + sprintf('(%s)', count));
    }
    else { // There are digits already, replace with the new count
        label.html(label.html().replace(digit, count));
    }

});


texts:
Question from the book:
(Geometry: closest pair of points) Write a program that lets the user click on
the panel to dynamically create points. Initially, the panel is empty. When a
panel has two or more points, highlight the pair of closest points. Whenever a
new point is created, a new pair of closest points is highlighted. Display the
points using small circles and highlight the points using filled circles, as
shown in Figure 16.26a–c. (Hint: store the points in an ArrayList.)

Solution attempt:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class ClosestPairOfPoints extends JFrame {
    private PointsPanel pointsPanel = new PointsPanel();

    public ClosestPairOfPoints() {
        add(pointsPanel);
    }
    //Main method
    public static void main(String[] args) {
        JFrame frame = new ClosestPairOfPoints();
        frame.setTitle("Exercise16_22");
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private class PointsPanel extends JPanel {
        private ArrayList<Point> points = new ArrayList<Point>();
        private int[] closestPairIndices = {2, 2};

        public PointsPanel() {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    addPoint();
                    repaint();
                }
            });
        }

        /** Add new random point **/
        public void addPoint() {
            int randomX = (int)(Math.random() * getWidth());
            int randomY = (int)(Math.random() * getHeight());

            points.add(new Point(randomX, randomY));
            if (points.size() > 1) {
                updateClosestPair();
            }
        }

        /** Alternate method **/
        private int minDistance = Integer.MAX_VALUE;
        private void updateClosestPair() {
            if (minDistance == Integer.MAX_VALUE) {     // Obtain first actual minDistance
                minDistance = getDistance(points.get(0), points.get(1));
                closestPairIndices[0] = 0;
                closestPairIndices[1] = 1;
            }
            else {      // Compare previous points with latest point
                for (int i = 0; i < points.size() - 1; i++) {
                    int testDistance = getDistance(points.get(i), points.get(points.size() - 1));
                    if (testDistance < minDistance) {
                        minDistance = testDistance;
                        closestPairIndices[0] = i;
                        closestPairIndices[1] = points.size() - 1;
                    }
                }
            }
        }

        private int getDistance(Point p1, Point p2) {
            double a = (double)Math.abs(p1.getX() - p2.getX());
            double b = (double)Math.abs(p1.getY() - p2.getY());

            return (int)Math.sqrt(a * a + b * b);
        }

        /** Paint Points from ArrayList and highlight the Points at closestPairIndices **/
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // Draw every point
            for (int i = 0; i < points.size(); i++) {
                if (i == closestPairIndices[0] || i == closestPairIndices[1]) {
                    g.fillOval((int)points.get(i).getX(), (int)points.get(i).getY(), 5, 5);
                }
                else {
                    g.drawOval((int)points.get(i).getX(), (int)points.get(i).getY(), 5, 5);
                }
            }
        }
    }
}


texts: Review of three constructors for a String class

texts:
I have the following declaration in my String.h file:

private:
    char* nstring;
    int nlength;
};

The following are three constructors I've implemented in String.cpp.  I would like these to be reviewed.

// Default constructor for this class. Initializes an empty string.
string::string() {
    nlength = 1; // for "\0" terminating character at the end of the char array
    nstring = new char[nlength];
    nstring[nlength - 1] = '\0';
}

// Constructor for String class. Initializes a string based on the given C string.
string::string(const char* input) {
    nlength = strlen(input) + 1;
    nstring = new char[nlength];
    for (int i = 0; i < (nlength - 1); i++) {
        nstring[i] = input[i];
    }
    nstring[(nlength - 1)] = '\0';
}

// Copy constructor for String class.
// Initializes a string from an already existing string.
// The contents of the existing string should be copied over to this string.
string::string(const string& S) {
    nlength = S.nlength;
    nstring = new char[nlength];
    for (int i = 0; i < (nlength - 1); i++) {
        nstring[i] = S.nstring[i];
    }
    nstring[(nlength - 1)] = '\0';
}


texts: MASM) assembly implementation of recursive Fibonacci

texts:
I'm trying to teach myself assembly via MASM, below is my first implementation of the recursive form of the fibonacci sequence. I timed it against an equivalent C implementation in release mode and the C implementation was much better optimized. What can I do better? I haven't gotten the hang of how the various side effects of instructions impact the state of registers or flags yet, or, well, most things in assembly.
Assembly:
;extern "C" unsigned long fibonacci_asm_canonical(unsigned long number)
fibonacci_asm_canonical proc number: dword
    LOCAL fib_lhs:DWORD
    mov eax, number ; store number parameter in eax register (also used as return value).
    .IF eax > 1
        ; recursively call this function, retrieving the value for the left-hand side.
        dec eax
        mov edx, eax
        invoke fibonacci_asm_canonical, edx
        mov fib_lhs, eax ; store the result of fibonacci_asm_canonical(number - 1) into fib_lhs.
        mov eax, number ; store number parameter in eax register to set up right-hand side of addition.
        ; recursively call this function, retrieving the value for the right-hand side.
        sub eax, 2
        invoke fibonacci_asm_canonical, eax
        ;eax now contains result of fibonacci_asm_canonical(number - 2), following the invocation,
        ;so add it with the result of fibonacci_asm_canonical(number - 1) which is in fib_lhs.
        add eax, fib_lhs
    .ENDIF
    ret
fibonacci_asm_canonical endp

C version:
unsigned long fib_canonical(unsigned long number)
{
    if (number <= 1)
        return number;
    return fib_canonical(number - 1) + fib_canonical(number - 2);
}

```


texts: List of all possible monetary totals from a set of cash

texts:
This code prints out a list of all the possible sums that can be made from a set of cash.

For example, say you have 2 fives and 2 tens in your wallet. With these, you can make exact change for $0, $5, $10, $15, $20, $25, and $30.

import itertools
cash = {1: 1, 5: 3, 10: 2} # Keys are denominations (e.g. $1 bill)
                        # Values are the numbers of bills (e.g. three $1 bills)
totals = set() # Set of possible totals
cash_list = [i for i in sorted(cash) for j in range(cash[i])] # List of all bills
for r in range(len(cash_list)+1):
    for subset in itertools.combinations(cash_list, r): # All the bill combinations
        totals.add(sum(subset)) # Record the total of the bills
print(sorted(list(totals))) # Print all possible totals

Output:

[0, 1, 5, 6, 10, 11, 15, 16, 20, 21, 25, 26, 30, 31, 35, 36]


texts:
I was implementing something similar to Python's join function, where

join([a1, a2, ..., aN], separator :: String)

returns

str(a1) + separator + str(a2) + separator + ... + str(aN)

e.g.,

join([1, 2, 3], '+') == '1+2+3'

I was implementing something similar and was wondering, what is a good pattern to do this? Because there is the issue of only adding the separator if it is not the last element

def join(l, sep):
    out_str = ''
    for i, el in enumerate(l):
        out_str += '{}{}'.format(el, sep)
    return out_str[:-len(sep)]

I'm quite happy with this, but is there a canoncial approach?


texts: User controller for a .net core WebAPI dating app

texts:
I have this user controller that follows the repository pattern.  It works perfect, but is it easy to understand? Is this good quality work?

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp_API.Data;
using DatingApp_API.DataTransferObjects;
using DatingApp_API.Helpers;
using DatingApp_API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DatingApp_API.Controllers
{
    [ServiceFilter(typeof(LogUserActivity))]
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IDatingRepository _repo;
        private readonly IMapper _mapper;
        public UsersController(IDatingRepository repo, IMapper mapper)
        {
            _mapper = mapper;
            _repo = repo;
        }

        [HttpGet]
        public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
        {
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var userFromRepo = await _repo.GetUser(currentUserId);

            userParams.UserId = currentUserId;

            if(string.IsNullOrEmpty(userParams.Gender))
            {
                userParams.Gender = userFromRepo.Gender == "male" ? "female" : "male";
            }

            var users = await _repo.GetUsers(userParams);
            var usersToReturn = _mapper.Map<IEnumerable<UserForListDTO>>(users);

            Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
            return Ok(usersToReturn);
        }

        [HttpGet("{id}", Name = "GetUser")]
        public async Task<IActionResult> GetUser(int id)
        {
            var user = await _repo.GetUser(id);
            var userToReturn = _mapper.Map<UserForDetailedDTO>(user);

            return Ok(userToReturn);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateUser(int id, UserForUpdateDTO userForUpdateDTO)
        {
            if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            return Unauthorized();

            var userFromRepo = await _repo.GetUser(id);

            _mapper.Map(userForUpdateDTO, userFromRepo);

            if(await _repo.SaveAll())
                return NoContent();

            throw new Exception($"Updating user {id} failed on save");
        }

        [HttpPost("{id}/like/{recipientId}")]
        public async Task<IActionResult> LikeUser(int id, int recipientId)
        {
            if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
                return Unauthorized();

            var like = await _repo.GetLike(id, recipientId);

            if(like != null)
                return BadRequest("You already like this user");

            if(await _repo.GetUser(recipientId) == null)
                return NotFound();

            like = new Like
            {
                LikerId = id,
                LikeeId = recipientId
            };

            _repo.Add<Like>(like);

            if(await _repo.SaveAll())
                return Ok();

            return BadRequest("Failed to like user");
        }

    }
}


texts: Creating connections and executing queries/updates

texts:
I've recently learned how to use MySQL to store/retrieve data. I've created a MySQLManager class for creating connections and executing queries/updates. Would this be an efficient way to do so?

public class MySQLManager {

private String host;
private String port;
private String database;
private String user;
private String password;

public MySQLManager(String host, String port, String database, String user, String password){
    this.host = host;
    this.port = port;
    this.database = database;
    this.user = user;
    this.password = password;
}

private Connection createConnection(){
    Connection connection;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user, password);
        return connection;
    } catch (SQLException e) {
        System.out.println("Could not connect to MySQL server! because: " + e.getMessage());
    } catch (ClassNotFoundException e) {
        System.out.println("JDBC Driver not found!");
    }
    return null;
}

public ResultSet executeQuery(String query){
    Connection connection = createConnection();
    Statement statement = null;
    ResultSet set = null;
    try {
        statement = connection.createStatement();
        set = statement.executeQuery(query);
        return set;
    } catch (SQLException e) {
        e.printStackTrace();
    } finally { //Close in order: ResultSet, Statement, Connection.
        try { set.close(); } catch (Exception e) { }
        try { statement.close(); } catch (Exception e) { }
        try { connection.close(); } catch (Exception e) { }
    }
    return null;
}

public void executeUpdate(String update){
    Connection connection = createConnection();
    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.executeUpdate(update);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try { statement.close(); } catch (Exception e) { }
        try { connection.close(); } catch (Exception e) { }
    }
}
}

I would then use this to execute queries/updates:

MySQLManager manager = new MySQLManager(host, port, database, user, pass);
manager.executeQuary("SELECT * FROM table;");
manager.executeUpdate("Some update;");

Are there any better ways of doing this? Is there anything I can improve in my code?


texts: Optimizing snap SVG animation with collision detection

texts:
I have a snap SVG animation which animates a bunch of circles, and draws a line between them if they are within a certain proximity of each other. However, I realize that there is a lot of optimizing I can do, but I'm not exactly sure how to do it. I feel like it would be useful to

have a good example of proximity detection in snap
have some more information on optimizing animations in snap SVG. It hasn't been easy to find.

Here is a working example of the animation:

and here are the things I believe can be optimized:

Each circle calls its own animation function - the circles have all been added to a group, and I'm guessing there is a way to apply random motion to all members of a group that is more performant than call a function for each and every element within the group.

for (var i=0; i<this.drawingConfig.circles.amount;i++){
  ...
  this.animateSingle(circleShape);
}

The proximity function is awkward - for each circle, for each update cycle, I have to loop through an array of all the other circles and find out if the X and Y coordinates are close enough to draw a line to. Plus, that means you're getting duplicate lines, because each circle will draw a line to its neighbors, instead of having a single shared line between the two.

for (var i=0;i<circles.length;i++){
  var nextCircle = circles[i].node;
  var nextCircleX = nextCircle.cx.baseVal.value;
  var distance = Math.abs(nextCircleX-thisCircleX);
  var proximity = mainModule.drawingConfig.circles.proximity;
  if (distance < proximity){

    var nextCircleY = nextCircle.cy.baseVal.value;
    var thisCircleY = shape.node.cy.baseVal.value;
    var distanceY = Math.abs(nextCircleY - thisCircleY);
    if (distanceY < proximity){

      var line = mainModule.s.line(thisCircleX, thisCircleY, nextCircleX, nextCircleY).attr({stroke: '#a6a8ab', strokeWidth: '1px'});
      mainModule.drawingConfig.circles.circleGroup.add(line);
    }
  }
}

Correspondingly, I each circle's animation function clears all the lines on the screen. Ideally all the circles would be sharing one update function, and in that function, you'd clear the lines.

Snap.animate(startX, animX, function (val) {

  var lines = Snap.selectAll('line');
  lines.remove();

  ...

}, mainModule.drawingConfig.circles.animTime);

Right now, I can tell the renderer can't keep up with all of the various animations / loops. Any help optimizing the above things (or anything else you can see that I'm doing weird, would be greatly appreciated.


texts:
In this strstr implementation, I am basically skipping the already matched and checked characters with an if else condition. Is this a right way of implementing it?

char *strstrImp(char *input, char *find) {
    if(*find=='\0')
        return input;
    if(*input=='\0')
        return NULL;

    char *start=input;
    char *p;
    while(*start!='\0')
    {
        p=start;
        char *q=find;
        while(*p!='\0' && *q!='\0' && *p==*q)
        {
            p++;
            q++;
        }

        if(*q=='\0')
        {
            return start;
        }
        //update the starting position based on whether any character matched
        if(p == start) //no match
            start++;
        else
            start = p; //skip characters and start from the previously left place
    }
    return NULL;
}

int main()
{
    char * res;
    res = strstrImp("helloworld","low");
    printf("%s",res);
}