texts:
After having spent a month or two trying to learn JavaScript, especially functional programming, async, and closures, I finally get it. But I don't know if I'm writing elegant code... Specifically, I'm not sure if I'm creating too many closures, because I don't entirely grasp when contexts remain and when they're marked for garbage collection.

You can probably tell from the example that I'm using node.js -- basically, this is just a piece of test code that connects to a database, gets 20,000 records asynchronously with individual SELECT queries (I'm just doing some profiling, don't worry), and manipulates the data. At the end, it tells me how long it took and closes the MySQL connection.

In order to get a final timestamp and close the connection, I needed something like the async library to keep track of all the various asynchronous functions that are being spawned. It takes all my queries as an array of functions (using a factory called makeQuery()) and then runs a callback to do the cleanup.

Questions:

Am I creating a huge amount of contexts by creating and returning the function doQuery() which uses the argument id in the makeQuery() function, thereby causing 20,000 contexts to persist until async.parallel() is run?
Is the factory function makeQuery() a good and tidy way to create this array of doQuery() functions? Can you suggest any better way to do it?

var mysql = require('mysql');
var radix64 = require('./lib/radix64');
var async = require('async');

var client = mysql.createClient({user: 'root', password: '12345678'});
client.query('USE nodetest');

var startTime = (new Date()).getTime(); // poor man's profiling
var queries = []; // this will be fed to async.parallel() later

var makeQuery = function makeQuery (id) { // factory function to create the queries
    return function doQuery (cb) {
        client.query('SELECT * FROM urls WHERE id='+id,
            function logResults (e, results, fields) {
                results = results[0];
                results.key = radix64.fromNumber(results.id); // yep, I'm converting the
                                                              // number into base-64 notation
                cb(); // if I wanted to do something useful at the end, I would have
                      // called cb(results) instead, which compiles an array of results
                      // to be accessed by the final callback
            }
        );
    };
};

for (i = 1001; i <= 20000; i ++) { // build the list of tasks to be done in parallel
    queries.push(makeQuery(i));
}

// run those tasks
async.parallel(queries, function finished () { // clean up and get the elapsed time
    console.log('done');
    client.end();
    console.log(((new Date()).getTime() - startTime) / 1000);
});

For those of you unfamiliar with async, it's a userland module built for node.js and the browser. Each function in the array that gets passed to async.parallel() is obliged to take a callback and then run that callback once it's done, in order to let async.parallel() know it's done.


texts: Generating all possible permutations of the string

texts:
This generates all possible permutations of the string.  I am also unable to understand the time complexity of this problem. Can someone please explain the complexity to me?

import java.util.ArrayList;

public class permutations {

    public ArrayList<String> performPermutations(String s){
        ArrayList<String> arrayList = new ArrayList<String>();
        if (s == null) {
            return null;
        }

        else if (s.length() == 0) {
            arrayList.add("");
            return arrayList;
        }

        else {
            for (int i = 0; i < s.length(); i++) {
                ArrayList<String> remaining = performPermutations(s.substring(0, i) + s.substring(i + 1));
                for (int j = 0; j < remaining.size(); j++) {
                    arrayList.add(s.charAt(i) + remaining.get(j));
                }
            }
            return arrayList;
        }
    }

    public static void main(String[] args) {
        permutations p = new permutations();
        ArrayList<String> arr = p.performPermutations("abcde");
            for(int i = 0; i<arr.size();i++) {
                System.out.println(arr.get(i));
            }
        }
    }
}


texts: Looping through JSON object with nested for loops

texts:
I've written a function that loops though all of the accounts, properties, views, and filters - each 'level' requires another for loop. I'm working with the Google Analytics Management API and Google Spreadsheet Script Editor.

Wondering how I could split up all of these loops into their own functions, or any other tips.

I also realize that I could cache the lengths in the loops to add some speed. I was looking around at changing it from for loop to forEach, but didn't see much of a speed improvement.

function _getViewFilterData(inAccountsList) {
  var accountsList = Array.isArray(inAccountsList) ? inAccountsList : accounts.list().getItems();
  var account = {};

  var propertiesList = '';
  var property = {};

  var profilesList = '';
  var profile = {};

  var filtersList = '';
  var filter = {};

  var i, j, k, l;

  var results = {};

  results.data = [];
  results.sheetName = 'viewFilters';
  results.header = [
    'account.name',
    'account.id',
    'property.name',
    'property.id',
    'profile.name',
    'profile.id',
    'filter.name',
    'filter.id'
    ];

  for (i = 0; i < accountsList.length; i++) {
    account.name = accountsList[i].name;
    account.id = accountsList[i].id;

    propertiesList = properties.list(account.id).getItems();

    for (j = 0; j < propertiesList.length; j++) {
      property.name = propertiesList[j].name;
      property.id = propertiesList[j].id;

      profilesList = profiles.list(account.id, property.id).getItems();

      for (k = 0; k < profilesList.length; k++) {
        profile.name = profilesList[k].name;
        profile.id = profilesList[k].id;

        filtersList = viewFilters.list(account.id, property.id, profile.id).getItems();

        for (l = 0; l < filtersList.length; l++) {

          filter.name = filtersList[l].filterRef.name;
          filter.id = filtersList[l].filterRef.id;

          results.data.push([
            account.name,
            account.id,
            property.name,
            property.id,
            profile.name,
            profile.id,
            filter.name,
            filter.id
          ]);
        }
      }
    }
  }

  return results;
}


texts:
I have implemented a stack in Python 3, and it works well. If anything needs to be improved, I would appreciate the criticism.

class Stack:

        def __init__(self):
            self.stack = []

        def isEmpty(self):
            return self.stack == []

        def push(self, data):
            self.stack.append(data)

        def pop(self):
            data = self.stack[-1]
            del self.stack[-1]
            return data

        def peek(self):
            return self.stack[-1]

        def sizeStack(self):
            return len(self.stack)

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.sizeStack())
print("Popped: ", stack.pop())
print("Popped: ", stack.pop())
print(stack.sizeStack())
print("Peek:", stack.peek())
print(stack.sizeStack())


texts: A clone_ptr that does not require T to have a clone method

texts:
Here is my clone pointer template:

#include <functional>
#include <utility>
#include <iostream>

template<typename T>
struct clone_ptr
{
    clone_ptr() : ptr(nullptr), cloner(nullptr) {}
    clone_ptr(clone_ptr&& other) noexcept
        : clone_ptr()
    {
        swap( other );
    }
    clone_ptr(const clone_ptr& other)
    {
        ptr = other.cloner(other.ptr);
        cloner = other.cloner;
    }
    void swap( clone_ptr& other ) noexcept
    {
        using std::swap;
        swap( ptr,    other.ptr    );
        swap( cloner, other.cloner );
    }

    clone_ptr& operator=( const clone_ptr& other )
    {
        clear();
        ptr = other.cloner(other.ptr);
        cloner = other.cloner;
        return *this;
    }
    clone_ptr& operator=( clone_ptr&& other )
    {
        clear();
        swap(other);
        return *this;
    }

    T* operator->() { return ptr; }
    const T* operator->() const { return ptr; }
    T& operator*() { return *ptr; }
    const T& operator*() const { return *ptr; }

    operator bool() const { return ptr; }

    bool operator<(const clone_ptr& other) const
    {
        if(!ptr) return other.ptr;
        if(!other.ptr) return false;
        return (*ptr) < (*other.ptr);
    }
    bool operator==(const clone_ptr& other) const
    {
        if(!ptr) return !other.ptr;
        if(!other.ptr) return false;
        return (*ptr) == (*other.ptr);
    }

    std::ostream& output(std::ostream& os) const { if(ptr) os << *ptr; else os << "<nullptr>"; return os ; }

    template<typename T2=T, typename ...Ts>
    void make( Ts&& ...ts )
    {
        clear();
        ptr = new T2( std::forward<Ts>(ts)... );
        cloner = [](T* p) -> T* { return new T2( * (T2*) p ); };
    }

    void clear() { delete ptr; ptr=nullptr; cloner=nullptr; }

    ~clone_ptr() { clear(); }

private:
    T* ptr;
    std::function<T*(T*)> cloner;
};

template<typename T, typename T2=T, typename ...Ts>
clone_ptr<T> make_cloned( Ts&& ...ts )
{
    clone_ptr<T> p;
    p.template make<T2>( std::forward<Ts>(ts)... );
    return p;
}

template<typename T>
std::ostream& operator<<(std::ostream& os, const clone_ptr<T>& p) { return p.output(os); }

It is primarily intended to preserve polymorphism, esp. when stored in a container. It "forwards" operator< and operator== so containers can be sorted etc. based on the contained object.

Have I missed/forgotten anything?


texts: Need help optimizing & improving this php form script

texts:
I usually program in python/javascript and am very new to php. I would appreciate some advice on how to improve the following form script.

Since this is for a highly trafficked website, I want it to be extremely secure, reliable and optimized.

Feel free to point out minor issues as well.

<?php

// avoid errors when in production
// ini_set("display_errors", "0");
error_reporting(-1);

# get value from array
function get_string($array, $index, $default = '') {
    if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) {
        return get_magic_quotes_gpc() ? stripslashes($value) : $value;
    } else {
        return $default;
    }
}

function test($field) {
    global $errors, $required_error;
    if ($field['value'] == '') {
        if ($field['required']) {
            $required_error = true;
        }
        return;
    }
    elseif ($field['validation'] == 'email' && !filter_var($field['value'], FILTER_VALIDATE_EMAIL)) {
        array_push($errors, $field['value'] . ' is an invalid email address.');
    }
    elseif ($field['validation'] == 'number' && !preg_match('/^[0-9 ]+$/', $field['value'])) {
        array_push($errors, $field['value'] . ' is an invalid number.');
    }
    elseif ($field['validation'] == 'alpha' && !preg_match('/^[a-zA-Z ]+$/', $field['value'])) {
        array_push($errors, $field['value'] . ' contains invalid characters. This field only accepts letters and spaces.');
    }
}

$post = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
$errors = array();
$required_error = false;
$ajax = get_string($post, "request_method") == 'ajax';

# select data that needs validation
$fields = array(
    'fullname' => array(
        'value' => get_string($post, "full-name"),
        'validation' => 'alpha',
        'required' => true,
    ),
    'emailaddress' => array(
        'value' => get_string($post, "email-address"),
        'validation' => 'email',
    ),
    'activites' => array(
        'value' => get_string($post, "activites"),
        'validation' => 'default',
    ),
    'country' => array(
        'value' => get_string($post, "country"),
        'validation' => 'default',
    ),
    'contactpreference' => array(
        'value' => get_string($post, "contact-preference"),
        'validation' => 'default',
    ),
    'message' => array(
        'value' => get_string($post, "message"),
        'validation' => 'alpha',
    ),
);

// test each field
foreach ($fields as $field) {
    test($field);
}

