A byte endian swapper There are both a simple byte endian (little and big) order swapper and its testbench. A data stream inputs to the module and is converted to the other endianness by computational logic.
byte_order_swap.v
`timescale 1ns / 1ps

module byte_order_swap #
(
    parameter integer DATA_WIDTH = 32
)
(
    input wire [DATA_WIDTH - 1 : 0] data_i,
    input wire [DATA_WIDTH - 1 : 0] data_o
);
    localparam integer DATA_BYTE_NUMBER = DATA_WIDTH / 8;
    localparam integer DEC_DATA_WIDTH   = DATA_WIDTH - 1;

    generate
        genvar i;
        if (0 == (DATA_WIDTH % 4)) begin
            for(i = 0; i < DATA_BYTE_NUMBER; i = i + 1) begin
                assign data_o[(i * 8) +: 8] = data_i[(DEC_DATA_WIDTH - i * 8)  -: 8];
            end
        end
        else begin
            assign data_o = {DATA_WIDTH{1'h0}};
        end
    endgenerate

endmodule

byte_order_swap_tb.v
`timescale 1ns / 1ps

module byte_order_swap_tb;

    localparam integer              DATA_WIDTH          = 32;
    localparam integer              CLOCK_PERIOD        = 100;
    localparam integer              ITERATION_NUMBER    = 1000;
    localparam [DATA_WIDTH - 1 : 0] COUNTER_START_VALUE = 32'hAABB1122;

    wire [DATA_WIDTH - 1 : 0] counter_swap_value;

    reg                      clk;
    reg [DATA_WIDTH - 1 : 0] counter_dir_value;

    byte_order_swap #
    (
        .DATA_WIDTH (DATA_WIDTH)
    )
    byte_order_swap_dut
    (
        .data_i (counter_dir_value),
        .data_o (counter_swap_value)
    );

    initial begin
        clk = 1'h0;

        forever begin
            #( CLOCK_PERIOD / 2 ) clk = !clk;
        end
    end

    initial begin
        counter_dir_value <= COUNTER_START_VALUE;

        repeat(ITERATION_NUMBER) begin
            @(posedge clk);
            counter_dir_value <= counter_dir_value + 1'h1;
        end
    end

    task check_swap;
    begin
        repeat(ITERATION_NUMBER) begin
            @(posedge clk);
            $display("A direction value:  %h -> the swap value: %h",counter_dir_value, counter_swap_value, $time);
        end
    end
    endtask

    initial begin

        check_swap;

        $stop();
    end

endmodule

The code makes good use of parameters.  However, I see a potential problem.
    if (0 == (DATA_WIDTH % 4)) begin

That code seems to imply that any multiple of 4 is supported.  But, if I try DATA_WIDTH = 20, then I see z values in the output.  Perhaps you should restrict values to be a multiple of 8 instead:
    if (0 == (DATA_WIDTH % 8)) begin

Conventionally, the word "check" means that you will compare an actual value to an expected value and report an error if the two do not match.  The check_swap task simply displays the values.  If that is all you are looking to do, then I suggest renaming the task as display_swap or monitor_swap.
However, you could add code to the testbench to do a comparison.  If your tool suite supports SystemVerilog features, then the following additions/modifications would provide automatic checking:
wire [DATA_WIDTH - 1 : 0] data_o;
generate
    if (0 == (DATA_WIDTH % 8)) begin
        assign data_o = {<< 8{counter_dir_value}};
    end else begin
        assign data_o = '0;
    end
endgenerate

task check_swap;
    repeat(ITERATION_NUMBER) begin
        @(posedge clk);
        $display("A direction value:  %h -> the swap value: %h", counter_dir_value, counter_swap_value, $time);
        if (data_o !== counter_swap_value) begin
            $display("ERROR: data miscompare", $time);
        end
    end
endtask

To create the expected data (data_o), I copied the generate code from the design and made some simplifications.  The {<< 8{counter_dir_value}} syntax is another way to perform the byte swap.  Refer to IEEE Std 1800-2017, section 11.4.14 Streaming operators (pack/unpack).  The '0 syntax is a simplified way of assigning all bits to 0, equivalent to what you have already.  If you plan to synthesize the design, and your tool chain supports this syntax, you could even use this code in your design module.
A minor note: with that type of task body, the begin/end keywords are now optional.


OO shopping cart class + product class interaction I built a small store site for learning purposes. I loaded my 'products' from the db into a Products class.  I used a method from this class to display the products in HTML.  Of course, the HTML contains 'Add to Cart' buttons which POST the product ID and quantity when a button is clicked.  The result is that the POSTed ID and quantity are sent to the Cart class.  This works, but it seems like I should be sending a product object to my cart instead of just two values that will be stored in an array.

I'm not sure how to do that, given that product information needs to be POSTed non-objectively.  And I'm not sure if it would be better.

class Products
{

private $products;

function __construct($data)
{

    $this->products = $data;

}

public function showProduct($id, $price, $type)
{
        echo "
";
        echo $type."
";
        echo $price."
";
        echo "Quantity: <input class='quantity' name='quantity' value='1' type='text'/>
";
        echo "<button onclick='add($id);'>Add to Cart</button>";
        echo "
";
}

public function showAll()
{
    foreach ($this->products as $id => $product) {

        $this->showProduct($id, $product->price, $product->type);
    }

}

}

And the Cart class:

class Cart
{
public $items = array();

function __construct() {

    if (isset($_SESSION['cart'])) { $this->items = $_SESSION['cart']; } else { $_SESSION['cart'] = ''; }
}

private function update() {

    $_SESSION['cart'] = $this->items;
}

public function add($id, $quantity) {

    $this->items[] = array('id'=>"$id", 'quantity'=>"$quantity");
    $this->update();

}
}

I'm not sure that I was able to get the objects from these classes to interact with each other properly.

Also, in this situation, since I need to use $_SESSION to keep the cart inventory persistent, I'm not sure why I need a Cart class at all.  It seems a little superfluous, but I have a nagging feeling that it shouldn't be.

I would have done it in the following way:

<?php
    class Product {
        private $id;
        private $type;
        private $price;

        public function __toString() {
            return  "your way to display the Product object ie:
 The id is: $this->getId
 ";
        }

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

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

        public function getType()
        {
            return $this->type;
        }

        public function setType($type)
        {
            $this->type = $type;
        }

        public function getPrice()
        {
            return $this->price;
        }

        public function setPrice($price)
        {
            $this->price = $price;
        }

    }

    class Cart {
        private $products;
        private $id;

        public function getProducts()
        {
            return $this->products;
        }

        public function addProduct(Product $product)
        {
            $this->products[] = $product;
        }

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

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

        /**
         * Returns the sum off all products prices
         * array_reduce docs: http://php.net/manual/en/function.array-reduce.php
         */
        public function total(){
            return array_reduce($this->getProducts(), function($carry, $product){
                return $carry + $product->getPrice();
            });
        }

    }

It's important to note here that you are managing objects, so you will need some Object Relational Mapper to persist objects on a DB, such as Doctrine.

You need to separate concerns in a MVC architecture, the logic of your domain the 'M' of MVC (in this case the shopping cart) reside in a object model (Product + cart) . Then you need the 'C' here you tell the cart that you want to add a new product:

class Controller {
        public function someAction(){
            $product = new Product();
            $product->setId(1);
            $product->setPrice(100.00);
            $product->setType(3); //Id of the type

            $cart = new Cart;
            $cart->addProduct($product);

            $cart->total(); //Will return 100.00
            //Logic to obtain twig engine
            return $twig->render('Template', ['cart' => $cart]); //returns HTML
        }
    }

And finally the V of the MVC there is where you build your HTML:

Using a template engine like Twig:

        Total: {{cart.total()}}

              {% for product in cart.products %}

{{product}}

              {% else %}

Empty cart

              {% endfor %}

Of course building this architecture on your own could be really complicated there is when frameworks like symfony kick in http://symfony.com/. It's just a personal recommendation.

Also, take a look at OOP patterns. They will make your life easier and you will learn how to program good architectures for models.


API with revealing module pattern in Javascript I'm working on a project where I want to create a API that can be used to do some mathmatical calculations.

Here are the important aspects:

I used the revealing module pattern
I added method chaining (sort of like in JQuery)
No Prototypes used (I don't see a advantage here)

My questions are the following:

Is it a mistake to not use prototypes ? I'm sort of thinking about the benefits I could gain by using them but I don't see any.
Is the error handling the correct way or should I do it differently ?
Does the code look viable and suitable for a API ?
Is there a other way of doing the method chaining ?

I'm also open for general suggestion to improve the code further which wasn't mentioned in the questions.

Edit: I haven't mentioned that I don't have a problem with using prototypes, I do understand the prototype inheritance and I also welcome any suggestion that is written with it.

Here is the code

function type(entity) {
  return Object.prototype.toString.call(entity).slice(8, -1);
}

function isNumber(entity) {
  return type(entity) === "Number";
}

let gMath = (function() {
  let currentNumber;
  let gotNumber = false;

  let number = function(number) {
    let numberType = type(number);

    if (isNumber(number) && !gotNumber) {
      currentNumber = gotNumber ? undefined : number;
      gotNumber = true;
    } else if (gotNumber) {
      console.log("Error! Cannot define 2 numbers. Only use .number() once or call .getNumber() to clear the current one.");
    } else if (type(number) === "String") {
      console.log(`This function only accepts Numbers as arguments. You passed in: "${numberType}"`);
    } else{
      console.log(`This function only accepts Numbers as arguments. You passed in: ${numberType}`);
    }
    return this;
  }

  let scatter = function(range) {
    currentNumber = Math.floor((currentNumber + (Math.random() * range * 2) - range) + 1);
    return this;
  }

  let randomize = function(number) {
    currentNumber = Math.floor(Math.random() * currentNumber);
    return this;
  }

  let atleast = function(number) {
    currentNumber = currentNumber < number ? number : currentNumber;
    return this;
  }

  let add = function(number) {
    currentNumber += number;
    return this;
  }

  let subtract = function(number) {
    currentNumber -= number;
    return this;
  }

  let show = function() {
    console.log(currentNumber);
    return this;
  }

  let getNumber = function() {
    gotNumber = false;
    return currentNumber;
  }

  let isCurrentNumber = function() {
    console.log("Currently the gotNumber variable is: " + gotNumber);
  }

  return {
    // chainable
    scatter,
    number,
    atleast,
    randomize,
    add,
    subtract,
    show,

    // non-chainable
    getNumber,
    isCurrentNumber
  }

})();

let a = gMath.number(10)
.scatter(50)
.getNumber();

console.log(a) // --> logs a Number between -40 and 60

Not using prototypes is completely fine. It can be advantageous at times to make use of them, but I agree that there is not much / any advantage to using them in this case.

If an error occurs, you should throw the error. Just logging it and moving on can result in some incredibly confusing behavior.

The biggest issue I see with using this code as an API is the inability use more than one number at once. If I want to use it to generate multiple numbers at once I can't. As a consumer of the library I would expect the following to work.

let a = gMath.number(50).scatter(50);
// Scatter twice by the same number
let b = a.scatter(a.getNumber()).scatter(a.getNumber()).getNumber();

There is another way to do method chaining that would solve the problem illustrated above. Instead of modifying the current state and returning this, return a new immutable gMath with the correct number set.

I'll point out a few potential problems / improvements with the current code, and then show how I would structure this api while keeping the usage the same.

There's no need to define isNumber. There is a built in method Number.isNaN that can check that with the additional benefit of handing NaN values (typeof NaN === "number")
There's no need to check gotNumber twice in the number function. This chain of if statements can be quickly improved if you throw errors for invalid inputs.

if (Number.isNaN(number)) {
    throw Error('This function only accepts numbers');
}
if (gotNumber) {
    throw Error('Cannot define 2 numbers. Only use .number() once or call .getNumber() to clear the current one.');
}
currentNumber = number;
gotNumber = true;

It looks like randomize might have a bug, it accepts a number but doesn't use it.
atleast can be simplified by using Math.max instead of the ternary.
None of your methods except number check if gotNumber is set. This leads to confusing behavior especially since number says calling getNumber clears the current number.

gMath.number(10);
gMath.getNumber(); // 10
gMath.subtract(5);
gMath.getNumber(); // 5

isCurrentNumber implies that the function returns a boolean. If you decide to keep with your current design of a single instance, this should probably be renamed to hasNumber and should return a boolean that the caller can log.

With this in mind, here is how I would write this module, keeping the same methods as the original for the most part. The one change is that instead of calling gMath.number(#) you call gMath(#) to create an instance.

function gMath(number) {
    if (Number.isNaN(number)) {
        throw Error('This function only accepts Numbers as arguments.');
    }

    let instance = {
        scatter(range) {
            let num = Math.floor((number + (Math.random() * range * 2) - range) + 1);
            return gMath(num);
        },

        randomize() {
            return gMath(Math.floor(Math.random() * number));
        },

        atleast(lowerBound) {
            return gMath(Math.max(lowerBound, number))
        },

        add(num) {
            return gMath(number + num);
        },

        subtract(num) {
            // Safer than using `this` as `this` can be changed
            // by how the function is called.
            return instance.add(-num);
        },

        show() {
            console.log(number);

            return instance;
        },

        getNumber() {
            return number;
        },
    };

    return instance;
}

let a = gMath(10).scatter(40).getNumber()
console.log(a);


Progressbar in Python i wish to improve my Progressbar in Python

from __future__ import division
import sys
import time

class Progress(object):
    def __init__(self, maxval):
        self._seen = 0.0
        self._pct = 0
        self.maxval = maxval

    def update(self, value):
        self._seen = value
        pct = int((self._seen / self.maxval) * 100.0)
        if self._pct != pct:
            sys.stderr.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n')
            sys.stdout.flush()
        self._pct = pct

    def start(self):
        pct = int((0.0 / self.maxval) * 100.0)
        sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n')
        sys.stdout.flush()

    def finish(self):
        pct = int((self.maxval / self.maxval) * 100.0)
        sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n')
        sys.stdout.flush()

toolbar_width = 300
pbar = Progress(toolbar_width)
pbar.start()
for i in xrange(toolbar_width):
    time.sleep(0.1) # do real work here
    pbar.update(i)
pbar.finish()

As per my comments, I've not sure SE.CodeReview is the right place to get the help you are looking for.

However, as I didn't read your question properly at first, I had a look at your code and changed a few things (please note that it's not exactly the same behavior as it used to be):

extract the display logic in a method on its own
reuse update in start and finish (little changes here : this method now updates the object instead of just doing some display)
removed self._seen because it didn't seem useful

Here the code :

class Progress(object):
    def __init__(self, maxval):
        self._pct = 0
        self.maxval = maxval

    def update(self, value):
        pct = int((value / self.maxval) * 100.0)
        if self._pct != pct:
            self._pct = pct
            self.display()

    def start(self):
        self.update(0)

    def finish(self):
        self.update(self.maxval)

    def display(self):
        sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*self._pct, self._pct) + '\n')
        sys.stdout.flush()


Python code to split csv into smaller csvs, not splitting IDs I have Python code that splits a given large csv into smaller csvs. This large CSV has an ID column (column 1), which consecutive entries in the csv can share. The large csv might look something like this:

sfsddf8sdf8, 123, -234, dfsdfe, fsefsddfe
sfsddf8sdf8, 754,  464, sdfgdg, QFdgdfgdr
sfsddf8sdf8, 485,  469, mgyhjd, brgfgrdfg
sfsddf8sdf8, 274, -234, dnthfh, jyfhghfth
sfsddf8sdf8, 954, -145, lihgyb, fthgfhthj
powedfnsk93, 257, -139, sdfsfs, sdfsdfsdf
powedfnsk93, 284, -126, sdgdgr, sdagssdff
powedfnsk93, 257, -139, srfgfr, sdffffsss
erfsfeeeeef, 978,  677, dfgdrg, ssdttnmmm
etc...

The IDs are not sorted alphabetically in the input file, but consecutive identical IDs are grouped together.

My code does not split the IDs into different csvs, ensuring that each id appears in only one output csv.

My code is:

import pandas as pd
import os

def iterateIDs(file): #create chunks based on tripID
    csv_reader = pd.read_csv(file, iterator=True, chunksize=1, header=None)
    first_chunk = csv_reader.get_chunk()
    id = first_chunk.iloc[0,0]
    chunk = pd.DataFrame(first_chunk)
    for l in csv_reader:
        if id == l.iloc[0,0] or len(chunk)<1000000: #Keep adding to chunk if less than 1,000,000, or in middle of trip
            id = l.iloc[0,0]
            chunk = chunk.append(l)
            continue
        id = l.iloc[0,0]
        yield chunk
        chunk = pd.DataFrame(l)
    yield chunk

waypoint_filesize = os.stat('TripRecordsReportWaypoints.csv').st_size #checks filesize

if waypoint_filesize > 100000000: #if file too big, split into seperate chunks
    chunk_count = 1
    chunk_Iterate = iterateIDs("TripRecordsReportWaypoints.csv")

    for chunk in chunk_Iterate:
        chunk.to_csv('SmallWaypoints_{}.csv'.format(chunk_count),header=None,index=None)
        chunk_count = chunk_count+1

However, this code runs very slowly. I tested it on a small file, 284 MB and 3.5 million rows, however it took over an hour to run. Is there any way I can achieve this result quicker? I don't mind if it's outside of python.

If I understand correctly, you want to split a file into smaller files, based on size (no more than 1000000 lines) and ID (no ID should be split among files).

If that's the case, I think you're over-complicating things. You don't need pandas and you definitely don't need to keep all data in memory.

You just need two counters, one for the amount of lines you've written and one for the index of the file to write.

Sample code (of course, replace file names with what you need, or move the check after the write to start from 0 instead of 1):

current_id = ''
index = 0
written_lines = 0
max_lines = 1000000

with open('data.csv', 'r') as input_file:
    for line in input_file:
        values = line.split(',')
        if (current_id != values[0]) or (written_lines > max_lines):
            index += 1
            current_id = values[0]
        with open('output_{:08d}.csv'.format(index), 'a') as output_file:
            output_file.write(line)
            written_lines += 1

EDIT: This works assuming the file is sorted or that at least the IDs are grouped together as you said in the comment.


I want to get weekdays for common time sets from the following hashmap I have the following HashMap :

  HashMap<String, String> days = new HashMap<String, String>(){
        days.put("MON", "9-5");
        days.put("TUE", "9-4");
        days.put("WED", "9-5");
        days.put("THU", "9-5");
        days.put("FR", "9-5");
        days.put("SAT", "Closed");
        days.put("SUN", "Closed");
};

I want to display following output :

  MON-WED-THU-FRI : 9-5,
  TUE: 9-4,
  SAT-SUN : Closed

NOTE:The value of hashmap("9-5") may change depending upon the inputs from the admin panel.