if (count($errors) or $required_error) {
    if ($ajax){
        echo 'FAIL';
        return;
    }

    $template_dict = array(
        'errors' => ''
    );

    if ($required_error == true) {
        $template_dict['errors'] .= "
Please fill out all required fields
";
    }

    foreach ($errors as $error) {
        $template_dict['errors'] .= "
$error
";
    }

    // show errors
    echo $template_dict['errors'];
} else {
    $template_dict = $fields;

    // send mail
    $formcontent = "Full Name: $fullname \nEmail Address: $emailaddress \nActivites: $activites \nCountry: $country \nContact preference: $contactpreference \nMessage: $message \n";
    $formcontent = wordwrap($formcontent, 70, "\n", true);

    $recipient = 'email@address.com'; $subject = "Form Name"; $mailheader = "From: $emailaddress \r\n";

    mail($recipient, $subject, $formcontent, $mailheader);

    if ($ajax) {
        echo 'PASS';
        return;
    }

    echo 'Success';
}
?>


texts:
I was trying to solve a problem concerning the difference of the diagonal sums of a matrix (using C99):

#include<stdio.h>

int main(){
    /*n: is the size of the matrix (squared matrix) and it is Entered by the user*/
    int n,line,row,sum_one=0,sum_two=0,dif;
    scanf("%i",&n);
    int array[n+1][n+1];

    for(line=1;line<=n;line++){
        for(row=1;row<=n;row++){
             scanf("%d",&array[line][row]);
        }
     }

     row = n;
     for(line=n;line>=1;line--){
            sum_one=sum_one+array[line][row];
            row--;
     }
     row = n;
     for(line=1;line<=n;line++){
            sum_two=sum_two+array[line][row];
            row--;
     }
     dif = sum_one-sum_two;
     if(dif<0){
         dif = -dif;
     }
     printf("%d \n",dif);
     return 0;
}

But I get in some testcases "terminated due to time out". Is there an efficient way than this algorithm?


texts:
I've written a function that takes a number and returns a value depending on where that number lies on a pre-defined scale. That's probably a little confusing so I've put the code below and added a JSFiddle (although you might be better off in the dev console).

var getSize = function(number){
        var sizes = {
            100 : 'url_t',
            240 : 'url_s',
            320 : 'url_n',
            500 : 'url_m',
            640 : 'url_z',
            800 : 'url_c',
            1024 : 'url_l',
        },
        result = sizes[100];

    for (var size in sizes){
        if(number < size){
            result = sizes[size];
            break;
        }
        result = sizes[1024];
    }
    return result;
};
getSize(10) // returns url_t
getSize(130) // returns url_s
getSize(2000) // returns url_l
getSize(600) // returns url_z

It works and it's fairly performant, it's just a bit icky. I've tried to come up with a better solution but it just feels ickier. Is there anything I'm missing that would make this a bit nicer? I was playing about with putting the sizes in an array so they're a little more JSON-ish, but then I got lost.


texts:
Can you please check if I've written the code correctly?

The task was:

Calculate the user's month of birth as a a number, where January = 0 through to December = 11.
Take the string entered
Get the substring, being the first three characters
Convert to uppercase
Find the starting location of the three-letter abbreviation in the month abbreviations string, and divide this by 3 (this is not the only way to find the month number, but it allows us to practice searching in a string)

var year = prompt('Enter year of birth as a 4 digit integer');

var month = prompt('Enter the name of the month of birth');

// Chop everything after the first 3 characters and make it uppercase
month = month.substring(0,3).toUpperCase();

// Store your array in months, differently named than the month input
var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
"NOV", "DEC"];

// We then use array.indexOf() to locate it in the array
var pos = months.indexOf(month);
if (pos >= 0) {
// valid month, number is pos
}

var date = prompt('Enter day of birth as an integer');


texts:
I'm developing a WordPress plugin using the singleton pattern with the following requirements:

There should ever exist one instance of the plugin
Another instance of the object should never be instantiated, created, cloned, copied etc in any way.
The singular plugin object and its public methods and vars should be easily accessible and usable in any scope, by anything including other plugins

The last one is a given with singleton pattern, but there is one concern I have:
 - __construct() should run only once, and should never run again. The code inside __construct() should never be reparsed and reprocessed however the singleton is instantiated.

I already tested the code and it seems to work, however the code in __construct() was being reprocessed every time i requested the instance of the object through get_instance() outside the plugin until I added self::$instance = $this; at the top.

I'm wondering whether I am violating the guidelines I listed above and also if it is possible for anyone to violate them through any kind of logic or method that they put into their plugins. Also whether this code will last at least a few PHP versions into the future.

    class particular_plugin {

        private static $instance = null;

        protected function __construct()
        {
            self::$instance = $this;

            // Numerous initialization variables and actions here
            // including calls to functions inside the class

        }

        public static function get_instance()
        {
            if (null === static::$instance) {
                static::$instance = new static();
            }

            return static::$instance;
        }

        private function __clone()
        {

        }

        private function __wakeup()
        {

        }

    }
    // Initializing the plugin here
    $particular_plugin = particular_plugin::get_instance();

    function particular_plugin_get()
    {
        // This function allows any plugin to easily retrieve this plugin object and access its public methods and vars as they exist at any given point in time
        return particular_plugin::get_instance();

    }


texts:
This script is my web crawlerfor small sites. Can you possibly review it for best coding practices?
Code
import bs4 as bs
import urllib.request
from urllib.parse import urlparse,urljoin
import pprint

class Page(object):
    def __init__(self,base_url,url):
        self.url = url
        self.base_url = base_url
    def soup(self):
        sauce = urllib.request.urlopen(self.url).read()
        return (bs.BeautifulSoup(sauce,'lxml'))
    def title(self):
        soup = self.soup()
        return soup.title.string
    def links(self):
        urls = []
        soup = self.soup()
        href = [i.get('href') for i in soup.findAll('a') ]
        links = [i for i in (list(map((lambda url : url if bool(urlparse(url).netloc) == True else urljoin (self.base_url, url)),href))) if i.startswith(self.base_url)]
        return links
    def map_page(self):
        map = {self.url:{'title':self.title(),'links':set(self.links())}}
        return map

def site_map(base_url):
    map_pages = {}
    links_to_map = [base_url]

    def check_and_add(url):
        if url not in map_pages:
            [links_to_map.append(i) for i in Page(base_url,url).links()]
            (map_pages.update(Page(base_url,url).map_page()))
            links_to_map.remove(url)
        else:
            links_to_map.remove(url)

    while links_to_map != []:
        url = links_to_map[0]
        check_and_add(url)

    pprint.pprint(map_pages)


texts:
I am currently refactoring a larger solution where the compiler gave multiple warnings about disposing the used System.Timers.Timer instances. The timers are running in short intervals so I would have to check before I dispose the timer if the elapsed callback is currently active.

Following the implementation with which I want to replace the System.Timers.Timer instances.

public class DisposableSafeTimer : IDisposable
{
    public event ElapsedEventHandler Elapsed;

    private System.Timers.Timer _timer;
    private readonly object _syncObject = new object();
    private volatile bool _isDisposing = false;

    public double Interval
    {
        get { return _timer.Interval; }
        set { _timer.Interval = value; }
    }

    public DisposableSafeTimer()
    {
        _timer = new System.Timers.Timer();
        _timer.Elapsed += _timer_Elapsed;
    }

    public void ExternalStart()
    {
        _timer.Start();
    }

    public void ExternalStop()
    {
        _timer.Stop();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        lock (_syncObject)
        {
            if(_isDisposing)
            {
                return;
            }

            if (disposing)
            {
                _isDisposing = disposing;
                _timer.Stop();
                _timer.Elapsed -= _timer_Elapsed;
                _timer.Dispose();
            }
        }
    }

    private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        lock (_syncObject)
        {
            if (_isDisposing)
            {
                return;
            }

            try
            {
                _timer.Stop();
                Elapsed?.Invoke(sender, e);
            }
            finally
            {
                _timer.Start();
            }
        }
    }
}

The Methods ExternalStart() and ExternalStop() are named with the intention that I get compiler errors wherever the Timer.Start() and Timer.Stop() methods are called. The stops and starts from the classes which use my timer implementation shouldn't care about the cyclic starts and stops of the internal timer.

So far I had no problems with my tests. I just want to make sure that I haven't overlooked something. Suggestions for improvements are welcome.


texts:
I'm writing a Direct2D game in c++ / WinAPI. I need to render things 60 times every a second using fixed time step.

__int64 time_before = 0;
__int64 time_now;
__int64 frequency;
__int64 time_elapsed;
double frameTime;
if (QueryPerformanceFrequency((LARGE_INTEGER*)&frequency)) {
    frameTime = (double)frequency / 60;
    while (true) {
        //process incoming messages here
        QueryPerformanceCounter((LARGE_INTEGER*)&time_now);
        time_elapsed = time_now - time_before;
        if (time_elapsed >= frameTime) {
            //update and render things here:
            time_start = time_before;
        }
    }
}

Are there any problems, or are there any improvements that can be made?


texts:
I have created a method that validates inputs based on a set of rules. If an error is found, it is put into an array which can later on be used to display the errors to the user.

Below is my code:

register.php

<?php
    require_once('core/init.php');

    if(input::inputExists()){
        $validate = new validate();
        $validate->checkInput($_POST, array(
            'username' => array(
                'formatted_name' => 'username',
                'required' => 'true',
                'min' => 4,
                'max' => 25,
                'unique' => 'users'
                ),
            'password' => array(
                'formatted_name' => 'password',
                'required' => 'true',
                'min' => 5
                ),
            'confirm_password' => array(
                'formatted_name' => 'password confirmation',
                'matches' => 'password',
                'required' => 'true'
                )
        ));
        if ($validate->validationPassed()) {
            // Register new member...
        } else {
            // Return Errors....
            print_r($validate->getErrors());
        }
    }

?>

<form method="POST" autocomplete="off">

            Username

        <input type="text" name="username" id="username" />

            Password

        <input type="password" name="password" id="password" />

            Confirm Password

        <input type="password" name="confirm_password" id="confirm_password" />

        <input type="submit" />

</form>

validate.class.php

<?php
class validate {
    private $errors;
    private $passed = 'false';

    // public function __construct(){}

    public function checkInput($data, $items = array()) {
        foreach($items as $item => $rules){
            foreach($rules as $rule => $rule_value){
                if ($rule != 'formatted_name'){
                    if ($rule === 'required' && empty($data[$item])){
                        $this->addError("{$rules['formatted_name']} is required.");
                    }
                    if ($rule === 'min' && strlen($data[$item]) < $rule_value){
                        $this->addError("{$rules['formatted_name']} must be at least {$rule_value} characters long.");
                    }
                    if ($rule === 'max' && strlen($data[$item]) > $rule_value){
                        $this->addError("{$rules['formatted_name']} can be a maximum of {$rule_value} characters long.");
                    }
                    if ($rule === 'matches' && $data[$item] != $rule_value){
                        $this->addError("{$rules['formatted_name']} does not match {$items[$rule_value]['formatted_name']}");
                    }
                }
            }

        }
    }

    private function addError($error){
        $this->errors[] = $error;
    }

    public function validationPassed(){
        return empty($this->errors);
    }

    public function getErrors(){
        return $this->errors;
    }
}

Any improvements, suggestions or advice you can give me?


texts:
I am trying to extract data from meshgrid output where zCs is 1000 x 1000 matrix of z values which is produced from meshgrid of s using bin2mat. s is a struct which has x, y, z data. res is 1000.

Based on the threshold I am trying to extract logical which is then used to extract data from s whose z values are between the thresholds.

This code is working but very slow as shown on the screenshot.

xi = linspace(min(s.X),max(s.X),res);
yi = linspace(min(s.Y),max(s.Y),res);

[~,~, iBins] = histcounts(s.X,xi);
[~,~, jBins] = histcounts(s.Y,yi);

n_pts = length(s.X);

in1 = zCs > 0.0030 & zCs < 0.1500;
Ind = find(in1(:));

[nrows ncols] = size(in1);

I = rem(Ind-1,nrows)+1;
J = (Ind-I)/nrows + 1;

%
%
% [I,J] = ind2sub(size(in1), Ind);
N_true = length(I);

hwb = waitbar(0,'Please wait...');

in = false(n_pts,1);
  for k = 1:N_true
      in3 =  iBins == J(k) & jBins == I(k);
      in = in | in3;

      waitbar(k / N_true);

  end
  close(hwb);
  sum(in);

xk = s.X(in);
yk = s.Y(in);
zk = s.Z(in);


texts: Limiting Q promise concurrency in JavaScript

texts:
I wrote a helper to limit Q promise concurrency.
If I have a promise-returning function promiseSomething, writing

promiseSomething = PromiseScheduler.limitConcurrency(promiseSomething, 5);

ensures no more than 5 promises are pending at the same time.

I'm coming to JS from .NET world, and I welcome critique of this code.
It seems to work fine, but I wonder if it can be made shorter / more concise / plain better.

One of the thing worth remembering is that Q always schedules continuations on the next tick.

'use strict';

var q = require('q');

/**
 * Constructs a function that proxies to promiseFactory
 * limiting the count of promises that can run simultaneously.
 * @param promiseFactory function that returns promises.
 * @param limit how many promises are allowed to be running at the same time.
 * @returns function that returns a promise that eventually proxies to promiseFactory.
 */
function limitConcurrency(promiseFactory, limit) {
  var running = 0,
      semaphore;

  function scheduleNextJob() {
    if (running < limit) {
      running++;
      return q();
    }

    if (!semaphore) {
      semaphore = q.defer();
    }

    return semaphore.promise
      .finally(scheduleNextJob);
  }

  function processScheduledJobs() {
    running--;

    if (semaphore && running < limit) {
      semaphore.resolve();
      semaphore = null;
    }
  }

  return function () {
    var _this = this,
        args = arguments;

    function runJob() {
      return promiseFactory.apply(_this, args);
    }

    return scheduleNextJob()
      .then(runJob)
      .finally(processScheduledJobs);
  };
}

module.exports = {
  limitConcurrency: limitConcurrency
};


texts:
I am implementing a very primitive threadpool with C++11 using mutex and conditional variable. The class ThreadPool is the main thread holder and will spawn a number of threads upon construction, and join all threads on destruction. The main thread adds task of type function<void()> into the queue and then wakes up any waiting threads through condition variable.

As a new C++11 learner, is there anything I can improve for the following code (or fix bugs)? For example, making the task function more generic and implementing the lock-free mechanism (best practice?).

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <iostream>
#include <stdexcept>
#include <unistd.h>

// Class: ThreadPool
class ThreadPool {

  // Class: Worker
  class Worker {

    public:

    // Constructor.
    explicit Worker(ThreadPool* master) : _master{master} {};

    // Functor.
    void operator ()() {

      ::std::function<void()> task;

      while(true) {
        { // Acquire lock.
          ::std::unique_lock<::std::mutex> lock(_master->_mutex);

          _master->_condition.wait(
            lock,
            [&] () { return !_master->_tasks.empty() || _master->_terminate.load(); }
          );

          if(_master->_terminate.load()) return;

          task = _master->_tasks.front();
          _master->_tasks.pop_front();
        } // Release lock.

        task();
      }
    }

    private:

    ThreadPool* _master;
  };

  public:

    ThreadPool(size_t);
    template<class F>
    void enqueue(F f);
    ~ThreadPool();

    ThreadPool(const ThreadPool&) = delete;
    ThreadPool& operator = (const ThreadPool&) = delete;

  private:

    friend class Worker;

    ::std::vector< ::std::thread > _workers;
    ::std::deque< ::std::function<void()> > _tasks;
    ::std::mutex _mutex;
    ::std::condition_variable _condition;
    ::std::atomic_bool _terminate {false};
};

// Constructor
ThreadPool::ThreadPool(size_t threads) {
  for(size_t i = 0;i<threads;++i) {
    _workers.push_back(::std::thread(Worker(this)));
  }
}

// Destructor.
ThreadPool::~ThreadPool() {
  _terminate.store(true);
  _condition.notify_all();
  for(auto& t : _workers) t.join();
}

// Procedure: enqueue
template<class F>
void ThreadPool::enqueue(F f) {

  { // Acquire lock
    ::std::unique_lock<::std::mutex> guard(_mutex);
    _tasks.push_back(::std::function<void()>(f));
  } // Release lock

  // wake up one thread
  _condition.notify_one();
}

void foo() {
  printf("hello by %p\n", ::std::this_thread::get_id());
  sleep(1);
}

int main() {

  ThreadPool tp(4);

  while(1) {

    printf("main %p: enque\n", ::std::this_thread::get_id());
    tp.enqueue(foo);
    sleep(1);
  }

  return 0;
}


texts:
I have written a simple landing page in Twitter Bootstrap. It works fine, I just want to know if my code is written in a "good-practice" way.

<!DOCTYPE html>

  <title>SigmaCubes - Home</title>
  <link href="favicon.ico" rel="shortcut icon" />

  <meta charset="utf-8">
  <meta content="IE=edge" http-equiv="X-UA-Compatible">
  <meta name="author" content="Julian Lachniet" />
  <meta name="description" content="Various HTML and JavaScript projects." />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

  <link rel="stylesheet" href="lib/bootstrap.min.css">

        About

        CubeSolver

        Projects

Various HTML and Javascript projects.

SigmaCubes.com is the best website on the internet, and the owner of CubeSolver.

Any suggestions?


texts:
Challenge from Hacker Rank -

Monica wants to buy a keyboard and a USB drive from her favorite electronics store. The store has several models of each. Monica wants to spend as much as possible for the items, given her budget.
Given the price lists for the store's keyboards and USB drives, and Monica's budget, find and print the amount of money Monica will spend. If she doesn't have enough money to both a keyboard and a USB drive, print -1 instead. She will buy only the two required items.

For example - with a budget of 10, two keyboards costing 3,1 & finally three drives available costing 5,2,8, the answer should be 9 as she is only able to purchase the keyboard for 3 and a drive for 5.
I've attempted to solve this logically and with good performance in mind. I'm not sure if I should be happy with my solution. I would appreciate any feedback.
My solution (which works) or my GitHub repo -
using System;
using System.Collections.Generic;
using System.Linq;

namespace ElectronicsShop
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine(GetMoneySpent(new int[] { 3, 1 }, new int[] { 5, 2, 8 }, 10));
            Console.WriteLine(GetMoneySpent(new int[] { 5}, new int[] { 4 }, 5));
            Console.ReadLine();
        }

        static int GetMoneySpent(int[] keyboards, int[] drives, int budget)
        {
            if (budget == 0)
                return -1;

            // sort the two arrays so the highest values are at the front
            keyboards = SortArrayDescending(keyboards);
            drives = SortArrayDescending(drives);

            // delete any that are over our budget
            var affordableKeyboards = GetAffordableItems(keyboards, budget);
            var affordableDrives = GetAffordableItems(drives, budget);

            // make a list to contain the combined totals
            var combinedTotals = new List<int>();

            foreach (var keyboard in keyboards)
            {
                foreach (var drive in drives)
                {
                    combinedTotals.Add(keyboard + drive);
                }
            }

            // sort the list & delete anything over budget
            combinedTotals.Sort();
            combinedTotals.Reverse();
            combinedTotals.RemoveAll(n => n > budget);

            return combinedTotals.Count == 0 ? -1 : combinedTotals[0];
        }

        static int[] SortArrayDescending(int[] array)
        {
            Array.Sort(array);
            Array.Reverse(array);

            return array;
        }

        static int[] GetAffordableItems(int[] array, int budget)
        {
            return array.Where(n => n < budget).ToArray();
        }
    }
}


texts:
I've made a splitString() function which receives a character and a string and returns a vector<string> containing all the string split by a character in the input string:
vector<string> splitString(string input, char separator) {

    size_t pos;
    vector<string> text;

    while (!input.empty()) {

        pos = input.find(separator); //find separator character position

        if (pos == string::npos) {
            text.push_back(input);
            break;
        }
        text.push_back(input.substr(0, pos));

        input = input.substr(pos + 1);
    }
    return text; //returns a vector with all the strings
}

Example Input(.csv):
name;surname;age

Output would be:
vector<string> contains {name, surname, age}

Is there any efficient way of doing this?
As you can see, the ; was deleted separating the strings.
I was wondering if there is any way of adding an option to NOT delete the separator character, including it in the split strings.


texts: Mapping the differences between JavaScript objects

texts:
The reason I want to do this is that the JavaScript objects are created from XML elements and if the element has changed I want to be able to detect that change in the JavaScript objects. So I wrote a function which maps out the differences between the first and second object. Can you improve on this function? (mapObjectDifferences, not the helper functions.)