I have done the below code but it's too lengthy:

    private void days() {

         String timing1 = null;
         String timing2 = null;
         String timing3 = null;
         String timing4 = null;
         String timing5 = null;
         String timing6 = null;
         String timing7 = null;

         ArrayList<String> time1 =new ArrayList<>();
         ArrayList<String> time2 =new ArrayList<>();
         ArrayList<String> time3 =new ArrayList<>();
         ArrayList<String> time4 =new ArrayList<>();
         ArrayList<String> time5 =new ArrayList<>();
         ArrayList<String> time6 =new ArrayList<>();
         ArrayList<String> time7 =new ArrayList<>();

         //iterating over the hash map and taking value ie time storing in respected variable

        for (Map.Entry<String, String> entry : days.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println("key" + key + "Val" + value.toString());

            if (timing1 ==null || timing1.equals(value.toString())){
                timing1 = value.toString();
                continue;
            }

            if (timing2 ==null || timing2.equals(value.toString())){
                timing2 = value.toString();
                continue;
            }

            if (timing3 ==null || timing3.equals(value.toString())){
                timing3 = value.toString();
                continue;
            }

            if (timing4 ==null || timing4.equals(value.toString())){
                timing4 = value.toString();
                continue;
            }

            if (timing5 ==null || timing5.equals(value.toString())){
                timing5 = value.toString();
                continue;
            }

            if (timing6 ==null || timing6.equals(value.toString())){
                timing6 = value.toString();
                continue;
            }

            if (timing7 ==null || timing7.equals(value.toString())){
                timing7 = value.toString();

            }

        }

         //based on value from hash-map appending the key ie. days name(eg. MON) to the respected array-list

        for (Map.Entry<String, String> entry : days.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (timing1!=null && timing1.equals(value.toString())){

                time1.add(key);
                continue;
            }

            if (timing2!=null && timing2.equals(value.toString())){

                time2.add(key);
                continue;
            }

            if (timing3!=null && timing3.equals(value.toString())){

                time3.add(key);
                continue;
            }

            if (timing4!=null && timing4.equals(value.toString())){

                time4.add(key);
                continue;
            }

            if (timing5!=null && timing5.equals(value.toString())){

                time5.add(key);
                continue;
            }

            if (timing6!=null && timing6.equals(value.toString())){

                time6.add(key);
                continue;
            }

            if (timing7!=null && timing7.equals(value.toString())){

                time7.add(key);
               // continue;
            }

        }

The thing you need to do is commonly called "grouping", i.e. you iterate over a given dataset, take one property (the time in your case) and collect the entries with the same property in a useful structure.

Fortunately, java (8+) already can do this for you by streaming through the map entries and grouping them all automagically:

    Map<String, List<Map.Entry<String, String>>> grouped = days.entrySet().stream()
        .collect(Collectors.groupingBy(Map.Entry::getValue));

OK, the data-structure looks a little wierd here, because your list consists of map-entries, but this was the main work. If you print this result, you already get (format added manually):

{
     9-4=[TUE=9-4],
     9-5=[MON=9-5, WED=9-5, THU=9-5, FRI=9-5],
     Closed=[SAT=Closed, SUN=Closed]
}

... which is exactly what you need from a data perspective. Using a further iteration over this map which uses the time as a key and the old map's entries as values to format the respective output should be quite trivial.

BTW: to keep the order of the days, you should use a LinkedHashMap instead of a HashMap.


Linq IEnumerable extensions for void functions I found myself wanting to use Linq to map void methods to an IEnumerable to modify all items. The existing Linq methods require a return variable when mapping, since they are based on Func.

So I decided to try my hand at creating some extension methods myself. This is the first time I've done anything like this, so if there are any pitfalls I'm missing, please do tell.

I created two extensions, one which applies a foreach loop to all elements, calling an Action<T> for each. The second one is basically the Zip extension, which allows for two IEnumerables to be iterated together and again maps a Action<T1,T2> to both of them.

public static void ForEachAction<T>(this IEnumerable<T> sequence, Action<T> action) {
  foreach(T value in sequence) {
    action(value);
  }
}

public static void ForEachActionZip<Tbase, Tsecond>(this IEnumerable<Tbase> sequence, IEnumerable<Tsecond> second, Action<Tbase, Tsecond> action) {
  sequence.Zip(second, (first, other) => new { first, other }).ForEachAction(x => action(x.first, x.other));
}

You can then use this like so:

someList.ForEachAction(x => x.Update());

or

someList.ForEachActionZip(secondList, (a, b) => a.Update(b));

This is generally considered to be a bad idea. IEnumerable has deferred execution, which means that in your example, someList can be forced to enumerate any desired number of times.

As a consequence, it depends on the implementation behind the IEnumerable whether any changes applied by action will still be visible after your methods have run. There are two possibilities:

someList is a materialized list (for example, List<SomeObject>). After running ForEachAction, a new enumeration of someList will produce the same, modified, objects.
someList is an enumerable that produces new objects on each execution. After running ForEachAction, a new enumeration of someList will produce new objects. The changed objects are out of scope and will soon be garbage collected.

An example of the second option is an IQueryable against a SQL backend. When it is executed it will emit a SQL query that returns new objects from the database (caching as applied by many ORMs aside).

In that case it totally depends on what happens in action whether any effect of it is persistent. If action only modifies objects in someList its effect will be lost. If it uses objects in someList to change some external state (e.g. increment some sum value) its effect will persist.

As a conclusion, I wouldn't do this. If you want to apply void methods to any IEnumerable, first materialize it to a list and then apply existing methods. Instead of...

someList.ForEachAction(x => x.Update());

...you'd have...

var concreteList = someList.ToList();
concreteList.ForEach(x => x.Update());

Now continue working with concreteList so you'll be sure that the effect of x.Update() will remain visible in your code.


Extend sums and products functions Exercise 2.57.  Extend the
  differentiation program to handle sums
  and products of arbitrary numbers of
  (two or more) terms. Then the last
  example above could be expressed as

  (deriv '(* x y (+ x 3)) 'x)

  Try to do this by changing only the
  representation for sums and products,
  without changing the deriv procedure
  at all. For example, the addend of a
  sum would be the first term, and the
  augend would be the sum of the rest of
  the terms.

I wrote the following solution.

(define (deriv exp var)
  (cond ((number? exp) 0)
        ((variable? exp)
         (if (same-variable? exp var) 1 0))
        ((sum? exp)
         (make-sum (deriv (addend exp) var)
                   (deriv (augend exp) var)))
        ((product? exp)
         (make-sum
          (make-product (multiplier exp)
                        (deriv (multiplicand exp) var))
          (make-product (deriv (multiplier exp) var)
                        (multiplicand exp))))
        ((exponentiation? exp)
         (make-product (exponent exp)
                       (make-exponentiation (base exp) (- (exponent exp) 1))))
        (else
         (error "unknown expression type -- DERIV" exp))))

(define (variable? x) (symbol? x))

(define (same-variable? v1 v2)
  (and (variable? v1) (variable? v2) (eq? v1 v2)))

(define (make-sum . a)
  (define (iter sum rest)
    (cond ((null? rest) (if (zero? sum) '() (list sum)))
          ((=number? (car rest) 0) (iter sum (cdr rest)))
          ((number? (car rest)) (iter (+ sum (car rest)) (cdr rest)))
          (else (cons (car rest) (iter sum (cdr rest))))))
  (let ((result (iter 0 a)))
    (if (= (length result) 1)
        (car result)
        (cons '+ result))))

(define (=number? exp num)
  (and (number? exp) (= exp num)))

(define (make-product . a)
  (define (iter product rest)
    (cond ((null? rest) (if (= 1 product) '() (list product)))
          ((=number? (car rest) 1) (iter product
                                         (cdr rest)))
          ((number? (car rest)) (iter (* product (car rest))
                                      (cdr rest)))
          (else
           (let ((result (iter product (cdr rest))))
             (if (and (pair? result) (eq? (car result) 0))
                 (list 0)
                 (cons (car rest) result))))))
  (let ((result (iter 1 a)))
    (if (= (length result) 1)
        (car result)
        (cons '* result))))

(define (sum? x)
  (and (pair? x) (eq? (car x) '+)))

(define (addend s) (cadr s))

(define (augend s) (if (> (length s) 3)
                       (cons '+ (cddr s))
                       (caddr s)))

(define (product? x)
  (and (pair? x) (eq? (car x) '*)))

(define (multiplier p) (cadr p))

(define (multiplicand p) (if (> (length p) 3)
                             (cons '* (cddr p))
                             (caddr p)))

(define (exponentiation? x)
  (and (pair? x) (eq? (car x) '**)))
(define (base s) (cadr s))
(define (exponent s) (caddr s))
(define (make-exponentiation m1 m2)
  (cond ((=number? m2 0) 1)
        ((= m2 1) m1)
        (else (list '** m1 m2))))

Can it be improved?  In particular, look closely at make-product and make-sum.

Your have the right ideas for implementing make-sum and make-product.  You may improve upon them in the following ways, in my opinion.

Within the two functions, you employ an inner function iter to partition numeric and non-numeric terms.  Traditionally, one uses the name iter to represent an iterative function; your definition, however, is most certainly recursive.  To make it truly iterative, one may use two accumulators--one for the sum of all numeric terms and the other for the rest of the terms.  Then one may return the cons of the two accumulators when the iteration terminates.

One may allow make-sum (and similarly make-product) to handle other sum-type objects in its terms list as well--simply test with sum?, then append its terms.

Finally, there are several cases that must be handled when iteration terminates: rest may be empty or it may contain one or more items; sum-numbers may be zero or non-zero.

Here's an implementation (naming scheme is slightly different from yours--in the iter function, terms is the list of remaining terms to be iterated upon, sum-numbers is the sum of all numeric terms seen so far, rest is a list of all non-numeric terms seen so far):

(define (make-sum . terms)
  (define (iter terms sum-numbers rest)
    (cond
      ((null? terms) (cons sum-numbers rest))
      ((=number? (car terms) 0) (iter (cdr terms) sum-numbers rest))
      ((number? (car terms)) (iter (cdr terms) (+ sum-numbers (car terms)) rest))
      ((sum? (car terms)) (iter (append (cdar terms) (cdr terms)) sum-numbers rest))
      (else (iter (cdr terms) sum-numbers (cons (car terms) rest)))))
  (let*
      ((result (iter terms 0 null))
       (sum-numbers (car result))
       (rest (cdr result)))
    (if (null? rest)
        sum-numbers
        (if (zero? sum-numbers)
            (if (null? (cdr rest))
                (car rest)
                (cons '+ rest))
            (cons '+ (cons sum-numbers rest))))))

(define (make-product . terms)
  (define (iter terms sum-numbers rest)
    (cond
      ((null? terms) (cons sum-numbers rest))
      ((=number? (car terms) 0) (cons 0 null))
      ((=number? (car terms) 1) (iter (cdr terms) sum-numbers rest))
      ((number? (car terms)) (iter (cdr terms) (* sum-numbers (car terms)) rest))
      ((product? (car terms)) (iter (append (cdar terms) (cdr terms)) sum-numbers rest))
      (else (iter (cdr terms) sum-numbers (cons (car terms) rest)))))
  (let*
      ((result (iter terms 1 null))
       (sum-numbers (car result))
       (rest (cdr result)))
    (if (null? rest)
        sum-numbers
        (if (zero? sum-numbers)
            (if (null? (cdr rest))
                (car rest)
                (cons '* rest))
            (cons '* (cons sum-numbers rest))))))

One may also simplify the definitions of augend and multiplicand by using make-sum and make-product respectively:

(define (augend s) (apply make-sum (cddr s)))

(define (multiplicand p) (apply make-product (cddr p)))

Note the similarities between make-sum and make-product.  It may be possible to factor out some code.  One may also use library functions such as partition (if available) to simplify the code.


Core Data code for manually creating a lot of entries from old ones Does this looks ok to everyone?

NSFetchRequest *oldFetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *oldEntryEntity = [NSEntityDescription entityForName:@"Entry"
                                                  inManagedObjectContext:oldContext];

[oldFetchRequest setEntity:oldEntryEntity];

int numberOfEntries = [oldContext countForFetchRequest:oldFetchRequest error:nil];

int batchSize = 10;
[oldFetchRequest setFetchBatchSize:10];
int offset = 0;

while (numberOfEntries - offset > 0) {

    [oldFetchRequest setFetchOffset:offset];
    NSError *error;
    NSArray *entries = [oldContext executeFetchRequest:oldFetchRequest error:&error];

    for (NSManagedObject *entry in entries) {
        Entry *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry"
                                                        inManagedObjectContext:newContext];

        [newEntry setupCreationDate:[entry valueForKey:@"creationDate"] withSave:NO];
        newEntry.entryID = [entry valueForKey:@"entryID"];

        NSMutableOrderedSet *newMediaSet = [[NSMutableOrderedSet alloc] init];

        NSOrderedSet *mediaSet = [entry valueForKey:@"media"];

        int i = 0;

        for (NSManagedObject *media in mediaSet) {

            Media *newMedia = [NSEntityDescription insertNewObjectForEntityForName:@"Media"
                                                            inManagedObjectContext:newContext];

            newMedia.positionInEntry = [NSNumber numberWithDouble:i + 1]; //Potentially needs changing
            newMedia.mediaID = [Entry generateString];

            MediaImageData *imageData = [NSEntityDescription insertNewObjectForEntityForName:@"MediaImageData"
                                                                      inManagedObjectContext:newContext];

            if ([newMedia.type isEqualToString:@"Image"]) {
                imageData.data = [media valueForKey:@"originalImage"];;
            }
            else if ([newMedia.type isEqualToString:@"Movie"]) {
                NSURL *movieURL = [NSURL URLWithString:newMedia.movie];
                MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
                [moviePlayer stop];
                UIImage *screenshot = [moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
                [moviePlayer stop];

                imageData.data = UIImageJPEGRepresentation(screenshot, 1.0);
            }

            newMedia.imageData = imageData;

            newMedia.entry = newEntry;
            [newMediaSet addObject:newMedia];

            i++;
        }

        newEntry.media = newMediaSet;

    }

    [newContext save:&error];

    offset = offset + batchSize;
}

The first big problem I see with this code is here:

int i = 0;

for (NSManagedObject *media in mediaSet) {
    // stuff
    newMedia.positionInEntry = [NSNumber numberWithDouble:i + 1];
    // more stuff
    i++;
}

First of all, if positionInEntry is a property intended to hold some sort of index or something for your Media class, then it should be of the same type that collections tend to use for their indexing: NSUInteger.  Although... the object itself probably doesn't need to know what position it is in the array, and as this could change, it's probably best to just not have this property at all.

Next, i is defined as an int, and 1 is an int literal, so we're creating the NSNumber in the wrong way.  We should be doing this (if we're going to continue to keep this positionInEntry property):

newMedia.positionInEntry = [NSNumber numberWithInt:i + 1];

Finally, we really shouldn't be doing this in this manner at all.  If we want to know what index we're working with, we should use a traditional for loop.

for (int i = 0; i < [mediaSet count]; ++i) {
    NSManagedObject *media = mediaSet[i];
    // stuff
    newMedia.positionInEntry = @(i+1);
    // more stuff
}

However, there's a slightly better option.

It is good to use a forin loop where we can, because this actually is faster than a traditional for loop in Objective-C.  We still don't want to rely on i however, for a couple of reasons, right now, I'll say, the most important of which is readability.  But there is this option:

for (NSManagedObject *media in mediaSet) {
    // stuff

    NSUInteger index = [mediaSet indexOfObject:media];

    newMedia.positionInEntry = @(index + 1);

    // more stuff
}

We can call indexOfObject: on an NSArray and it will return the first index it finds that object at.  As a note, this method returns NSNotFound if the object isn't found in the array, but in a forin loop, this should hopefully never be the case.


Two sprite-drawing functions for Amara game Ideally I would have one draw method in the parent class (Player).

But I can't figure out how to do this. I don't know if there is anyway to decouple it totally. I don't mind modifying the sprite sheet so that it can handle this sort of thing.

Any tips are very welcome!!

Both classes inherit from Player.

var skeleton =  Player(x, y, hp, name, moveSpeed);
//drawing the fly

var draw = function(ctx) {

if (flyAnimate >= 30){
  flyAnimate = 0;
}
var bugX = canvas.width/2 + fly.getDrawAtX() - localX - 50;

if (fly.getAlive()){
  ctx.fillStyle="#FF0000";
  ctx.fillRect(bugX+30,fly.getDrawAtY()-50,((fly.getHp()/2.2)),6);
} else {
  ctx.fillText("DEAD", bugX + 37, fly.getDrawAtY()-40);
}

if (flyAnimate <= 10){
  ctx.drawImage(flySprite,0,0, 100, 100, bugX,fly.getDrawAtY()-50, 100, 100);
}

else if (flyAnimate <= 20){
  ctx.drawImage(flySprite,100,0, 100, 100, bugX,fly.getDrawAtY()-50, 100, 100);
}
else if (flyAnimate <= 30){
  ctx.drawImage(flySprite,200,0, 100, 100, bugX,fly.getDrawAtY()-50, 100, 100);
}
ctx.drawImage(silverShield, bugX+ 20, fly.getDrawAtY()-3);

if (descendAttack || rightMouseActionHappening){
  if (!rightMouseActionHappening){
    rightMouseActionHappening = true;
  }
  //200 is pretty badass
}

if (descendAttack) {
  ctx.save();
  ctx.translate(bugX+60, fly.getDrawAtY()-40 + 90);
  ctx.rotate(Math.PI);
  ctx.drawImage(silverSword, 0, -10);
  ctx.restore();
} else {
  ctx.drawImage(silverSword, bugX+ 60, fly.getDrawAtY()-40);
}
flyAnimate++;

ctx.fillStyle = "black";
ctx.font = "bold 13px sans-serif";
ctx.fillText(name, bugX + 22, fly.getDrawAtY()-60);
};

// drawing what I call a redhatter

var draw = function(ctx) {
//var drawAtX = skeleton.getX()-50;
if (skeleton.getMoveDirection() === "left"){
  facing_left = true;
} else if (skeleton.getMoveDirection() === "right"){
  facing_left = false;
}
if (facing_left){
  spritesheet_offset_y = 102;
}
else {
  spritesheet_offset_y = 0;
}
var   drawAtX = canvas.width/2 + skeleton.getDrawAtX() - localX - 50;

if (skeleton.getAlive()){
  ctx.fillStyle="#FF0000";
  ctx.fillRect(drawAtX+30,skeleton.getY()-50,((skeleton.getHp()/2.2)),6);
  ctx.fillStyle = "black";
} else { /* If it's dead, just write DEAD */
  ctx.fillText("DEAD", drawAtX + 37, skeleton.getY()-40);
}
ctx.fillStyle = "black";
ctx.font = "bold 13px sans-serif";
ctx.fillText(name, drawAtX + 25, skeleton.getY()-60);

/* Decides what sprite to draw*/
if (skeleton.getAnimate() <= 20){
  ctx.drawImage(RedhatterSprite,0,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
}
else if (skeleton.getAnimate() <= 40){
  ctx.drawImage(RedhatterSprite,100,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
}
else if (skeleton.getAnimate() <= 60){
  ctx.drawImage(RedhatterSprite,200,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
} else{
  ctx.drawImage(RedhatterSprite,200,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
}
};

Here is the full source on GitHub.

I stopped reading through the code when I got to this:

if (descendAttack || rightMouseActionHappening){
  if (!rightMouseActionHappening){
    rightMouseActionHappening = true;
  }
  //200 is pretty badass
}

First, that comment means nothing to the code, get rid of it.

Second thing is that the inside operation will never get called when rightMouseActionHappening is true,  I am not sure how this is supposed to work, if you try something like

if (true) {
    if (false){
        console.log("true");
    }
}

you won't get an answer from it, so what I mean is that you should write this a little more like this

if (descendAttack && !rightMouseActionHappening){
    rightMouseActionHappening = true;
}

because the inner if isn't going to be called if rightMouseActionHappening is true, so don't test for that.

once we have gone this far, if rightMouseActionHappening is true, reassigning it to true isn't going to hurt it at all, so we might as well drop it off.

if (descendAttack){
    rightMouseActionHappening = true;
}

Now, the next statement is another if checking descendAttack again, so we might just want to merge these together like this

if (descendAttack) {
  rightMouseActionHappening = true;
  ctx.save();
  ctx.translate(bugX+60, fly.getDrawAtY()-40 + 90);
  ctx.rotate(Math.PI);
  ctx.drawImage(silverSword, 0, -10);
  ctx.restore();
} else {
  ctx.drawImage(silverSword, bugX+ 60, fly.getDrawAtY()-40);
}

all of your code could use another indentation inside of the functions, so that I know that it is inside of a function.

if (skeleton.getMoveDirection() === "left"){
  facing_left = true;
} else if (skeleton.getMoveDirection() === "right"){
  facing_left = false;
}

I would change this into a simple assignment like this

facing_left = skeleton.getMoveDirection() === "left"

and this

if (facing_left){
  spritesheet_offset_y = 102;
} else {
  spritesheet_offset_y = 0;
}

I would change into a ternary assignment statement like this

spritesheet_offset_y = facing_left ? 102 : 0;


A simple key-shift cipher Encryption is all the rage nowadays but let us not forget what it was like back before the advent of internet. I have written a small, simple cipher that takes texts, gets their char value, and adds or subtracts a certian given number from them aka "shifting" the keys.

If the receiving end has the direction and then number of the shift, he or she can easily decrypt the code. It's not a real cipher, and nothing important at all. Just something I've written as practice:

 """ This is a simple alphabetical shift encypter. Enter -1 or 1 for the direction, your desired shift and laslty, the
    text to cipher.
    Written by Sami Dena (aurlit@riseup.net)
"""

def cipher(direction, shift, text):
    text_split = list(text)

    text_split = [ord(i) for i in text_split]

    text_shift = [str(i + (direction * shift)) for i in text_split]

    return str.join(',', text_shift)

def decipher(direction, shift, text):
    text_split = str.split(text, ',')

    text_shift = [chr(int(i) - (direction * shift)) for i in text_split]

    return str.join('', text_shift)

if __name__ == '__main__':
    string = "The encryption step performed by a Caesar cipher is often" \
             " incorporated as part of more complex schemes, such as the Vigenère cipher" \
             ", and still has modern application in the ROT13 system. As with all single-alphabet" \
             " substitution ciphers, the Caesar cipher is easily broken and in modern practice offers " \
             "essentially no communication security."

    encrypted_string = cipher(-1, 4, string)
    print(encrypted_string)
    print(decipher(-1, 4, encrypted_string))

Thanks a lot for your reviews.

You know what comprehensions are, which is good!
But you've a couple of problems:

str.join(',', text_shift) is abnormal and should probably be ','.join(text_shift).
str.split(text, ',') is equally abnormal and should be changed to text.split(',').
text_split = list(text) is unneeded, as you can loop thought the string the exact same way.
text_split = [ord(i) for i in text_split] can be merged into text_shifts comprehension.
You can change both cipher and decipher to be one-liners.

I'd also change both direction * shift to be a variable, just to ease reading of the comprehension slightly.

And so you should be able to end up with functions that look like:

def cipher(direction, shift, text):
    order = direction * shift
    return ','.join([str(ord(i) + order) for i in text])

def decipher(direction, shift, text):
    order = direction * shift
    return ''.join([chr(int(i) - order) for i in text.split(',')])

Finally, your module level doc-string should have a short description on the first line, and then optionally have two spaces and a longer description.

You used implicit string concatenation, but you kept using \ at the end of the line.
Instead I'd change you string to be wrapped in () to remove these.

I also disliked that you added your whitespace characters to the front of the next string.
It looks odd, and is easier to read/ignore when it's on the other line.

And so in all I'd end up with:

"""
Simple alphabetical cipher

This is a simple alphabetical shift encypter. Enter -1 or 1 for the direction,
your desired shift and laslty, the text to cipher.
   Written by Sami Dena (aurlit@riseup.net)
"""

def cipher(direction, shift, text):
    order = direction * shift
    return ','.join([str(ord(i) + order) for i in text])

def decipher(direction, shift, text):
    order = direction * shift
    return ''.join([chr(int(i) - order) for i in text.split(',')])

if __name__ == '__main__':
   string = ("The encryption step performed by a Caesar cipher is often "
             "incorporated as part of more complex schemes, such as the Vigenère cipher, "
             "and still has modern application in the ROT13 system. As with all single-alphabet "
             "substitution ciphers, the Caesar cipher is easily broken and in modern practice offers "
             "essentially no communication security.")

   encrypted_string = cipher(-1, 4, string)
   print(encrypted_string)
   print(decipher(-1, 4, encrypted_string))


Stripping specified character Here's some code that removes the specified character, ch, from the string passed in. Is there a better way to do this? Specifically, one that's more efficient and/or portable?

//returns string without any 'ch' characters in it, if any.
#include <string>
using namespace std;
string strip(string str, const char ch)
{
        size_t p = 0; //position of any 'ch'

        while ((p = str.find(ch, p)) != string::npos)
                str.erase(p, 1);

        return str;
}

I'm not entirely sure how the performance will compare, but the standard way to accomplish this would be the erase-remove idiom:

str.erase(std::remove(str.begin(). str.end(), ch), str.end());

Unless the performance proves to be a bottleneck, it's typically better to stick with the C++ style of doing things.  I can't imagine that this would be significantly less efficient than the other method.  (In fact, I wouldn't be surprised if this is a bit faster for long strings with a high amount of the removed character -- though my assumption of that depends on quite a few non-guaranteed implementation choices, and a rather rough estimation of the cost of different low level operations.)


Create unique string from id to build an link shortening system I want to build my own link shortening system. Therefore I need a way to create unique strings from the record ids stored in my database table.
So far I came up with this. I wonder if you now a faster or better idea? Or are there any caveats to my method?
// generate unique alphanumeric string from id with map
function idToString($id) {
    $map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; # 62 characters (a-z;A-Z;0-9)
    $string='';
    if ($id<62) return $map[$id]; // return immediately
    while ($id>0) {
        if ($id%62>=0) {
            $string=$string.$map[$id%62];
            $id=intval($id/62);
        }
    }
    $string=strrev($string);     // Reverse string to emulate human reading
    return $string;
}

// get integer ID back from a String
function stringToID($string) {
    $map = str_split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); # same map as above of course
    $string=strrev($string);
    $string_array=str_split($string);
    $id=0;
    foreach ($string_array as $k=>$c) {
        $id=$id+(array_keys($map, $c)[0])*pow(62, $k);
    }
    return $id;
}

echo idToString(247698); // bcBi
echo stringToID('bcBi'); // 247698

I played with your code for a while, declared constants for your functions to use so that the static values didn't need to be regenerated with each call, added spacing around operators, curly braces for condition blocks, simplified expressions, reduced the total number of function calls, and generally made things more direct.
One point of concern is that you are using arithmetic to translate the values -- for this reason you will need to be wary of the upper limit for your system.  It would be a good idea to throw an exception when your calculation breaks the int max limit.  Also, scientific notation can monkey wrench things too.  I used number_format() to prevent scientific notation while I was testing -- I don't know how much extra mileage this will grant you.  This has been a fun rabbit hole to go down.
define('ALNUM_MAP', str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'));
define('DIGIT_MAP', array_flip(ALNUM_MAP));

function idToString($id) {
    if ($id < 62) {
        return ALNUM_MAP[$id];
    }
    $string = '';
    while ($id) {
        $id = number_format($id, 0, '', '');
        $string = ALNUM_MAP[$id % 62] . $string;
        $id = (int)($id / 62);
    }
    return $string;
}

function stringToID($string) {
    $id = 0;
    for ($i = strlen($string) - 1, $pow = 0; $i >= 0; --$i, ++$pow) {
        $id += DIGIT_MAP[$string[$i]] * (62 ** $pow);
    }
    return number_format($id, 0, '', '');
}

echo idToString(247698); // bcBi
echo "\n---\n";
echo stringToID('bcBi'); // 247698
echo "\n---\n";
//echo idToString(32611315596050636800); // M1ckM4ckUS4
//echo "\n---\n";
//echo stringToID('M1ckM4ckUS4'); // 32611315596050636800
//echo "\n---\n";
echo idToString(8483692923010050); // M1ckM4ckU
echo "\n---\n";
echo stringToID('M1ckM4ckU'); // 8483692923010050

That said, since you are starting with fully numeric values and you want to reduce their character count by converting to an alphanumeric string, then I have a far simpler way based on this answer that I post on Stack Overflow a couple years back.  (Be sure that the incoming values are string-type, not integer-type.)
Code: (Demo)
define('ALNUM_MAP', str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'));
define('DIGIT_MAP', array_flip(ALNUM_MAP));

function numToAlnum($num) {
    return strtr($num, ALNUM_MAP);
}

function alnumToNum($alphaNum) {
    return strtr($alphaNum, DIGIT_MAP);
}

$ids = ['4440', '464426', '43304441302845', '262018191701180', '273381111186152545352'];
foreach ($ids as $id) {
    $idLength = strlen($id);
    $alphaNum = numToAlnum($id);
    $alNumLength = strlen($alphaNum);
    $backToId = alnumToNum($alphaNum);
    var_export(['original' => $id, 'encoded' => $alphaNum, 'decoded' => $backToId, 'reduction' => $idLength - $alNumLength]);
    echo "\n---\n";
}

As stated in my SO post, using strtr() is a fantastic technique because it is designed to translate the longest substring that it can find as it traverses the input string.  This translation operates on a different algorithm, so it will not give exactly the same length reduction as your technique, but it will not suffer from any numeric/math-based side-effects either.


Basic structure for interactive single window application This is the basic structure I usually end up with whenever I'm writing a simple application. More recently I've learned about singletons and have started to incorporate them into my design, but other that that I haven't changed much about it in recent times.

I've been wondering if there is anything in here that I could improve on or that is considered bad practice.

Main

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
            e.printStackTrace();
        }

        Controller.getInstance();
    }
}

Controller

import javax.swing.*;

public class Controller {
    private static Controller instance;

    private static final int FPS = 30;
    public static final int WIDTH = 600;
    public static final int HEIGHT = 800;

    private final JFrame frame;

    private Timer timer;

    public static Controller getInstance() {
        return instance != null ? instance : (instance = new Controller());
    }

    private Controller() {
        //Do setup
        frame = new AppFrame();

        timer = new Timer(1000/FPS, e -> update());
        timer.start();
    }

    private void update() {
        //Update model
        frame.repaint();
    }
}

AppFrame

import javax.swing.*;

public class AppFrame extends JFrame {
    public AppFrame() {
        super("My Example App");
        setResizable(false);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(new AppPanel());

        //Do more setup if applicable

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

AppPanel

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

public class AppPanel extends JPanel {
    private final Dimension DIMENSION = new Dimension(Controller.WIDTH, Controller.HEIGHT);

    @Override
    public Dimension getPreferredSize() {
        return DIMENSION;
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        //Draw things on g2
    }
}

The code looks decent enough.  I'd like to point out three issues, though, all related to timing/multi-threading.

GUI → EDT

All GUI operations should happen on the Event Dispatch Thread.  Java boots into the Main thread, which is different from the EDT.  Your Controller.getInstance() should be called on the EDT:

EventQueue.invokeLater(Controller::getInstance)

Controller.instance should be guarded

Currently, the instance if filled in via the Main thread.  If the GUI (on the EDT or through the timer) later requests the instance, there is no guarantee they will see it, or they might see it in an inconsistent/incomplete state.

This can be solved by either making instance volatile or, perhaps better, making getInstance() a synchronized method.

repaint() is on a best-effort basis

It looks like this is the basis for a game or other graphically heavy application (judging from FPS).  Swing (and its timers) may not give you the timing guarantees you'd need for things like game logic.

Consider using a game loop with a Canvas and a BufferStrategy, disabling redraw requests, and taking over from there.

Isn't the Timer good enough?  I'm tempted to say, yes, it might be good enough, if the game logic is simple and not intense.  Though you're no longer blocking the EDT with Thread.sleep (big win), the actions that the timer calls are still executed on the EDT.  This makes handling GUI elements and fields much simpler (no sync needed), but heavier stuff may result in jitter.  Worse: heavy stuff on the EDT may make your game loop jitter.

In short: the timer is simpler and probably good enough.  The game loop in a separate thread (say, your main thread) is more heavyweight but also more reliable and more likely to benefit from hardware acceleration.

Nitpicking

Controller.getInstance seems like an odd method to call from main to kick things off.  Maybe make it Controller.run() or Controller.getInstance().run() or some such that would better imply the side effect of running your program.
getPreferredSize returns a mutable final variable (Dimension is mutable).  Perhaps you could try this:

public Dimension getPreferredSize() {
    return isPreferredSizeSet() ? super.getPreferredSize() : new Dimension(DIMENSION);
}


Keep reading Command-line until you get the word END I have to write a code which takes (integers) numbers from Command-line and keeps reading the terminal until it gets a word END

So I wrote the following; I feel its really bad. Is there any way I can improve below code

I updated my code from previously to below

func main() {
    buf := bufio.NewReader(os.Stdin)
    lines, err := buf.ReadBytes('\n')

    if err != nil {
        return
    }

    fmt.Printf(" %q \n", string(lines))
    line := strings.Replace(string(lines), "\n", "", -1)

    numbers := strings.Split(line, " ")
    fmt.Printf("numbers %q ", numbers)
    var sum int64
    for _, num := range numbers {
        num, err := strconv.ParseInt(num, 10, 0)
        if err != nil {
            fmt.Println(err)
            break
        }
        sum += num
    }
    fmt.Println("Sum of all numbers :", sum)

}

takes (integers) numbers from Command-line and keeps reading the
  terminal until it gets a word END.

For example,

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    sum := int64(0)
    s := bufio.NewScanner(os.Stdin)
    s.Split(bufio.ScanWords)
    for s.Scan() {
        word := s.Text()
        num, err := strconv.ParseInt(word, 10, 64)
        if err != nil {
            if strings.ToUpper(word) == "END" {
                break
            }
            fmt.Fprintln(os.Stderr, err)
            continue
        }
        sum += num
    }
    if err := s.Err(); err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    fmt.Println("Sum of all numbers:", sum)
}

Terminal:

12 24
36
6
6
  END
Sum of all numbers: 84


Q/A trivia quiz query This project is based on trivia (question/answer quiz). The scenario is simple but I have to improve/optimize my query using these tables:

$query=$this->db->query("SELECT
q.`id`,
q.`topic_id`,
t.`topic`,
q.`question`,
GROUP_CONCAT(a.`answer`) AS `answer`,
GROUP_CONCAT(a.`is_correct`) AS `is_correct`,
GROUP_CONCAT(a.`id`) AS `ans_id`,
q.`answer_type`,
q.`image_url`,
q.`created_date`,
(SELECT ua.`topic_id` FROM usersAnswer ua
WHERE t.`id`= ua.topic_id AND ua.`user_id` = '".$user_id."' LIMIT 1)
AS `userdone_topic`,
(SELECT ua.`answer_id`
FROM usersAnswer ua
WHERE ua.`question_id` = q.`id` AND ua.`user_id`='".$user_id."'
AND ua.`answer_id`
IN
(SELECT a.`id` FROM answers a
WHERE a.`is_correct` != '0' AND a.question_id = q.`id`
)) AS `user_correct_id`
FROM
questions q INNER JOIN topics t ON q.`topic_id`= t.`id`
INNER JOIN answers a ON q.`id`=a.`question_id`
WHERE
(SELECT s.`status`
FROM `status` s
WHERE
s.`month_date`= q.created_date AND s.`status`= 2
$valid)
GROUP BY q.`id`
");
return $query->result();

well I used the MS sql for reference but that should be a bit batter. I would also reccomend you to structure your sql cos that way you get a better overview of things.
Carefull the below seelect is not grouped you can group it as a subquery again

SELECT q.id, q.topic_id, q.question, a.answer, a.is_correct, a.id as ans_id,
    q.answer_type, q.image_url, q.created_date, uaAll.topic_id as userdone_topic,
    uaCorrect.answer_id as user_correct_id
FROM questions q
    inner join topics t on q.topic_id = t.id
    inner join answers a on q.id = a.question_id
    inner join status s on q.created_date = s.month_date
    left outer join
    (
        SELECT top 1 ua.topic_id
        FROM UserAnswers ua
        where ua.userid = ''
    ) as uaAll on t.id = uaAll.topic_id
    left outer join (
        select ua.answer_id,ua.question_id
        FROM UserAnswers ua
            inner join answers a on a.id = ua.answer_id
        where ua.userid = ''
            and a.is_correct <> 0
    ) as uaCorrect on q.id = uaCorrect.question_id AND a.id = uaCorrect.answer_id
WHERE s.status = 2


Multi-threading upload tool We have about 14G files and each is about 150k.

I'm writing a script to upload them to Azure Blob storage and would like to run an upload() function (each with own file to upload) in 5 threads.

Here is how I realized it and it looks like it works - but I still have doubts about how correct this code is.

...
class Loader:

    def __init__(self):

        self.account = 'accname'
        #self.container = 'userdata'
        self.container = 'bar1'
        key = 'DQ4***A=='

        self.base_url = 'http://' + self.account + '.blob.core.windows.net'
        self.blob = BlobService(account_name=self.account, account_key=key)

    def uploader(self, filepath, userfile, locker):

        print 'Uploading file: {}'.format(userfile)

        self.blob.put_block_blob_from_path(self.container,
                                           userfile,
                                           filepath,
                                           max_connections=1,
                                           max_retries=5,
                                           retry_wait=1.0)

        locker.release()

    def upload(self, path):

        print('Upload files from {} to {}'.format(path, self.base_url))

        locker = threading.BoundedSemaphore(5)

        for root, dirs, files in os.walk(path):
            print root
            for userfile in files:
                #print 'Uploading {}'.format(os.path.join(root, userfile))
                locker.acquire()
                t = threading.Thread(target=self.uploader, args=(os.path.join(root, userfile), userfile, locker))
                t.start()
...

And script in action:

$ ./storage_upload.py -u --path /tmp/bartest/
Upload files from /tmp/bartest/ to http://accname.blob.core.windows.net
/tmp/bartest/
Uploading file: 15.txt
Uploading file: 12.txt
Uploading file: 7.txt
Uploading file: 13.txt
Uploading file: 19.txt

Looks okay if a bit sloppy with different formatting for some print x
vs. print(x) calls (the latter being preferred really); you probably
should also use
new-style classes,
i.e. class Loader(object):.

Other than that the main concern I'd have is that the semaphore should
be protected against exceptions.  This is mostly a concern for bigger
scripts, but it's a good habit regardless.  Thus, the release method
should be called regardless of whether an exception was raised by
anything else in the thread - otherwise the program could just get stuck
there, which is fine for a one-off script probably.

You should probably also check whether the threading actually does
improve the throughput, considering Pythons global interpreter lock.


Simple Contains() Function I wrote simple generic function to check if any STL container has an element. It seems work fine. I have tested it with VC++, GCC and Clang compilers. It works perfectly.

How can I improve it further.

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

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

// Based on std::conditional
template <bool B, typename T, typename F>
struct conditional_impl
{
    constexpr static F pick(T&& , F&& f)
    {
        return std::forward<F>(f);
    }
};

template <typename T, typename F>
struct conditional_impl<true, T, F>
{
    constexpr static T pick(T&& t, F&&)
    {
        return std::forward<T>(t);
    }
};

template <bool B, typename T, typename F>
auto conditional(T&& t, F&& f)
{
    return conditional_impl<B,T,F>::pick(std::forward<T>(t), std::forward<F>(f));
}

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

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

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

    return op(container, key);
}

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

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

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

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

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

Nice toy! Took me a while to wrap my head around it. It looks ok. The only thing I was thinking about is why not to use std::enable_if as it is much simpler.

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

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

template <typename C, typename T>
typename std::enable_if<has_find<C>::value, bool>::type contains(const C& container, const T& key) {
    return c.end() != c.find(k);
}

template <typename C, typename T>
typename std::enable_if<!has_find<C>::value, bool>::type contains(const C& container, const T& key) {
    return c.end() != std::find(c.begin(), c.end(), k);
}

int main()
{
    /* */
}


Reusable Ajax object I've been working on a new project and I've found myself needing to make multiple Ajax calls, often on the same page and at the same time. I decided rather than repeating code that I would try and make a reusable object that to handle these calls.

I'm very new to Object Orientated JavaScript so I'm looking for some feedback and advice on my code; am I doing it right? is there something I'm not doing? should I be doing things differently etc?

Here's my Ajax constructor:

/**
 *
 * AjaxRequest Constructor
 *
 * @param url
 * @param success_callback
 * @param limit
 * @param type
 * @constructor
 */

function AjaxRequest (url, success_callback, limit, type) {
    this.url = url;
    this.success_callback = success_callback;
    this.limit =  limit || 3;
    this.type = type || "POST";

    //init ajax
    this.init();
}

/**
 * initialise
 * ajax
 */

AjaxRequest.prototype.init = function () {

    var _self = this;

    $.ajax({
        dataType: "json",
        url: this.url,
        type: this.type,
        data: {
            member_id: 1,
            limit: this.limit
        },
        beforeSend : function (){
            console.log('loading');
            //spinner.spin(target);
        },
        success: function (response) {
            if (response.success === 1) {
                _self.success_callback(response);
            }
        },
        error: function (a, b, c) {

        }
    });
}

/**
 * change number of
 * displayed outputs
 * @param limit
 */

AjaxRequest.prototype.set_limit = function (limit) {
    this.limit = limit;
    this.init();
}

and here is how I'm calling it

/**
 * instantiate getAchievements
 * @type {AjaxRequest}
 */

getAchievements = new AjaxRequest("/ajax-member/get-achievements", function (response) {

    var i,
        container = document.getElementsByClassName('achievements-container')[0],
        achievements_data = '';

    for (i in response.achievements) {
        achievements_data += ("

" + response.achievements[i].t_achievement_name + "
" + response.achievements[i].t_achievement_description + "

");
    }

    container.innerHTML = achievements_data;
});

/**
 * instantiate getComments
 * @type {AjaxRequest}
 */

getComments = new AjaxRequest("/ajax-member/get-comments", function (response) {

    var i,
        container = document.getElementsByClassName('comments')[0],
        comments_data = '';

    for (i in response.comments) {
        comments_data += ("

" + response.comments[i].t_fname + " " + response.comments[i].t_lname + "
" + response.comments[i].t_comment_content + "

");
    }

    container.innerHTML = comments_data;
});

It would be good to hear some feedback on this.  I'm always looking to improve and find the best ways of doing things so if you spot something I should be doing differently then please shout.

From a quick once over:

JsHint.com has very little feedback, good!
Consider using use strict to activate strict mode
Avoid console.log
Both beforeSend , error and complete should be customizable by the caller
success() returns ( PlainObject data, String textStatus, jqXHR jqXHR ) you should pass all 3 to success_callback
JavaScript is lowerCamelCase, success_callback -> successCallback
member_id: 1, <- Maybe this is sample code, this magic constant deserves a comment
I wonder if AjaxRequest should know about "/ajax-member/, from a DRY perspective
for (i in response.achievements) {, response.achievements seems to be an array, please use a regular for loop to iterate over arrays, it will prevent hard to find bugs at a later stage
Find a good templating library, you need it, consider Handlebars
I think your Ajax class could be expanded, getAchievements and getComments are clearly a result of copy pasting code


Simple Java mergeSort implementation public class MergeSortImplementation {

    public static int[] merge(int[] arrayA, int[] arrayB) {
        int n = arrayA.length + arrayB.length;

        int[] mergedArray = new int[n];

        int x = 0;
        int y = 0;
        int a = 0;
        int b = 0;

        for (int i = 0; i < mergedArray.length; i++) {

            // Check if arrayA is out of bounds.
            if (x < arrayA.length) {
                a = arrayA[x];
            } else {
                b = arrayB[y];
                mergedArray[i] = b;
                y++;
                continue;
            }

            // Check if arrayB is out of bounds.
            if (y < arrayB.length) {
                b = arrayB[y];
            } else {
                a = arrayA[x];
                mergedArray[i] = a;
                x++;
                continue;
            }

            if (a == b) {
                mergedArray[i] = a;
                i++;
                x++;
                mergedArray[i] = b;
                y++;
            } else if (a < b) {
                mergedArray[i] = a;
                x++;
            } else if (b < a) {
                mergedArray[i] = b;
                y++;
            }
        }

        return mergedArray;
    }

    public static int[] mergeSort(int[] inputArr) {

        int n = inputArr.length;

        // Base Case: Array's length is less than 1
        if (n <= 1) {
            return inputArr;
        }

        // Creating two arrays to store values
        int[] arrayA = new int[n / 2];
        int[] arrayB = new int[n - (n / 2)];

        // Creating resulting array
        int[] outputArr = new int[n];

        // Initializing arrayA
        for (int i = 0; i < arrayA.length; i++) {
            arrayA[i] = inputArr[i];
        }

        // Initializing arrayB
        for (int i = 0; i < arrayB.length; i++) {
            arrayB[i] = inputArr[i + (n / 2)];
        }

        // Divide array into 2 halves
        arrayA = mergeSort(arrayA);
        arrayB = mergeSort(arrayB);
        outputArr = merge(arrayA, arrayB);

        return outputArr;
    }

    public static void main(String[] args) {

        int[] intArr = {49, 23, 59, 23, 49, 32};

        int[] sortedArray = mergeSort(intArr);

        for (int e : sortedArray) {
            System.out.print(e + " ");
        }
    }
}

It looks very different from others. This is because I am creating an extra array and returning another. Other than memory/space inefficiency can someone tell me what could be better with the way I'm implementing MergeSort? Or why this coding style is not acceptable?

The merge method

The implementation of merge is difficult to understand.

Naming is one problem. a, b, x, y are hard to distinguish. Was a the value and x the index of the first array? Or the other way around? It's easy to get lost.
Another issue with naming is that arrayA and arrayB differ by one letter. It's recommended to avoid using similar variable names, as the human eye may overlook too minor differences. first and second would be unmistakable.
A loop with a long body, multiple continue statements, and multiple incremented variables, is generally hard to read. It's all too easy to get lost in this code.

A simpler, almost naive implementation of the same thing:

private static int[] merge(int[] first, int[] second) {
    int[] merged = new int[first.length + second.length];

    int firstIndex = 0;
    int secondIndex = 0;
    int index = 0;

    while (firstIndex < first.length && secondIndex < second.length) {
        if (first[firstIndex] < second[secondIndex]) {
            merged[index++] = first[firstIndex++];
        } else {
            merged[index++] = second[secondIndex++];
        }
    }

    while (firstIndex < first.length) {
        merged[index++] = first[firstIndex++];
    }

    while (secondIndex < second.length) {
        merged[index++] = second[secondIndex++];
    }

    return merged;
}

Note that I also changed the visibility to private. This method is an implementation detail of your sorting algorithm, no need to expose it.

The mergeSort method

It's recommended to minimize the live time of variables: the number of lines between declaration and last use. In other words, declare variables right before they are needed, not sooner.

In mergeSort, look at outputArr:

    // Creating resulting array
    int[] outputArr = new int[n];

    // Initializing arrayA
    for (int i = 0; i < arrayA.length; i++) {
        arrayA[i] = inputArr[i];
    }

    // Initializing arrayB
    for (int i = 0; i < arrayB.length; i++) {
        arrayB[i] = inputArr[i + (n / 2)];
    }

    // Divide array into 2 halves
    arrayA = mergeSort(arrayA);
    arrayB = mergeSort(arrayB);
    outputArr = merge(arrayA, arrayB);

    return outputArr;

It's not used until much later in the method. Notice what happens when you delay the declaration as much as possible:

    // Creating resulting array
    int[] outputArr = new int[n];
    outputArr = merge(arrayA, arrayB);

    return outputArr;

Do you see a problem? A new array is allocated in new int[n], only to be thrown away. Such mistakes become visible when you delay the declaration as much as possible. The above can be reduced to:

    return merge(arrayA, arrayB);

Memory/space inefficiency

You asked for comments "other than this". That's not a good idea. Usually there's a good reason why obvious problems should be avoided.

A merge sort can be implemented with essentially the same algorithm, but without creating the half-arrays. You will still need an extra array to perform the merge step. But the number of arrays created will be reduced drastically.

The JDK has Arrays.sort and Collections.sort utility methods for sorting arrays and collections, respectively. Both operate in-place. Usually it's good to follow example practices of the JDK. If you don't want to destroy the original array/collection, you can create a simple wrapper that copies the original collection, sort the copy and return a copy.


Ruby array search, returning either a result with a good score or the last result I have an array of hashes, each of which has two attributes: "title" and "Zscore". I want to return either the result of find or the last element. This can be done with:

a = array.select{|i| i["title"] == "some title"}
b = a.find{|i| i["Zscore"].to_f >= 5} || a.last

Is there an elegant way to put the conditional inside the block, something like the following?

array.select{|i| i["title"] == "some title"}.find{|i| i["Zscore"].to_f >= 5 || last}

Any built-in method? Any ideas of one-liner that is nicer than the following?

array.select{|i| i["title"] == "some title"}.find{|i| i["Zscore"].to_f >= 5} ||
array.select{|i| i["title"] == "some title"}.last

You can always define your own custom method to refactor your code in the Array class:

class Array
  def find_or_last(&block)
    find(&block) || last
  end
end

And use it like this:

array.select { |i| i['title'] == 'some title' }.find_or_last { |i| i['Zscore'].to_f >= 5 }

You can also use procs or lambdas to achieve this.


Buffered RNG-wrapper using openmp in c++ I wrote a class around a UniformRandomBitGenerator, which in turn also satisfies the concept of a UniformRandomBitGenerator. It uses a buffer and parallelism (openmp) to quickly generate large amounts of random numbers.

I'm happy about all kinds of feedback, but I'm most unsure about my use of openmp and ensuring that the same seed always generates the same sequence of pseudo-random numbers.

Here's the class:

#pragma once
#include <random>
#include <vector>
#include <omp.h>

template<class RNG_type>
class BP_RNG {
public:

    using unsigned_t = unsigned;
    using result_type = typename RNG_type::result_type;
    constexpr static result_type min() { return RNG_type::min(); };
    constexpr static result_type max() { return RNG_type::max(); };

    BP_RNG(int seed = 42, unsigned_t buffer_size = 1e8, unsigned_t nthreads = 4);

    result_type operator()();
private:
    using buffer_t = std::vector<result_type>;
    using iter_t = typename std::vector<result_type>::iterator;

    void refill();

    RNG_type engine_;
    buffer_t buffer_;
    iter_t position_;
    const unsigned_t nthreads_;
};

template<class RNG_type>
BP_RNG<RNG_type>::BP_RNG(int seed, unsigned_t buffer_size, unsigned_t nthreads):
    engine_(seed),
    buffer_(buffer_size),
    position_(buffer_.begin()),
    nthreads_(nthreads)
{
    refill();
}

template<class RNG_type>
void BP_RNG<RNG_type>::refill()
{
    // Get seeds for RNGs in parallel section beforehand to ensure determinism
    buffer_t seedvals(nthreads_);
    for (auto& seed : seedvals) seed = engine_();

    #pragma omp parallel num_threads(nthreads_)
    {
    RNG_type local_engine( seedvals[omp_get_thread_num()] );
    #pragma omp for
    // Pedestrian vector-iteration so that omp works
    for (unsigned_t i = 0; i < buffer_.size(); ++i) buffer_[i] = local_engine();
    }

    position_ = buffer_.begin();
}

template<class RNG_type>
typename BP_RNG<RNG_type>::result_type BP_RNG<RNG_type>::operator()()
{
    if (position_ == buffer_.end()) refill();
    return *(position_++);
}

And the main.cpp I used to test it:

#include <iostream>
#include <chrono>

#include "buffered_parallel_rng.hpp"

template<class RNG>
void time_rng(RNG& eng, unsigned long iter, std::string name)
{
    typename RNG::result_type a;

    auto start = std::chrono::high_resolution_clock::now();
    for (unsigned long i = 0; i < iter; ++i)
    {
        a = eng();
    }
    auto stop = std::chrono::high_resolution_clock::now();
    double elapsed = static_cast<std::chrono::duration<double> >(stop-start).count();

    std::cout << name << " : " << elapsed << "\n";
}

void test_determinism(unsigned ntests)
{
    BP_RNG<std::mt19937_64> seeder(42);
    for (unsigned j = 0; j < ntests; ++j)
    {
        int seed = seeder();
        BP_RNG<std::mt19937_64> myeng1(seed),myeng2(seed);

        for (unsigned i = 0; i < 10; ++i)
        {
            if (myeng1() != myeng2()) {
                std::cout << "Different results from same seed!\n"
                    << "Seed is: " << seed << "\n";
                return;
            }
        }
    }
}

int main() {
    unsigned iter = 1e9;
    std::mt19937_64 ref_eng;
    ref_eng.seed(100);
    BP_RNG<std::mt19937_64> my_eng(100);

    time_rng(ref_eng, iter, "Other");
    time_rng(my_eng , iter, "Mine ");
    test_determinism(100);
}

There are a few (relatively minor) things here that can be improved on:

Order your includes. Specifically, group your includes by their source (i.e. current project headers, STL headers, library headers...). Most commonly, the following order is used:

Header file the current source file implements (i.e. a.h for a file called a.cpp) if any
Headers from the same project you're working on
Headers from different projects/libraries (in your case, omp.h, for example)
Headers from the standard library

This, on one hand, serves the purposes of checking whether each header file actually contains all required includes (say, for example, your header actually used something from chrono; with your current include order, your compiler would not complain because you include chrono in main.cpp before buffered_parallel_rng.hpp, thus hiding the missing include), on the other hand helps readers of you source code to verify includes quickly.
using unsigned_t = unsigned; Quite frankly, I don't see the reason you do this here. Why not just use unsigned?

Anyhow, if you really want to have this (and also have a good reason to), I would expect a similar using for int here because of consistency. Alternatively, one could argue that you should be taking an SizeType and a SeedType as template parameters, especially since the result_types and thus the seed types of random number generators in the standard library are different for different generators (for example, std::mt19937_64 uses std::uint_fast64_t whereas std::minstd_rand0 uses std::uint_fast32_t).
Instead of using iter_t = typename std::vector<result_type>::iterator;, you should write using iter_t = typename buffer_t::iterator; to prevent subtle bugs when changing the type of buffer_t.
The name BP_RNG is not very clear. Although the abbreviation "rng" is quite common, what "bp" means will not be clear to most people on first sight. Since your header is named buffered_parallel_rng.hpp, I would expect your class to have the same name.
time_rng currently takes a std::string as argument by value, but you only ever output it to std::cout, so you should take it by const reference instead.
Don't write "\n" where '\n' would suffice. For example, when writing to std::cout, the former implies a call to std::strlen and an additional indirection while the latter just passes the value directly.
iter is not really a fitting name for the second parameter you pass to time_rng. I was confused the first time I glossed over that function because, for me at least, iter almost exclusively stands for iterator. I would have grasped that parameter's meaning much more quickly if you had actually named it iterations or anything along that line.

All in all, you code is mostly well written. None of the points above constitute a "Act now! Your code is on fire!"-grade problem, only tips that could make your already good code a little better and prevent some subtle, thus nasty bugs.

However, I can't tell whether your approach is really worth anything. You should definitely perform some benchmarks to see if there are any performance improvements compared to a single threaded approach and, if yes, how big they are.

Another thing you should consider is learning to do proper testing. There are a variety of testing frameworks (for example, Google Test) which provide functionality for writing and executing tests effectively. Especially since you are concerned about determinism here, writing and executing tests at a much larger scale should help you verify that your code works correctly.


Template parsing function I am using preg_replace_callback(), and I am concerned that I might have some sort of security risk.  I am hoping to get a review of the below substitute() function.  The purpose of the function is to parse a user provided template with user provided data.  A quick description on how it is used is shown below.

The user posts data to the server, which is saved in a database (escaped for SQL injection of course). Note that the application will limit which array indexes are allowed (i.e. firstname, lastname, and phone only in this example).

$userProvidedString='Hello {?firstname?} {?lastname?}, Our database shows that your phone number is {?phone?}.';

$userProvidedArray=array(
    0 => array('firstname'=>'John','lastname'=>'Doe','phone'=>'(555) 222-1212'),
    1 => array('firstname'=>'Jane','lastname'=>'Doe','phone'=>'(555) 333-1212'),
    2 => array('firstname'=>'Mike','lastname'=>'Moe','phone'=>'(444) 222-1212'),
);

Later the data is pulled from the database, and parsed as follows:

foreach($userProvidedArray AS $contact)
{
    $customMessage=substitute($userProvidedString,$contact);
}

My question relates to the substitute() function.  Specifically, does my use of preg_replace_callback() pose any security issues?  Previously, I was using

$template_new= preg_replace('/\{\?(\w+)\?\}/e', '$contact["$1"]', $userProvidedString);

which uses the /e flag which I assume can be dangerous.

Does that danger still remain? Any other recommendations for it?  I am currently using PHP 5.3.18, but will hopefully upgrade to 5.4 soon.

function substitute($template, $values, $deliminator='{??}') {
    //Replaces occurrences of {?name?} with $values['name] if it exists in $values.  Deliminators can be changed
    $deliminator="\\".implode("\\",str_split($deliminator));
    $half = (int) ( (strlen($deliminator) / 2) );
    $pattern = '/'.substr($deliminator, 0, $half).'(\w+)'.substr($deliminator, $half).'/';
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($values) {
            if (isset($values[$matches[1]])) {
                return $values[$matches[1]];
            }
            return $matches[0];
        },
        $template);
}

Escaping the RegExp

You should never do manual escaping, if an appropriate function exists. For RegExp, this is preg_quote. Another risk is that you'r escaping before splitting, so you might destroy an escaping sequence. Better do

function substitute($template, $values, $delimiter = '{??}')
{
    $half    = (int) ( (strlen($delimiter) / 2) );
    $begin   = preg_quote(substr($delimiter, 0, $half), '/');
    $end     = preg_quote(substr($delimiter, $half), '/');
    $pattern = '/' . $begin . '(\w+)' . $end . '/';

Escaping the Values

The user provided values maust be escaped according to the context, where they are used. In this case it is HTML, so you must suppress unwanted tags, especially scripting tags. You can use strip_tags() or htmlspecialchars() for that purpose. I prefer the latter, because the user's value is not changed.

    return preg_replace_callback(
        $pattern,
        function ($matches) use ($values) {
            if (isset($values[$matches[1]])) {
                return htmlspecialchars($values[$matches[1]]);
            }
            return $matches[0];
        },
        $template);
    }
}

Conclusion

With these two small changes you have done everything to make that function save.


common lisp: nested loop beautification (checkboard texture generator) I've written a small code snippet that generates checkboard texture using cl-opengl.

(defun init-texture (tex)
    (gl:bind-texture :texture-2d tex)
    (gl:tex-parameter :texture-2d :texture-min-filter :nearest)
    (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
    (print *test-texture*)
    (let* ((tex-w 16) (tex-h 16) (pixel-size 4)
        (pixel-data (make-array (* (* tex-w tex-h) pixel-size) :element-type '(unsiged-byte 8) :adjustable nil :initial-element 0)))
    (loop for y from 0 to (- tex-h 1) do
        (let ((line-offset (* (* tex-w pixel-size) y)))
            (loop for x from 0 to (- tex-w 1) do
                (let ((x-offset (+ line-offset (* x pixel-size))) (c (if (oddp (+ x y)) 255 0)))
                    (setf (aref pixel-data x-offset) 255)
                    (setf (aref pixel-data (+ x-offset 1)) c)
                    (setf (aref pixel-data (+ x-offset 2)) c)
                    (setf (aref pixel-data (+ x-offset 3)) 255)))))
    (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))

Problem:
it looks ugly and is unnecessarily verbose, especially (- tex-h 1) and 4 setf in a row.

How can I "beautify"/simplify this?

Program logic:

generate 1d array of (unsigned-byte 8). Array size is tex-w*tex-h*pixel-size, where tex-w is 16, tex-h is 16, pixel-size is 4. 1 pixels. That's 16x16 texture data in rgba format where every pixel takes 4 elements.
Fill array. If (oddp (+ x y)), put white pixel, otherwise put blue pixel.

Not much better:

(defun init-texture (tex &aux (tex-w 16) (tex-h 16) (pixel-size 4))
  (gl:bind-texture :texture-2d tex)
  (gl:tex-parameter :texture-2d :texture-min-filter :nearest)
  (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
  (print *test-texture*)
  (let ((pixel-data (make-array (* tex-w tex-h pixel-size)
                                :element-type '(unsiged-byte 8)
                                :adjustable nil
                                :initial-element 0)))
    (loop for y below tex-h
          for line-offset = (* tex-w pixel-size y)
          do (loop for x below tex-w
                   for x-offset = (+ line-offset (* x pixel-size))
                   for c = (if (oddp (+ x y)) 255 0)
                   do  (setf (aref pixel-data (+ x-offset 0)) 255
                             (aref pixel-data (+ x-offset 1)) c
                             (aref pixel-data (+ x-offset 2)) c
                             (aref pixel-data (+ x-offset 3)) 255)))
    (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))

To get rid of the arefs is not really possible. One way would be to use the function REPLACE:

(replace pixel-data (vector 255 c c 255) :start1 x-offset)

But now it allocates a vector for that. Then one might want to wish that the vector would be allocated on the stack:

(let ((new-data (vector 255 c c 255)))
  (declare (dynamic-extent new-data))
  (replace pixel-data (vector 255 c c 255) :start1 x-offset))

Another way is not to write the arefs, but to hide it behind a macro:

(defmacro vector-put-at ((vector start) &rest data)
  `(progn
     ,@(loop for d in data and i from 0
             collect `(setf (aref ,vector (+ ,start ,i)) ,d))))

The you can write above as:

(defun init-texture (tex &aux (tex-w 16) (tex-h 16) (pixel-size 4))
  (gl:bind-texture :texture-2d tex)
  (gl:tex-parameter :texture-2d :texture-min-filter :nearest)
  (gl:tex-parameter :texture-2d :texture-mag-filter :nearest)
  (print *test-texture*)
  (let ((pixel-data (make-array (* tex-w tex-h pixel-size)
                                :element-type '(unsiged-byte 8)
                                :adjustable nil
                                :initial-element 0)))
    (loop for y below tex-h
          for line-offset = (* tex-w pixel-size y)
          do (loop for x below tex-w
                   for x-offset = (+ line-offset (* x pixel-size))
                   for c = (if (oddp (+ x y)) 255 0)
                   do (vector-put-at (pixel-data x-offset)
                        255 c c 255)
    (gl:tex-image-2d :texture-2d 0 :rgba tex-w tex-h 0 :rgba :unsigned-byte pixel-data)))


Tower of Hanoi simulation I've just implemented a simulation of tower of hanoi in Java. Any suggestions are welcomed. Here's my code:

static class Node{
    int data;
    Node next;

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

static class Stack{
    Node top;
    String stackName;

    public Stack(String name){
        stackName = name;
    }

    public String getStackName(){
        return stackName;
    }

    public void push(int data){
        if(top==null){
            top = new Node(data);
            System.out.println("Created Stack, pushing : " + data);
        }else{
            System.out.println("Pushed : " + data);
            Node someNode = new Node(data);
            someNode.next = top;
            top = someNode;
        }
    }

    public Node pop(){
        if(top==null){
            System.out.println("Error : Stack is empty!");
            return new Node(-1);
        }
        if(top.next==null){
            Node toRet = new Node(top.data);
            System.out.println("Stack " + this.stackName + " will be emptied now");
            top = null;
            return toRet;
        }
        Node temp = top;
        top = top.next;
        System.out.println("Popped : " + temp.data);
        return temp;
    }

    public String getTop(){
        if(top==null){
            return "Stack is empty";
        }
        return String.valueOf(top.data);
    }

    public void pushTo(Stack anotherStack){
        System.out.println("Pushed " + this.top.data + " from " + this.stackName + " to " + anotherStack.stackName);
        Node toPush = this.pop();
        anotherStack.push(toPush.data);
    }

}

public static void tower(int number, Stack stackFrom, Stack stackInter, Stack stackTo){
    if(number == 1){
        stackFrom.pushTo(stackTo);
    }else{
        tower(number-1, stackFrom, stackTo, stackInter);
        stackFrom.pushTo(stackTo);
        tower(number-1, stackInter, stackFrom, stackTo);
    }
}

public static void main(String[] args) {
    Stack myStack = new Stack("A");
    myStack.push(10);
    myStack.push(15);
    myStack.push(20);
    myStack.push(25);
    Stack anotherStack = new Stack("B");
    Stack yetAnotherStack = new Stack("C");
    tower(4, myStack, anotherStack, yetAnotherStack);
}

Use java.util.Deque

Instead of implementing your own stack,
it's better and easier to use the Deque in the JDK.
(Not Stack, as the JavaDoc explains, Deque is recommended.
Thanks @greybeard for the tip!)

Naming

In this game there are discs and towers (or sticks, rods, pegs).
It would be better to call them that way instead of Node and Stack.

tower is a poor name for moving discs.
In general, verbs are best for method names.
In this example move would be natural.

Alternative implementation

With the above suggestions applied,
the implementation becomes:

import java.util.ArrayDeque;
import java.util.Deque;

public class Hanoi {

    private static class Tower {

        private final String name;
        private final Deque<Integer> stack;

        public Tower(String name) {
            this.name = name;
            this.stack = new ArrayDeque<>();
        }

        public void add(int... discs) {
            for (int disc : discs) {
                stack.push(disc);
            }
        }

        public int size() {
            return stack.size();
        }

        public void moveOneDisc(Tower to) {
            System.out.println("Pushed " + this.stack.peek() + " from " + this.name + " to " + to.name);
            to.stack.push(this.stack.pop());
        }

        private void moveDiscs(int count, Tower mid, Tower to) {
            if (count == 1) {
                moveOneDisc(to);
            } else {
                moveDiscs(count - 1, to, mid);
                moveOneDisc(to);
                mid.moveDiscs(count - 1, this, to);
            }
        }
    }

    public static void main(String[] args) {
        Tower from = new Tower("A");
        from.add(10, 15, 20, 25);
        Tower mid = new Tower("B");
        Tower to = new Tower("C");
        from.moveDiscs(from.size(), mid, to);
    }
}

Some other improvements:

Moved the tower method inside the Tower class and renamed to move
Tower.add accepts varargs, for conveniently adding multiple discs
Tower.size to know the number of discs on a tower
The method names of Tower are all in the language of the problem domain, not the implementation (implementation details are well hidden)