<html>
<head>
<title>MAP OBJECT DIFFERENCES</title>
<script type="text/javascript">

    function isArray(object) {
        return Object.prototype.toString.apply(object) == "[object Array]";
    }

    function getType(variable) {
        var type = typeof variable;
        if (type == "object")
            if (isArray(variable))
                return "array";
        return type;
    }

    function arrayToObject(array) {
        var object = {};
        for (var i = 0; i < array.length; ++i)
            if (array[i] !== "undefined") object[i] = array[i];
        return object;
    }

    function mapObjectDifferences(outerObject, innerObject) {
        var _mapObjectDifferences = function (outerObject, innerObject, parentMap, parentName) {
            var localMap = {};
            for (var outerProp in outerObject) {
                if (outerObject.hasOwnProperty(outerProp)) {
                    var match = false;
                    var outerPropValue = outerObject[outerProp];
                    var outerType = getType(outerPropValue);
                    var result;
                    for (var innerProp in innerObject) {
                        if (innerObject.hasOwnProperty(innerProp)) {
                            var innerPropValue = innerObject[innerProp];
                            var innerType = getType(innerPropValue);
                            if (outerProp == innerProp && outerType == innerType) {
                                match = true;
                                if (outerType == "array" || outerType == "object") {
                                    if (outerType == "array") {
                                        outerPropValue = arrayToObject(outerPropValue);
                                        innerPropValue = arrayToObject(innerPropValue);
                                    }
                                    _mapObjectDifferences(outerPropValue, innerPropValue, localMap, outerProp);
                                }
                                break;
                            }
                        }
                    }
                    if (match == false) {
                        localMap[outerProp] = outerType;
                        if (parentMap)
                            parentMap[parentName] = localMap;
                    }
                    else if (parentMap) {
                        var difChild = false;
                        for (var prop in localMap)
                            if (localMap.hasOwnProperty(prop)) {
                                difChild = true;
                                break;
                            }
                        if (difChild == true)
                            parentMap[parentName] = localMap;
                    }
                }
            }
            return localMap;
        }
        return _mapObjectDifferences(outerObject, innerObject);
    }

    var o1 = {
        val: "level one",
        val2: 1,
        val3: 3,
        m: {
            s2: "this is level two",
            l1: ["a", "b", "c", 1, {a:"a"}],
            ao: [{ x: "1" }, { y: 1 }, { z: 1}]
        },
        n: {
            n1: { abc: 123 }
        }
    };
    var o2 = {
        val: "level on23e",
        val2: 1,

        m: {
            s3: "this is level two",
             l1: ["a", "b", "c"],
            ao: [{ x: 1 }, { y: 1 }, { z: "3"}]
        },
        n: {
            n1: { abc: "abc" }
        }
    }
    var result = mapObjectDifferences(o1, o2);
    debugger;
</script>
</head>
<body>
</body>
</html>


texts: Deleting most recent files by parsing filename

texts:
I have hundreds of .mp3 files in a single directory of the same naming format, title_YYYY-MM-DD.mp3, with maybe 30 different titles.
Here is an example two different titles:

vision_am_2015-08-04.mp3
vision_am_2015-08-03.mp3
vision_am_2015-07-31.mp3
vision_am_2015-07-30.mp3

lum_pro_2015-08-04.mp3
lum_pro_2015-08-03.mp3
lum_pro_2015-08-01.mp3
lum_pro_2015-07-31.mp3
lum_pro_2015-07-30.mp3
lum_pro_2015-07-29.mp3
lum_pro_2015-07-28.mp3
lum_pro_2015-07-27.mp3

I need to keep X number of most recent files for each title. I figured that since the date format is YYYY-MM-DD, after building a data structure for the files, I can make sure the files are sorted in descending order. Then iterate through them. Then safely delete with confidence each file after the Xth iteration.

Here is my idea:

my $num_to_keep = 2; # or get from @ARGV
$num_to_keep = $num_to_keep - 1;

my $dir = "/home/mp3files";
opendir my $DH, "$dir" or die "$! not open";
my $dateRE = qr/\d{4}-\d{2}-\d{2}/;
my $fileRE = qr/^.+_$dateRE\.mp3$/; # only mp3s
my @files = sort grep {/$fileRE/ && -f "$dir/$_"} readdir($DH);
close $DH;

my %hash = ();
for my $file (reverse @files) {
    my ($fname) = $file =~ m/(.*)?_$dateRE/;
    push(@{ $hash{$fname} }, $file);
}

for my $fname (sort keys %hash) {
    my @files = @{$hash{$fname}};
    print "\n\n\nFILE: $fname<<\n";
    for my $i (0..$#files) {
        if ($i > $num_to_keep) {
            unlink "$dir/$files[$i]";
        }else{
            print "\t\t\t\tI will keep this file $files[$i]\n";
        }
    }
}

This is working as I expected, but since I am using this to delete large numbers of files regularly, I would like an expert take on this. I do not want to accidentally delete wrong files. Plus, I am interested in any general improvements or more elegant solutions.


texts: Zeckendorf Representation of positive integer

texts:
Zeckendorf's theorem states that all positive integers crepresented uniquely as the sum of one or more distinct Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers.

So like given the input 10, the outcome would be [8,2].

This is my working code that was for Reddit's dailyprogrammer challenge:

def fib_list(max_num):
    x=3     #starting at 3 because we have [1,1] in list already.
    list_of_fib = [1,1]
    while x < max_num:
        x = list_of_fib[-1] + list_of_fib[-2]
        list_of_fib.append(x)
    return list_of_fib

def find_num_smaller(num, my_list):
    for value in reversed(my_list):
        if value <= num:
            return value

def solve(num):
    combo_list = []
    list_to_pick_from = fib_list(num)
    while num > 0:
        temp_value = find_num_smaller(num,list_to_pick_from)
        num -= temp_value
        combo_list.append(temp_value)
    print(combo_list)

solve(10)

Running it through timeit.timeit I get about 0.06917929102201015 seconds with the input of 1234. Medium size input of 123456789 yields about 0.22879931901115924 seconds and a large size input of 123456789123456789123456789 yields 1.3149479770218022 seconds. Is there anyway to speed it up? Or make it more acceptable at a "higher standard"  (whatever this means, I guess some would call it 'Pythonic' but I'm not sure the correct term)? Maybe is there some better practice I can employ here.

I have thought of turning Solve() into a generator and just get all the combo values out, but I'm not sure if that's faster.

I know that if I were to run it multiple times, I would check if the input is within the already generated fib_list, and if it isn't I would generate a new one. But that's another question, I just want to see one input.


texts:
Here is my shopping cart class! I want it to be perfect and never to have to implement it.

What improvements would you do?

New : IComparable

interface IComparable
{
    public function equals($object);
}

New : ICartItem

interface ICartItem extends IComparable
{
    public function setQuantity($quantity);
    public function getQuantity();
}

New : ICart

interface ICart
{
    public function add(ICartItem $item);
    public function remove(ICartItem $item);
    public function getQuantity(ICartItem $item);
    public function setQuantity(ICartItem $item, $quantity);
    public function isEmpty();
    public function getItems();
    public function clear();
}

New : Cart

class SessionCart implements ICart
{
    const IDENTIFIER = '_CART_';
    protected $items;

    public function __construct(&$container = null)
    {
        if (is_null($container)) {
            if (session_id() == '') {
                session_start();
            }
            if (!isset($_SESSION[self::IDENTIFIER])) {
                $_SESSION[self::IDENTIFIER] = array();
            }
            $container = & $_SESSION[self::IDENTIFIER];
        }
        $this->items = & $container;
    }

    public function add(ICartItem $item)
    {
        $index = $this->getIndexOfItem($item);

        if ($index == -1) {
            $this->items[] = $item;

        } else {
            $item = $this->items[$index];
            $item->setQuantity($item->getQuantity() + 1);
        }

        return $item->getQuantity();
    }

    public function remove(ICartItem $item)
    {
        $index = $this->getIndexOfItem($item);

        if ($index == -1) {
            throw new Exception('The item isn\'t inside the cart.');
        }

        $item = $this->items[$index];

        $quantity = $item->getQuantity() - 1;

        if ($quantity > 0) {
            $item->setQuantity($quantity);

        } else {
            unset($this->items[$index]);
        }
        return $quantity;
    }

    public function getQuantity(ICartItem $item)
    {
        $index = $this->getIndexOfItem($item);

        if ($index == -1) {
            return 0;

        } else {
            return $this->items[$index]->getQuantity();
        }
    }

    public function setQuantity(ICartItem $item, $quantity)
    {
        if (($quantity = (int)$quantity) < 1) {
            throw new Exception('A positive quantity is required.');
        }

        $index = $this->getIndexOfItem($item);

        if ($index == -1) {
            $item->setQuantity($quantity);
            $this->items[] = $item;

        } else {
            $item = $this->items[$index];
            $item->setQuantity($quantity);
        }

        return $item->getQuantity();
    }

    public function isEmpty()
    {
        return empty($this->items);
    }

    public function getItems()
    {
        return $this->items;
    }

    public function clear()
    {
        $this->items = array();
    }

    private function getIndexOfItem(ICartItem $item)
    {
        foreach ($this->items as $key => $value) {
            if ($item->equals($value)) {
                return $key;
            }
        }
        return -1;
    }
}


texts:
I spent some time today trying to write FizzBuzz in a functional/declarative style. I thought it would be a good chance to get some feedback on it since I've been doing functional programming for about a year now.

(I know there are some similar questions asked here before, but their approach to the code has been different to mine and it would be good to get feedback more specific to my code)

The main things I want to know are:

How consistent is this code with the best practices in functional and declarative programming?
Are there any bad practices in it that I should be aware of?

const isFizz = number => number % 5 === 0
const isBuzz = number => number % 3 === 0

const newArrayInRange = (min, max) => [...Array(max + 1).keys()].slice(min)

const fizzBuzz = (min, max) => newArrayInRange(min, max)
  .map(number => {
    if (isFizz(number) && isBuzz(number)) {
      return 'fizzbuzz'
    }
    if (isFizz(number)) {
      return 'fizz'
    }
    if (isBuzz(number)) {
      return 'buzz'
    }
    return number
  })
  .join('\n')

console.log(fizzBuzz(1, 100))


texts: Haskell game server auth: cookie key generate&check

texts:
C++ code version (description copied from it)

gameKeys id is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls generateId, then gameKeys id and returns it as JSON using encodeJSON to player via API. When a friend establishes connection, he sends the game id and his key, server calls gameKeys id, where id is user data, and then checks user's key.

Algorithm is:

use current time and internal counter to generate id if it's not provided, or use provided id
make fast crypto hash using Blake2 function of id and secret(Yes, I know about HMAC and using as key, but in this case it doesn't matter)
split 64-bit hash to four 16-bit values, one hash for one user
make JSON object from id and keys and return it

I want to make stable code: exploit-free, no memory leaks and high speed (for high load and DDOS prevention). I'm experimenting now, so the algorithm was first written in JavaScript, then in C++ and now in Haskell.

I think Haskell is best in writing stable code.

Please review the Haskell code; I think it can be improved (I'm new to Haskell). Code compiles and works same as JS and C++. Also please advise me, which programming language is better for this: JS, C++ , Haskell or Go?

Here's the Haskell code; install dependencies cabal install blake2 hex split unix-time json to run it:

{-# LANGUAGE DeriveDataTypeable #-}
import Data.IORef
import System.IO.Unsafe
import qualified Crypto.Hash.BLAKE2.BLAKE2b as Blake2
import qualified Data.ByteString.Char8 as Char8
import Data.Hex
import Data.Char
import Data.List.Split
import Data.UnixTime
import Text.JSON.Generic

topsecret = "TOPSECRET"

dateCounter :: IORef Int
dateCounter = unsafePerformIO (newIORef 0)

hashBytes :: Char8.ByteString -> Char8.ByteString
hashBytes = Blake2.hash 64 mempty;
hashHex :: String -> String
hashHex =  (map toLower) . Char8.unpack . hex . hashBytes . Char8.pack;
makeKeys :: String -> [String]
makeKeys = (chunksOf 32) . hashHex;

data GameAuth = GameAuth
  { id :: Int
  , keys :: [String]
  } deriving (Show, Data, Typeable)

gameKeys id = GameAuth id (makeKeys ((show id)++"|keys|"++topsecret))

generateId = do
  time <- getUnixTime
  counter <- readIORef dateCounter
  modifyIORef dateCounter addCounter
  return $ shiftTime time counter
shiftTime time counter  = (fromEnum (utSeconds time))*1000 + counter
addCounter c = (c+1) `mod` 1000

main = do
  id <- generateId
  putStrLn (encodeJSON (gameKeys id))

Here's the node.js version; it needs blakejs (run npm i blakejs to install it):

const TOPSECRET = "TOPSECRET", blake = require("blakejs").blake2bHex;
let dateCounter = 0;

function gameKey(checkId){
  let id = checkId || (Date.now()/1000>>0)*1000+(dateCounter++%1000),
    keys = blake(`${id}|keys|${TOPSECRET}`).match(/.{32}/g);
  return {id, keys};
}
console.log(gameKey());


texts: Variant optional to return error string or value

texts:
I needed a class with more information than optionals give, I need to know why the optional is not valid in error states. I used a Boost variant for this. Since this will be wrapping almost all of my return values, I need to know if it's as fast as possible (i.e. did I do move semantics and all that jazz properly?).

template<typename T>
class Result
{
public:
    Result(const std::string& errorString) {
        contents = errorString;
    }

    Result(T&& value) {
        contents = std::forward<T>(value);
    }

    operator bool() {
        //is the active value our T
        return contents.which() == 0;
    }

    T unwrap() {
        return boost::get<T>(contents);
    }

    std::string unwrapErr() {
        return boost::get<std::string>(contents);
    }

private:
    boost::variant<T, std::string> contents;
};

Example use

Result<std::vector<int>> foo()
{
    if(success)
         return Result<std::vector<int>>({1,2,3});
    else
         return Result<std::vector<int>>("failure reason");
}

if(auto vec = foo())
   vec.unwrap() //do stuff to contained value
else
   std::cout << vec.unwrapErr();


texts: How can I optimize this code that finds the GCD?

texts:
int count;
int gcdCount;
int testCase = 5;

while (testCase > 0)
{
    int n = 5;
    count = 0;
    gcdCount = 0;
    // to get two  random numbers a and b a<=n and b<=n
    //get probablity of gcd(a,b) ==b
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            count++;
              // check if gcd(i,j) is equal to second number j
            if (findgcd(i, j) == j)
            {
                gcdCount++;
            }
        }
    }
     //return probability of gcdcount
    System.out.println(gcdCount + "/" + count);
    testCase--;
}


texts:
Given a serialized hash of any depth in string format, convert it into a hash object.

I want to know if my approach is correct, I am capturing states and storing the results in a stack and generating the hash from the stack. Also, is there a name for this kind of parsing approach?

def deserialize(input)
  h = {}
  l = 0
  stack = []
  curr_string = ""
  while l < input.length do
    case input[l]
    when "{" #state = DICT_START
      curr_string = ""
    when ":" #state =  VALUE_START
      stack.push(curr_string)
      curr_string = ""
    when "}", "," #state = DICT_END
      if curr_string != "" then
        stack.push(curr_string)
      end
      if stack.length > 0 then
        val = stack.pop
        key = stack.pop
        stack.push({key => val})
      end
      curr_string = ""
    else
      curr_string+=input[l]
    end
    l+=1
  end
  stack.each {|n| h.merge!(n)}
  h
end

p deserialize("{a:test,b:test1,c:test3}")
p deserialize("{a:{b:test1}}")
p deserialize("{a:{b:{c:test1}}}")
p deserialize("{a:{b:{c:test1}},d:123}")


texts:
I am caching an image locally..That same image will be used in few screens. Steps for doing this is as follows:

Get image from cache
If not present in NSCache, get image from Cache directory
If not present in Cache Directory, download from Internet
Save downloaded image to dir
Insert the image in cache

//Helper class is as

     class ImageCacheHelper:NSObject{

        static var cache = NSCache()
        static var isNotRunningDispatch:Bool = true

      class func setObjectForKey(imageData:NSData,imageKey:String){

            ImageCacheHelper.cache.setObject(imageData, forKey: imageKey)

        }

      class func getObjectForKey(imageKey:String)->NSData?{

            return ImageCacheHelper.cache.objectForKey(imageKey) as? NSData

        }

      class func getImage(imageUrl:String,completionHandler:(NSData)->()){
            if ImageCacheHelper.isNotRunningDispatch{

                ImageCacheHelper.isNotRunningDispatch = false
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
                    let imgUrl = NSURL(string:imageUrl)
                    let imageData = NSData(contentsOfURL: imgUrl!)!
                    ImageCacheHelper.setObjectForKey(imageData, imageKey: "\(imageUrl.hashValue)")
                    ImageCacheHelper.isNotRunningDispatch = true
                    completionHandler(imageData)

                })
            }else{
               print("alerady started loading image")
           }
        }
      }

//How i call this from ViewController class is as

let userImageUrl = "\(appBaseUrl)\(imageUrlString)"
let fileManager = NSFileManager.defaultManager()
let diskPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let cacheDirectory = diskPaths[0] as NSString
let diskPath = cacheDirectory.stringByAppendingPathComponent("\(userImageUrl.hashValue)")
if let data = ImageCacheHelper.getObjectForKey("\(userImageUrl.hashValue)"){
          let userImage =  UIImage(data: data)
          self.userImgView.image = userImage

}else if fileManager.fileExistsAtPath(diskPath){

          let image =  UIImage(contentsOfFile: diskPath)
          self.userImgView.image = image
          ImageCacheHelper.setObjectForKey(UIImageJPEGRepresentation(image, 1.0)!, imageKey: "\(userImageUrl.hashValue)")

}else   {
          ImageCacheHelper.getImage(userImageUrl){ imageData in

            imageData.writeToFile(diskPath, atomically: true)
                    dispatch_async(dispatch_get_main_queue()){

                        let userImage =  UIImage(data: imageData)
                        self.userImgView.image = userImage

                    }
        }
}

Flaws That I see in my code are as follows:

Creating a static variable for NSCache.
Would be great if settingObject in NSCache, getting would be as of NSUserDefaults.

How to optimize this?

Here is a snippet of project that i have tried to do
https://drive.google.com/file/d/0B6dTvD1JbkgBS1k3Ry1xNmZ1VHc/view?usp=sharing


texts:
I wonder if there is a "correct" way to display different content, based on the the state of responsive webdesign. Different in this case is meant as an abbreviated text to display instead of the full one.

I have created this example table with a couple columns, containing either the full name of a state, or, when resized to a smaller screensize, it's 2-letter code.

HTML:

<!doctype html>
<meta name="viewport" content="width=device-width"/>

    CaliforniaCA
    FloridaFL
    TexasTX
    GeorgiaGA

    Sacramento
    Tallahassee
    Austin
    Atlanta

CSS:

th {
    border: 1px solid #000;
}

td {
    border: 1px solid #000;
}

@media screen and (max-width:760px){
.full {
    display: inline;
    }
.abbr {
    display: none;
}
}

@media screen and (max-width:320px){
.full {
    display: none;
    }
.abbr {
    display: inline;
}
}

jsFiddle

It works as I want, but this solution kind of seems more like a hack to me to get it working.

I've googled, but haven't found anything regarding the topic, which might just be the result of not knowing what exactly to ask. Anyhow, I somehow got the feeling, that there's a more sophisticated way of doing such a thing.


texts: Scala: Are assertions acceptable outside of test context?

texts:
In the case that Type is not an option, data must exist so I just use an assert to clarify and throw an exception if data is missing. Is there a better way to do this? I think in Java this would be acceptable but I know the scala crowd tends to have a different idea of what idiomatic use of the language is.

private def convertData(dataOption: Option[ByteString], tpe: Type): Any = {

    if(tpe.<:<(typeOf[Option[Any]])){
      dataOption match{
        case Some(x) => ???
        case None => None
      }
    } else{
      assert(dataOption.isDefined)
      ???
    }
}


texts: Merit of a "Search" class similar to a "Builder" class

texts:
I have a class something like the following:

class ItemManager {

    List<Item> items;

    public ItemManager() {

        items = Database.retrieveItems();

    }
}

An item has several attributes, so much so that I used a Builder class instead of a typical constructor(Like the builder classes found in Joshua Bloch's Effective Java).  I want to use ItemManager to keep track of a large number of items and I want to be able to search for Items that match one or more given attributes.  My question is, is the following method a reasonable approach, where can I improve it, and what is a common method of tackling this problem?

class ItemManager {

    ... // constructor etc.

    public Search getSearch() {
        return new Search();
    }

    public class Search {

        // Set default search parameters
        AttrA attrA = null;
        AttrB attrB = null;
        AttrC attrC = null;

        public Search setAttrA(AttrA a) {
            attrA = a;
            return this;
        }

        ... // set method for all attributes

        public List<Item> search() {

            List<Item> results = new ArrayList<Item>();

            for(Item i : items) {

                // If the search parameter is still null OR if the attribute
                // matches the search parameter, add it to the result set
                if ( (attrA==null || i.getAttrA().equals(attrA) )
                    && (attrB==null || i.getAttrB().equals(attrB) )
                    && (attrC==null || i.getAttrB().equals(attrC) ) {

                    results.add(i);

                }
            }

            return results;
        }
    }
}

The implementation would look somethign like this (bear in mind the actual Item class would have much more than three attributes):

ItemManager itemManager = new ItemManager();

List<Item> items =
    itemManger.getSearch()
    .setAttrA(a)
    .setAttrB(b)
    .search();

There's a number of ways I can think of to improve this, but I didn't want to include them all (so they're welcome).


texts:
I wrote a simple ruby program for interacting with one of my temporary AWS S3 using Ruby SDK. Below is the program I've written. Since I learned ruby by myself I need help/suggestions in following ruby's best practices with OOPs concept.

require './my_aws_helper'

class AwsDemo
  include MyAwsHelper

  def start_execution
    p '1. Bucket Details, 2. Create Bucket 3. Upload To Bucket'
    choice = gets.chomp.to_i
    start_user_interaction(choice)
  end

  private

  def start_user_interaction(choice)
    case choice
    when 1 # Bucket details
      bucket_details
    when 2 # Create bucket
      create_bucket
    when 3 # Upload to bucket
      upload_file
    else
      p 'Invalid Selection'
    end
  end

  def bucket_details
    p "Enter ALL for all bucket details or select from [#{MyAwsHelper.bucket_names.join(', ')}]"
    selection = gets.chomp
    if selection == 'ALL'
      MyAwsHelper.all_bucket_details
    else
      MyAwsHelper.bucket_details(selection)
    end
  end

  def create_bucket
    p 'Enter bucket name'
    selection = gets.chomp
    response = MyAwsHelper.create_bucket(selection)
    if response.class == Aws::S3::Types::CreateBucketOutput
      p "Bucket created successfully, #{response.location}"
    else
      p response
    end
  end

  def upload_file
    p 'Select a bucket from bellow'
    bucket_names = MyAwsHelper.bucket_names
    bucket_names.each_with_index do |name, index|
      p "#{index + 1}. #{name}"
    end
    bucket_name = bucket_names[gets.chomp.to_i - 1]
    p 'Select files from bellow list'
    p current_dir_files
    file_name = gets.chomp
    response = MyAwsHelper.upload_file_to_aws(bucket_name, file_name)
    if response == true
      p 'File uploaded sucessfully'
    else
      p response
    end
  end

  def current_dir_files
    Dir.glob('*.*')
  end

  def file_in_dir(_dir_name)
    Dir.chdir('dir_name')
    Dir.glob('*.*')
  end
end

aws_demo = AwsDemo.new
aws_demo.start_execution

And below is my helper module

require 'aws-sdk'

module MyAwsHelper
  def self.set_aws_configs
    Aws.config.update(credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
                      region: 'us-east-1')
  end

  def self.aws_resource
    Aws::S3::Resource.new(region: 'us-east-2')
  end

  def self.aws_client
    Aws::S3::Client.new(region: 'us-east-2')
  end

  def self.create_bucket(bucket_name)
    p "Creating your bucket with name #{bucket_name}..."
    bucket = aws_resource.bucket(bucket_name)
    bucket.create
  rescue Aws::S3::Errors::ServiceError => e
    e.message
  end

  def self.upload_file_to_aws(bucket_name, file_name)
    p "Uploading #{file_name} to #{bucket_name} bucket...."
    obj = aws_resource.bucket(bucket_name).object(file_name)
    obj.upload_file(file_name)
  rescue Aws::S3::Errors::ServiceError => e
    e.message
  end

  def self.get_bucket(bucket_name)
    aws_resource.bucket(bucket_name)
  rescue Aws::S3::Errors::ServiceError => e
    e.message
  end

  def self.buckets
    aws_client.list_buckets
  end

  def self.bucket_names
    buckets.buckets.map(&:name)
  end

  def self.all_bucket_details
    p "Found #{bucket_names.length} buckets...."
    bucket_names.each do |bucket|
      bucket_details(bucket)
    end
  end

  def self.bucket_details(bucket_name)
    puts "\n\n"
    p 'Please wait..'
    bucket = get_bucket(bucket_name)
    if bucket.exists?
      p "name    : #{bucket.name}"
      p "created : #{bucket.creation_date}"
      contents = aws_client.list_objects_v2(bucket: bucket_name).contents
      puts("#{contents.length} records present")
      contents.each_with_index do |content, index|
        puts " => #{index + 1} #{content.key} \n"
      end
    else
      p "Bucket #{bucket_name} not found"
    end
  end
end

I need suggestions on

how this program can be improved
what are the other ways of achieving it
Security issues in the program


texts: Optimise many namedtuple assignment statements

texts:
I'd just like to know if there's a way I can reduce the number of namedtuple assignment statements in the code below. The actual program has over 60 assignment statements and I feel like that could be optimised using some form of loop or maybe a function of some kind.

I'm not exactly sure how to do this myself, any advice?

The more pythonic the better, may I add. I'm using Python 3.6.

Here is a reduced section of my code:

from collections import namedtuple
import json

try:
    with open('assets/bin/units.bin', 'r') as file:
        units = json.load(file)
except:
    print('Could not load file.')

Unit = namedtuple('Unit', ['name', 'stats', 'type', 'population', 'cost', 'description'])
Unit.__doc__ += ': Stores data about a single unit, including Name, Stats, Type, Population and Cost.'

#Units(Infantry)
trooper = Unit(units[0]['name'],
               units[0]['stats'],
               units[0]['type'],
               units[0]['population'],
               units[0]['cost'],
               units[0]['description'])
robot = Unit(units[1]['name'],
             units[1]['stats'],
             units[1]['type'],
             units[1]['population'],
             units[1]['cost'],
             units[1]['description'])
commando = Unit(units[2]['name'],
                units[2]['stats'],
                units[2]['type'],
                units[2]['population'],
                units[2]['cost'],
                units[2]['description'])
flame_trooper = Unit(units[3]['name'],
                     units[3]['stats'],
                     units[3]['type'],
                     units[3]['population'],
                     units[3]['cost'],
                     units[3]['description'])
engineer = Unit(units[4]['name'],
                units[4]['stats'],
                units[4]['type'],
                units[4]['population'],
                units[4]['cost'],
                units[4]['description'])

#Units(Vehicles)
truck = Unit(units[5]['name'],
             units[5]['stats'],
             units[5]['type'],
             units[5]['population'],
             units[5]['cost'],
             units[5]['description'])
tank = Unit(units[6]['name'],
            units[6]['stats'],
            units[6]['type'],
            units[6]['population'],
            units[6]['cost'],
            units[6]['description'])
icv = Unit(units[7]['name'],
           units[7]['stats'],
           units[7]['type'],
           units[7]['population'],
           units[7]['cost'],
           units[7]['description'])
railgun = Unit(units[8]['name'],
               units[8]['stats'],
               units[8]['type'],
               units[8]['population'],
               units[8]['cost'],
               units[8]['description'])
missile_launcher = Unit(units[9]['name'],
                        units[9]['stats'],
                        units[9]['type'],
                        units[9]['population'],
                        units[9]['cost'],
                        units[9]['description'])


texts: Tight loop, string manipulation and calculations

texts:
I'm working on some precompilation operations for a world compiler. Currently to identify flags placed by the level designer I need recognize when a specific entity exists at specific coordinates from the flag's origin. I need to generate a list of offset coordinates from the origin(and include the origin) in string form. That is 7 coordinates. this operation is done for every flag in the world, so it is preferred to be efficient. It is not an operation that takes place during gameplay, so I don't have to worry too much.

My current implementation works correctly, and quickly, however I still would like to get a review on what I have written, and hear any advice to better this operation.

string origin = "0 0 0";
double[] originParts = origin.Split(' ').Select(s => double.Parse(s)).ToArray();
List<string> origins = new List<string> { origin };
for (int i = 0; i < 3; i++)
    for (int j = -48; j <= 48; j += 96)
        origins.Add(string.Format("{0} {1} {2}",
            originParts[0] + (i == 0 ? j : 0),
            originParts[1] + (i == 1 ? j : 0),
            originParts[2] + (i == 2 ? j : 0)));


texts: Fold large input lines into smaller ones

texts:
I am working on a program that is meant to fold a large input line into smaller ones. Basic flow of the program would be as follows:

User calls the program with a long string as input
Program prints tokens generated in separate lines

I haven't seen handling file input yet, so keep that in mind. I haven't seen reading input from the command line either.

Here's the source code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int length(char input[]);

int main(int argc, char* argv[])
{

    if(argc < 3)
    {
        printf("Usage: %s input [n]\n", argv[0]);
        exit(1);
    }

    int COL_BOUND = atof(argv[2]);

    int startCol, currentCut, nextBound, numOfCuts;

    startCol = currentCut = nextBound = numOfCuts = 0;

    //while the next bound is still "inside" string
    while((nextBound = startCol + COL_BOUND - 1) <= length(argv[1]))
    {
        //find cut character
        for(int i = startCol; i <= nextBound; ++i)
        {
            if(isspace(argv[1][i]) && !isspace(argv[1][i-1]))
                currentCut = i - 1;
        }
        //there was no valid "cut" before whitespace or bound itself is valid
        if(!isspace(argv[1][nextBound]) || currentCut <= startCol)
            currentCut = nextBound;

        //print [startCol, cut]
        int printed = 0;
        for(int i = startCol; i <= currentCut; ++i)
        {
            if(isspace(argv[1][i]) && printed == 0)
                continue;
            ++printed;
            putchar(argv[1][i]);
        }

        printf("\n");

        //adjust start column for the next run
        startCol = startCol + COL_BOUND;
        ++numOfCuts;
    }

    //print remaining characters
    int printed = 0;
    ++numOfCuts;
    for(int i=startCol; i <= length(argv[1]); ++i)
    {
        if(isspace(argv[1][i]) && printed == 0)
            continue;
        ++printed;
        putchar(argv[1][i]);
    }

    printf("\nOriginal string split into %d parts (bound was %d)\n", numOfCuts, COL_BOUND);
    return 0;
}

int length(char input[])
{
    int i;
    for(i=0; input[i] != '\0'; ++i)
        ;
    return i;
}


texts:
I have written a program to reverse the lines of a file. I made use of the String [] approach with the String.split(separator) using a custom separator.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ReverseTheLinesOfaFile {

private static final String  SEPERATOR="-";

/**
 * This function reads the data of the file and then reverses the lines of the file keeping
 * the content as the same
 * @param fileName
 */
private void reverseLines(String fileName) {
    // TODO Auto-generated method stub
    File file = new File(fileName);
    //get the readers ready
    FileInputStream inputFile = null;
    StringBuilder textInput= new StringBuilder();
    String line=null;
    try {

        inputFile = new FileInputStream(file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputFile));

        //read the file line by line and append the separator
        while ((line= reader.readLine())!=null){
            textInput.append(line+SEPERATOR);
        }
        reader.close();
        inputFile.close();

        //get the writers ready
        FileOutputStream outputFile = new FileOutputStream(file);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputFile));

        String[] lines   = textInput.toString().split(SEPERATOR);

        //write line by line to the file
        for (int i= lines.length-1 ; i > -1 ; --i){
            writer.write(lines[i]+"\n");
        }
        writer.flush();
        writer.close();
        System.out.println("file reversing done");
    } catch (FileNotFoundException e) {
        System.out.println("The file with name ="+file.getName()+" could not be found");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("There has been a IO exception");
        e.printStackTrace();
    }
}

public static void main(String[] args) {

    ReverseTheLinesOfaFile linesOfaFile = new ReverseTheLinesOfaFile();
    linesOfaFile.reverseLines("data.txt");
}

}

I want to know whether this can be done even more efficiently and without the use of the Seprator variable. The file can contain all sorts of characters in the ASCII table.


texts:
I am trying to solve this question

  Given a non-empty string s and a dictionary wordDict containing a list
  of non-empty words, add spaces in s to construct a sentence where each
  word is a valid dictionary word. Return all such possible sentences.

  Note:

  The same word in the dictionary may be reused multiple times in the
  segmentation. You may assume the dictionary does not contain duplicate
  words.

https://leetcode.com/problems/word-break-ii/

My working code that times out:

class Solution:
    def wordBreak(self, s, word_set) :
        cache = {}
        word_set = set(word_set)
        def dfs(i):
            if i in cache:
                return cache[i]

            words = []
            res = ""
            if s[i:] in word_set:
                words.append(s[i:])

            for k in range(i, len(s)):
                res += s[k]
                next_words = dfs(k+1)
                if res in word_set:
                    for w in next_words:
                        new = res + " "+w
                        words.append(new)

            cache[i] = words
            return words
        return dfs(0)

How do I optimize this in terms of time and space complexity?


texts: Decoding custom packets with Python using Twisted

texts:
This server require fast decoding of packets from clients, as I am expecting 5000 concurrent clients that is sending packets possibly every second. This is a game server (5000 players walking send packets each n every step).

I want to see if my implementation is fast enough or there are still room for improvements. The encryption isn't on this code as I only want to tackle the decryption for now.

The decode function is taken from a JavaScript implementation, This is the best output I got after trying to translate it. (though the translation is correct because the results are same from JavaScript and now Python)

def dataReceived(self, data):
    packet = decode(data)
    (counter, packet_id, username, password, unknown) = unpack('<B H 16s 16s 16s', packet)
    print counter
    print packet_id
    print username
    print password
    print unknown

For example the above implementation is pretty straight forward but the concern here is the decode(data) part.

I am new to Python and Twisted so I had to do some maybe absurd way on implementing this.

This is my decode function:

def decode(packet_data):
    cl = 0x6e
    internal_rounds = 2
    i = 0

    seqX = bytearray.fromhex('HEXSTRINGREMOVED')
    seqY = bytearray.fromhex('HEXSTRINGREMOVED')
    result = []

    while i < (len(packet_data) - 4):
        dl = ord(packet_data[i])
        bl = seqX[(i * 2) + 1]
        al = seqX[i * 2]
        bl2 = seqY[(i * 2) + 1]
        dl2 = seqY[i * 2]
        j = internal_rounds - 1

        while j > 0:
            if bl <= dl:
                dl -= bl
            else:
                bl = (~bl) & 0xFF
                bl += 1
                dl += bl

            dl ^= bl2
            j -= 1
        if al <= dl:
            dl -= al
        else:
            al = (~al) & 0xFF
            al += 1
            dl += al
        dl ^= dl2
        dl ^= cl
        result.append(dl)
        cl ^= dl
        i += 1

    return "".join(map(chr, result))

I did this dl = ord(packet_data[i]) because I keep getting int -= char error.

Also did this return "".join(map(chr, result)) because I kept getting errors with unpack because the return was previously return result which result is an array.

So what do you think?  Should I also have used unpack_from instead? But I don't know how to make a buffer in Python. Is the data received already a buffer?


texts:
Question:

  An anagram is a word that can be written as a permutation of the
  characters of another word, like "dirty room" and "dormitory"(ignore
  spaces). However, "the" and "thee" are not anagrams, since "the" only
  has a single "e" whereas "thee" has two "e" characters (spaces can
  occur zero, or multiple times, however).

  Give a list of words as input, you should output another list of
  strings, each containing words that are mutual anagrams.

  Each string of the output should be a single group of anagrams joined
  with commas.

  Within an output string, the expressions should be sorted
  lexicographically. If a group contains only a single element, output
  that one-element group as a single string. And the strings should also
  be output in lexicographical order.

  Given e.g.:

  pear
  amleth
  dormitory
  tinsel
  dirty room
  hamlet
  listen
  silent

  The output would be:

amleth,hamlet
dirty room,dormitory
listen,silent,tinsel
pear

My solution is:

Convert into each string to a char array, and in the meantime, compare to each char array group. After that, get how many groups for an input string array, and divide them into a respective group.
Sort each group alphabetically, and eventually order by group.

Time-complexity is \$O(n^2)\$

I wrote code for this question, and it has a poor time-complexity. Are there any suggestions for this?

ArrayList<char[]> group = new ArrayList<char[]>();
    ArrayList<ArrayList<String>> originalList = new ArrayList<ArrayList<String>>();
    String[] tempstr = str.clone(); //clone could do deep copy, and avoid to change str.

    //Category group for str.
    outerloop:
    for(int pos=0; pos<tempstr.length; pos++){
        tempstr[pos]= tempstr[pos].trim().replaceAll(" ", "");
        char[] c = new char[tempstr[pos].length()];
        tempstr[pos].getChars(0,tempstr[pos].length(),c,0); //last character is at index srcEnd-1
        Arrays.sort(c);//ignore character's order in string.
        ArrayList<String> sArrList = new ArrayList<String>();

        Iterator<char[]> it = group.iterator();
        while(it.hasNext()){
            sArrList.clear();
            char[] comparedChars = (char[])it.next();
            if(Arrays.equals(comparedChars,c)){//only compare character in same index.
                sArrList = originalList.get(group.indexOf(comparedChars));
                sArrList.add(str[pos]);
                continue outerloop;
            }
        }
        // can not find group
        sArrList.add(str[pos]);
        originalList.add(sArrList);
        group.add(c);
    }

    //Following begin to do sorting.
    String[] groupStr = new String[group.size()];
    Iterator<ArrayList<String>> it2 = originalList.iterator();
    for(int groupId=0 ; groupId<group.size() && it2.hasNext(); groupId++){
        ArrayList<String> temp = it2.next();
        Collections.sort(temp); // let string in each single row sort by alphabet.
        for(Iterator it3 = temp.iterator();it3.hasNext();){
            String ss = (String) it3.next();
            if(groupStr[groupId]==null || groupStr[groupId].length()==0) groupStr[groupId] = ss;
            else groupStr[groupId] += "," + ss;
        }
    }


texts: Colored image will become black and white

texts:
For a project of mine, which is targeting java 6, I had been in the need to have different algorithms/methods to change a BufferdImage with a ColorSpace.TYPE_RGB to a plain ole black and white one.

To test these implementations I therefore created an interface

public interface BlackAndWhiteConverter {
    BufferedImage toBlackAndWhite(BufferedImage image);
    void setThreshold(int threshold);
}

and the, for me, most successful implementation is up for review

import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class BlackAndWhiteRedThresholdConverter implements BlackAndWhiteConverter {

    @Override
    public BufferedImage toBlackAndWhite(final BufferedImage image) {

        final int imageType = image.getColorModel().getColorSpace().getType();

        if (imageType != ColorSpace.TYPE_RGB) {
            throw new IllegalArgumentException();
        }

        final int width = image.getWidth();
        final int height = image.getHeight();
        final int upperLimit = width * height;

        final DataBuffer buffer = image.getRaster().getDataBuffer();
        final int[] source = ((DataBufferInt) buffer).getData();

        byte[] destination = new byte[upperLimit];

        for (int i = 0; i < upperLimit; i++) {

            int red = (source[i] >> 16) & 0x000000FF;

            if (red > threshold) {
                destination[i] = -1;
            }
        }

        WritableRaster raster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, width, height, 1, 2, null);
        raster.setDataElements(0, 0, width, height, destination);

        BufferedImage destinationImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
        destinationImage.setData(raster);
        return destinationImage;
    }

    private int threshold = 110;

    @Override
    public void setThreshold(int threshold) {
        this.threshold = threshold;
    }

}

Please comment on anything that springs into your face. No matter what, I can't use a java version higher than 6.


texts: Fetch an array result set using a mysqli wrapper class

texts:
I have a PHP class:

<?php
//connectionclass.php
class connectionclass{
public $conn;
public $warn;
public $err;

function __construct(){
  $this->connect();
}

private function connect(){
  $this->conn = @ new mysqli('localhost', 'sever_user', 'user_password');
    if ($this->conn->connect_error) {
      $this->conn = FALSE;
      $this->warn = '
Failed to connect database! Please try again later';
     }
}

public function get_data($qry){
 $result = $this->conn->query($qry);
    if ($result->num_rows>=1) {
        while($row=$result->fetch_assoc()){
           $rows[] = $row;
        }
        return $rows;
    } else {
        $this->err = $this->conn->error;
        return FALSE;
    }
}

}
?>

and a PHP page:

<?php
//login.php
include('/include/connectionclass.php');
$db = new connectionclass();

$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
  $rownum = count($data);
  for($i=0;$i<$rownum;$i++){
     echo $data[$i]['name'].'- '.$data[$i]['age'].'
';
  }
?>

Is there any idea for an easier way to iterate $data in the PHP page?


texts:
I've come up with this simple implementation of the Caesar cipher. It takes an integer argument and a file to produce the cipher text like so:

./caesar 4 < text.raw

Here's the code:

import System.Environment
import Data.List
import Data.Maybe

alnum = ['A' .. 'Z'] ++ ['a' .. 'z'] ++ ['0' .. '9']
anlen = length alnum

rotChar :: Int -> Char -> Char
rotChar r c
    | elem c alnum = alnum !! (mod (r + fromJust (elemIndex c alnum)) anlen)
    | otherwise = c

rotStr :: Int -> [Char] -> [Char]
rotStr 0 s = s
rotStr r s = (map (rotChar (mod (anlen + r) anlen)) s)

main :: IO ()
main = do
    args <- getArgs
    contents <- getContents
    putStrLn $ rotStr (read $ head args) contents

I'm new to Haskell and I'd like some opinions on the:

global "variables"
use of parentheses
argument parsing

Could any of this be improved? Any other tips will be appreciated.


texts: Uninstalling Erlang and RabbitMQ, using Write-Verbose to ensure sequencing

texts:
I'm new at PowerShell and I like it.

I had the change to write a script that uninstall Erlang and RabbitMQ and I want the same script to then remove the Erlang folder and the RabbitMQ folder.

But in order to do so I need the script to respect the tasks order.

My way out was to use Write-Verbose (line 13) so the script needs to wait for the task to end in order to pass to the next task:

# Let's set some verbosity
$VerbosePreference = 'Continue'

function Check_Program_Installed($programName){
    $check = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"  |
    Get-ItemProperty | Where-Object {$_.DisplayName -like "*$programName*" } | Select-Object -Property DisplayName, UninstallString

    If ($check.DisplayName) {
        $result = $check.DisplayName
        Write-Output "I found: $result, let's uninstall it!"
        $uninst = $check.UninstallString

        Write-Verbose $uninst
        Start-Process -FilePath $uninst -ArgumentList "/qn" -Wait #-NoNewWindow

        Check_Program_Installed($programName)
    }
    Else{
        Write-Output "$programName is not installed"
        }
}

# Erlang check and Uninstall
Write-Output "Checking if Erlang exist"
Check_Program_Installed("Erlang")
# RabbitMQ check and Uninstall
Write-Output "Checking if RabbitMQ exist"
Check_Program_Installed("Rabbit")

# These actions need to be executed ONLY after Erlang and RabbitMQ uninstall
Write-Output "Then we do action 1"
Start-Sleep -s 3
Write-Output "Then we do action 2"
Start-Sleep -s 3
Write-Output "Then we do action 3"
Start-Sleep -s 3
Write-Output "Then we do action 4"
Start-Sleep -s 3
Write-Output "Then we do action 5"

This is a very newbie approach but it's the only thing I came out with.

Is there a more elegant way to handle the task and avoid PowerShell to pass to the next task if the previous one isn't completed?


texts:
I am fairly new to programming and even newer to C++ but I am currently in a class for scientific computing, and our task from two weeks ago was to improve the speed of a primality test program. I regrettably do not have the original code because I wrote over it, but the long and short was that program selects 100,000 integers from 100,000 to 999,999 and checks all numbers from 2 to less than the number.

Needless to say, it took over 17 seconds to run. My code was able to get it down to ~74 milliseconds. I handed in my code last week but it's been bugging me that I don't know if I got it as fast as it could go.

(The area I made is at the bottom, at int CountPrimes)

#include "stdafx.h"

using namespace std;
using namespace chrono;

int CountPrimes(unique_ptr<vector<int>> const &samples);

seed_seq seed{ 2016 };
default_random_engine generator{ seed };
uniform_int_distribution<int> distribution(100000, 999999);

int main()
{
    const auto samples{ make_unique<vector<int>>(100000) };

    for (auto &sample : *samples)
        sample = distribution(generator);

    cout.imbue(std::locale(""));
    cout << "Searching vector of "
        << samples->size() << " integers..."
        << endl;

    auto startTime = system_clock::now();

    int numPrimes = CountPrimes(samples);

    auto stopTime = system_clock::now();

    auto totalTime = duration_cast<milliseconds>(stopTime - startTime);

    cout << "Number of Primes: " << numPrimes << endl;
    cout << "Total run time (ms): " << totalTime.count() << endl;

    system("pause");
    return 0;
}

int CountPrimes(unique_ptr<vector<int>> const &samples)
{
    int numPrimes{};
    for (const auto &sample : *samples) {
        bool isPrime = true;
        int n{ 2 };
        int m{ 3 };
        if (sample % n == 0)
        {
            isPrime = false;
        }
        while (m < sample && m < 990)
        {
            if (sample % m == 0)
            {
                isPrime = false;
                break;
            }
            m += 2;
        }

        if (isPrime)
            numPrimes++;
    }
    return numPrimes;
}


texts:
I made a simple program in which I compare two images pixel by pixel and determine if the pictures are the same. I'm trying to adapt it to MPI, but I'm afraid that the communications are taking too long, making it way more inefficient than its sequential counterpart. I have tried with images of very big resolution and the result is the same: the sequential code is more efficient than the parallel code. Is there a way of making it more efficient?

Sequential code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

unsigned char* BMP(char* filename,int* sizes)
{
    int i;
    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f);

    int ancho = *(int*)&info[18];
    int alto = *(int*)&info[22];

    int size = 3 * ancho * alto;
    *sizes = size;
    unsigned char* data = new unsigned char[size];
    fread(data, sizeof(unsigned char), size, f);
    fclose(f);
    for(i = 0; i < size; i += 3)
    {
            unsigned char tmp = data[i];
            data[i] = data[i+2];
            data[i+2] = tmp;
    }

    return data;
}

int main(int argc,char **argv){
  int sizes,i,bol;
  clock_t t1,t2;
  double tiemp;
  t1 = clock();
  bol=1;
  unsigned char* data1= BMP(argv[1],&sizes);
  unsigned char* data2= BMP(argv[2],&sizes);
  for (i =0; i<sizes; i += 3)
  {
    if(data1[i]!=data2[i]){
      printf("The images are not the same\n");
      bol=0;
      break;}
    }

  if(bol==1)
   printf("The images are the same\n");

   t2 = clock();
   tiemp = ((double) (t2 - t1)) / (CLOCKS_PER_SEC);
   printf("%f\n",tiemp );
  return 0;
 }

MPI counterpart:

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>

unsigned char* BMP(char* filename,int* sizes)
{
    int i;

    FILE* f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f);

    int ancho = *(int*)&info[18];
    int alto = *(int*)&info[22];

    int size = 3 * ancho * alto;
    *sizes = size;
    unsigned char* data = new unsigned char[size];
    fread(data, sizeof(unsigned char), size, f);
    fclose(f);
    for(i = 0; i < size; i += 3)
    {
            unsigned char tmp = data[i];
            data[i] = data[i+2];
            data[i+2] = tmp;
    }

    return data;
}

int main(int argc,char **argv){
  int sizes,i,world_rank,world_size;
  clock_t t1,t2;
  double tiemp;
  t1 = clock();

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  unsigned char* data1;
  unsigned char* data2;
  int root = 0;
  if(world_rank==0){
  data1= BMP(argv[1],&sizes);
  data2= BMP(argv[2],&sizes);
  printf("%d",sizes);
  }
  MPI_Bcast(&sizes,1,MPI_INT,root,MPI_COMM_WORLD);
  int num_elements_por_proc = sizes/world_size;
  unsigned char* subdata2=new unsigned char[num_elements_por_proc];
  unsigned char* subdata1=new unsigned char[num_elements_por_proc];
  MPI_Scatter( data1, num_elements_por_proc, MPI_UNSIGNED_CHAR, subdata1, num_elements_por_proc, MPI_UNSIGNED_CHAR, root, MPI_COMM_WORLD );
  MPI_Scatter( data2, num_elements_por_proc, MPI_UNSIGNED_CHAR, subdata2, num_elements_por_proc, MPI_UNSIGNED_CHAR, root, MPI_COMM_WORLD );
  int bol = 0;
  if(world_rank!=0){

    for(i=0;i<=num_elements_por_proc;i++){
      if(subdata1[i]!=subdata2[i]){
        bol = 1;
        break;
      }
     }
 }
 int bolls;
 MPI_Reduce(&bol,&bolls,1, MPI_INT, MPI_SUM, 0,MPI_COMM_WORLD);

 if(world_rank==0){
  if(bolls !=0){
    printf("The images are not the samen");}
  else{
    printf("The images are the same \n" );}

 t2 = clock();
 tiemp = ((double) (t2 - t1)) / (CLOCKS_PER_SEC);
 printf("%f\n",tiemp );
 }
 MPI_Finalize();
 return 0;
 }


texts: Calculate the Euler-Mascheroni constant without the math module

texts:
The below code was written to generate γ, for educational purposes.

Single threaded, no functional zeroes required, no binary splitting(which can all be used to compute competitively like y-cruncher, that version in works).
Uses the Arithmetic Geometric Mean to calculate large logarithms quickly.
Uses decimal module for precision management.

I've computed 3000 digits in a few hours with it, and 200 in about a minute. I am happy calculating.

import decimal

D = decimal.Decimal

def agm(a, b):      #Arithmetic Geometric Mean
    a, b = D(a),D(b)
    for x in range(prec):
        a, b = (a + b) / 2, (a * b).sqrt()
    return a

def pi_agm():       #Pi via AGM and lemniscate
    a, b, t, p, pi, k = 1, D(2).sqrt()/2, 1/D(2), 2, 0, 0
    while 1:
        an    = (a + b) / 2
        b     = (a * b).sqrt()
        t    -= p * (a - an)**2
        a, p  = an, 2**(k+2)
        piold = pi
        pi    = (a + b) * (a + b) / (2*t)
        k    += 1
        if pi == piold:
            break
    return pi

def factorial(x):       #factorial fast loop
    x = int(x)
    factorial = D(1)
    for i in range(1, x+1):
        factorial *= i
    return factorial

def lntwo():        #Fast converging Ln 2
    logsum, logold, n = D(0), D(0), 0
    while 1:
        logold = logsum
        logsum += D(1/((D(961**n))*((2*n)+1)))
        n += 1
        if logsum == logold:
            logsum1 = (D(14)/D(31))*logsum
            break
    logsum, logold, n = D(0), D(0), 0
    while 1:
        logold = logsum
        logsum += D(1/((D(25921**n))*((2*n)+1)))
        n += 1
        if logsum == logold:
            logsum2 = (D(6)/D(161))*logsum
            break
    logsum, logold, n = D(0), D(0), 0
    while 1:
        logold = logsum
        logsum += D(1/((D(2401**n))*((2*n)+1)))
        n += 1
        if logsum == logold:
            logsum3 = (D(10)/D(49))*logsum
            break
    ln2 = logsum1 + logsum2 + logsum3
    return ln2

def lnagm(x):   #Natural log via AGM,
    try:
        if int(x) == 1:
            return 0
        if int(x) == 2:
            return lntwo()
    except:
        pass
    m = prec*2
    ln2 = lntwo()
    decimal.getcontext().prec = m
    pi = D(pi_agm())
    twoprec = D(2**(2-D(m)))/D(x)
    den = agm(1, twoprec)*2
    diff = m*ln2
    result = (D(pi/den) - D(diff))
    logr = D(str(result)[:m//2])
    decimal.getcontext().prec = prec
    return logr

def gamma():   #Compute Gamma from Digamma Expansion
    print('Computing Gamma!')
    k = D(prec/2)
    print('Calculating Logarithms...')
    lnk = lnagm(k)
    logsum = D(0)
    upper = int((12*k)+2)
    print('Summing...')
    for r in range(1, upper):
        logsum += D((D(-1)**D(r-1))*D(k**D(r+1)))/D(factorial(r-1)*D(r+1))
        if r%1000==0:
            print(str((D(r)/D(upper))*100)[:5], '% ; Sum 1 of 2')
    logsum1 = D(0)
    print('...')
    for r in range(1, upper):
        logsum1 += D((D(-1)**D(r-1))*(k**D(r+1)))/D(factorial(r-1)*D(D(r+1)**2))
        if r%1000==0:
            print(str((D(r)/D(upper))*100)[:5], '% ; Sum 2 of 2')
    twofac = D(2)**(-k)
    gammac = str(D(1)-(lnk*logsum)+logsum1+twofac)
    return D(gammac[:int(prec//6.66)])

#Calling Gamma
prec = int(input('Precision for Gamma: '))*8
decimal.getcontext().prec = prec
gam = gamma()
print(gam)


texts:
Is there a simpler way with a simpler notation to do the following part of code:

void swap(char **s1, char **s2){
    char *tmp=*s1;
    *s1=*s2;
    *s2=tmp;
}

void sort(char ***m, int dim){
    int i, j, flag=1;

    for(i=0; i<dim-1 && flag==1; i++){
        flag=0;
        for(j=0; j<dim-1; j++)
            if(strcmp((*m)[j],(*m)[j+1])>0){
                swap(&(*m)[j],&(*m)[j+1]);
                flag=1;
            }
    }
}

int main(int argc, char *argv[]){

    char **m, s[30];
    int i;

    m=malloc(N*sizeof(char *));
    for(i=0; i<N; i++){
        scanf("%s", s);
        m[i]=strdup(s);
    }

    sort(&m, N);
    for(i=0; i<N; i++)
        printf("%s\n", m[i]);

    for(i=0; i<N; i++)
        free(m[i]);
    free(m);

    return 0;
}

The aim is to sort an array of strings allocated dynamically.
What I've written above works but I want to know if there is a more efficient and readable way to write the function sort.


texts:
Is there a way to make my code simpler/more Pythonic?

  Given three int values (a, b, c), return True if one of b or c is "close"
  (differing from a by at most 1), while the other is "far", differing
  from both other values by 2 or more. Note: abs(num) computes the
  absolute value of a number.

  close_far(1, 2, 10) → True
  close_far(1, 2, 3) → False
  close_far(4, 1, 3) → True

def close_far(a, b, c):
    if abs(a - b) <= 1 or abs(a - c) <= 1:
        if abs(c - a) >= 2 <= abs(c - b) or abs(b - a) >= 2 <= abs(b - c):
            return True
    return False