texts:
I have recently started using browserify and have created a custom module to toggle two menus based on the ID clicked and apply a transparent overlay effect behind the menu. I have got it working but just wanted to get some feedback on weather it can improved performance or coding wise as I am wanting to improve my JS skills.

/**
* Require modules
*/
var dullBackground = require('./dullBackground');

/**
* Export module
*/
module.exports = function() {

  'use strict';

  /**
  * Selectors
  */
  var menu = document.getElementById('nav-main');
  var panel = document.getElementById('overlay-panel');
  var productsPanel = document.getElementById('products-panel');
  var systemsPanel = document.getElementById('systems-panel');
  var close = document.getElementById('overlay-close');
  var activeClass = 'active';
  var hideClass = 'hide';

  /**
  * Methods
  */
  function togglePanel(event) {

    // Selectors
    var elementId = event.target.id;

    event.preventDefault();

    // Conditions
    if(elementId === 'page-products' || elementId === 'page-systems') {
      dullBackground();
      panel.classList.add(activeClass);
    }
    if(elementId === 'page-products') {
      productsPanel.classList.remove(hideClass);
    }
    if(elementId === 'page-systems') {
      systemsPanel.classList.remove(hideClass);
    }

  }
  function closePanel(event) {

    // Actions
    panel.classList.remove(activeClass);
    event.preventDefault();

    // Conditions
    if(!productsPanel.classList.contains(hideClass)) {
      productsPanel.classList.add(hideClass);
    }
    if(!systemsPanel.classList.contains(hideClass)) {
      systemsPanel.classList.add(hideClass);
    }

  }

  /**
  * Events/APIs/init
  */
  menu.addEventListener('click', togglePanel, false);
  close.addEventListener('click', closePanel, false);

};


texts: Using doParallel to cycle through *.rds files

texts:
Overview

I have 165,000 *.rds files that are around 200,000 obs x 13 variables each.  These files are unique to grid files (2.5 square mile data) so I need to keep them in their unique grid numbers.  Currently, I'm loading each individual file, performing some function on the data, and resaving them to another directory; however, this took up to a week to process and I'm trying to improve the code to run in parallel.  I recently started 10 individual RStudio sessions and divided the grids into 10 separate sessions to run in parallel.  It worked fine and only took a day to run through.  This is not very efficient though and I would like to try to get it running in parallel using only one rsession.

The following code is a simple example I made that closely resembles the basic function of the loop.  This is not the exact code as it would not be useful to post all the files and all the code.

Question

Is this the proper way to run parallel when loading individual files,  applying a function to the data, and re-save to a directory?  It seems to be working, but I don't know if it is the correct way to do this.

RDS Files:

df1

df2

df3

Code

# Multicore
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)

# Function
check <- function(x){
  df <- readRDS(paste0("./", x))
  df$var <- df$var*2
  saveRDS(df, paste0("./temp/", x))
}

# Directory where *.rds files are
files <- list.files("./")

# for loop
for (i in unique(files)){
  check(i)
}

# foreach loop
foreach(i = unique(files)) %dopar% check(i)


texts: Project Euler #4 Python while loop efficiency

texts:
The problem statement for Project Euler Problem 4 is as follows:

  A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  Find the largest palindrome made from the product of two 3-digit numbers.

Looking to make this code more efficient. I'm using a variable to pass into the function so that the answer to ints of various lengths can be determined. It's been the most efficient that I've been able to come up with. Any suggestions?

def largestPalindromeProduct(digits):
    num=int(digits*"9")
    maxPalindrome=0
    i=int(num)
    floor=int(num/10) if digits > 1 else -1
    while i > floor:
        j=i
        while j > floor:
            val=str(i*j)
            if val==val[::-1]:
                floor=j
                maxPalindrome=max(maxPalindrome,i*j)
            j-=1
        i-=1
    return maxPalindrome

print(largestPalindromeProduct(3))


texts: “Offset position on scroll” JavaScript snippet

texts:
I'm at a loss as to how I could optimize this bit of code. I realize I could place these objects into some sort of array, but I'm not sure how to go about this.

$(document).ready(function () {
   var $stripe01 = $('.stripe-01');
   var $stripe02 = $('.stripe-02');
   var $stripe03 = $('.stripe-03');
   var $stripe04 = $('.stripe-04');
   var $stripe05 = $('.stripe-05');
   var $stripe06 = $('.stripe-06');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c) * 18);
    scrollPercent02 = (s / (d - c) * 14);
    scrollPercent03 = (s / (d - c) * 30);
    scrollPercent04 = (s / (d - c) * 4);

    var position01 = -(scrollPercent * ($(document).width() - $stripe01.width()));
    var position02 = -(scrollPercent02 * ($(document).width() - $stripe01.width()));
    var position03 = -(scrollPercent03 * -($(document).width() - $stripe03.width()));
    var position04 = (scrollPercent04 * -($(document).width() - $stripe04.width()));

    $stripe01.css({
        'left': position01
    });
    $stripe02.css({
        'left': position02
    });
    $stripe03.css({
        'right': position03
    });
    $stripe04.css({
        'right': position03
    });
    $stripe05.css({
        'right': position03
    });
    $stripe06.css({
        'left': position04
    });
});
});


texts:
I'm trying to come up with a solution to a coding challenge on Kattis, where there is a 2D grid filled with x's and o's, and the goal is to figure out whether or not a given starting coordinate can reach a given end coordinate by traveling up, down, left, or right. Only the o's are navigable, and the width and height of the grid can each be up to 1000 characters.

Here is an example grid:

xoxxx
ooxxo
oxxxo
ooooo
oxxxx
ooooo

I'll define this as

std::vector<std::string> space;

For this space, e.g., space[0][1] can reach space[5][4].

Note: This isn't quite the problem. I've generalized it a bit because there are some nuances that are a bit irrelevant to efficiency. Here's the actual problem.

I've taken a recursive approach to this problem, and my program passes the first 22 out of the 25 total test cases, before exceeding the 1-second time limit. The algorithm that I thought of was to keep checking whether the next valid coordinate could reach the end. The base case occurs when the starting coordinate is the ending coordinate, and it signifies that the problem's starting point can reach the ending point. If there is no valid next location then the current path cannot reach the ending point. If all the paths reach a dead end then that signifies that the problem's starting point cannot travel to the ending point.

Here are the brains of the program (specifically canTravel):

struct Point {
    int x, y;
    friend bool operator==(const Point &p1, const Point &p2);
};

bool operator==(const Point &p1, const Point &p2) {
    return p1.x == p2.x && p1.y == p2.y;
}

std::vector<Point> memo; // take note of the visited locations to avoid revisiting them

bool memoContains(const Point &p1) {
    return std::find_if(memo.begin(), memo.end(), [&](const Point &p) { return p == p1; }) != memo.end();
}

bool canTravel(const std::vector<std::string> &space, const Point &start, const Point &end) {
    if (start == end) // base case: the start == the destination
        return true;

    memo.push_back(start); // add current location to the list of visited locations

    /*
    format:

    const auto &next_location = avoid out of bounds error &&
        next location is an 'o' &&
        avoid revisiting a location &&
        recursively check whether the next location can reach the destination

    */

    const auto &right = start.x < space[start.y].length() - 1 &&
        space[start.y][start.x + 1] == 'o' &&
        !memoContains({ start.x + 1, start.y }) &&
        canTravel(space, { start.x + 1, start.y }, end);

    const auto &left = start.x > 0 &&
        space[start.y][start.x - 1] == 'o' &&
        !memoContains({ start.x - 1, start.y }) &&
        canTravel(space, { start.x - 1, start.y }, end);

    const auto &down = start.y < space.size() - 1 &&
        space[start.y + 1][start.x] == 'o' &&
        !memoContains({ start.x, start.y + 1 }) &&
        canTravel(space, { start.x, start.y + 1 }, end);

    const auto &up = p1.y > 0 &&
        space[start.y - 1][start.x] == 'o' &&
        !memoContains({ start.x, start.y - 1 }) &&
        canTravel(space, { start.x, start.y - 1 }, end);

    return right || left || down || up; // at least one path needs to reach the destination
}

Why is this slow/inefficient? How can it be improved? Can a recursive approach be used here or is an iterative one preferable?


texts: Solution to 99 lisp problems: P08 with functional javascript

texts:
Solution to 99 lisp problems: P08, with functional javascript

  If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.

* (compress '(a a a a b c c a a d e e e e))
  (A B C A D E)

Anyone want to review?

function cond( check, _then, _continuation ) {
  if(check) return _then( _continuation )
  else return _continuation()
}

function compress( list ) {
  return (function check( index, item, nextItem, compressed ) {
    return cond( item !== nextItem, function _then( continuation ) {
        compressed = compressed.concat([ item ])
        return continuation()
      },
    function _continueation() {
      return cond(!nextItem, function _then() {
          return compressed
      },
      function _continuation() {
          return check( index + 1, list[index + 1], list[index + 2], compressed )
      })
    })
  })( 0, list[0], list[1], [] )
}

ref:
http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html


texts:
I am a newbie and tried to find the laziest way to do a file upload using EmberJS, jQuery and formdata (IE10+). The code might look stupid, but it worked.

Can you please take a look and give some suggestions?  Am I doing it wrong?

<script type="text/x-handlebars" data-template-name="posts">

<form role="form" enctype="multipart/form-data" method="post" id="fileinfo" {{action    'createPost' on='submit'}}>

  {{input type="text" value=newPost  id="newPost" placeholder="Post" class="form-control"}}

  {{input type="file" id="inputFile"  class="form-control" name="file"}}

  <button type="submit" class="btn btn-default" >Submit</button>

</form>

</script>

App.PostsController = Ember.ArrayController.extend({
actions: {
    createPost: function(){
                    var fd = new FormData(document.getElementById("fileinfo"));
                    fd.append("postContent", this.get('newPost'));
                    this.set('newPost', ''); //reset text field
                    $('#inputFile').val(''); //reset fileinput field

                    Ember.$.ajax({
                      url: "http://localhost:3000/posts",
                      type: "POST",
                      data: fd,
                      processData: false,  // tell jQuery not to process the data
                      contentType: false,   // tell jQuery not to set contentType
                    });

                    }
                 }
             });


texts: Run different methods in background threads without duplication

texts:
In my Android app I have number of methods that should be executed in a background thread.

One of the methods looks like this

public static void processItem(final Context context, final String itemId)
{
    if (Looper.myLooper() == Looper.getMainLooper())
    {
        Thread task = new Thread()
        {
            @Override
            public void run()
            {
                processItem(context, playlistId);
            }
        };

        task.start();
        return;
    }

    // actual processing
}

As you can see, there are some code that only ensures an eligible thread is used.

How can I avoid copying this "threading" code over and over for each method that should be run in a background thread?


texts: A simple and safe implementation for strnstr (search for a substring in the first n characters of char array)

texts:
I'd like to suggest the following implementation:

// Find an instance of substr in an array of characters
// the array of characters does not have to be null terminated
// the search is limited to the first n characters in the array.
char *strnstr(char *str, const char *substr, size_t n)
{
    char *p = str, *pEnd = str+n;
    size_t substr_len = strlen(substr);

    if(0 == substr_len)
        return str; // the empty string is contained everywhere.

    pEnd -= (substr_len - 1);
    for(;p < pEnd; ++p)
    {
        if(0 == strncmp(p, substr, substr_len))
            return p;
    }
    return NULL;
}

The rationale for the first parameter is not to be const is that you may want to use the return value pointer to modify the array in that location.

for completeness, in C++, it's possible to add an overloaded variant that's const:

const char *strnstr(const char *str, const char *substr, size_t n)
{
    return strnstr((char *)str, substr, n);
}

Any comments?

As suggested, here's a test program:

#include <iostream>
#include <cstring>
#include <string>

int main()
{
    char s[] = "1234567890abcdefgh";
    size_t n = sizeof(s) - 1;

    const char *patterns[] = { "efgh", "0ab", "0b", NULL };
    const char *result = NULL;
    const char *pPattern = patterns[0];

    std::cout << "array of length " << n << " is: " << s << std::endl;

    for (int i = 0; pPattern; pPattern = patterns[++i])
    {
        result = strnstr(s, pPattern, n);
        std::cout << "finding " << pPattern << " n=" << n << ": "
            << (result ? result : "(null)") << std::endl;
    }

    pPattern = patterns[0];
    result = strnstr(s, pPattern, n-1);
    std::cout << "finding " << pPattern << " n=" << n-1 << ": "
        << (result ? result : "(null)") << std::endl;
    return 0;
}

Output:

array of length 18 is: 1234567890abcdefgh
finding efgh n=18: efgh
finding 0ab n=18: 0abcdefgh
finding 0b n=18: (null)
finding efgh n=17: (null)


texts: Analyzer for compression algorithms (or tools)

texts:
This file contains the main functions of my tool, rac. In particular, I care a lot about the Shannon function.

Would you please give some hints to make the file  cleaner? I have a perversion for concise and good indented code.

#include <math.h>
#include <stdio.h>
#include "headers/utils.h"

double ccount(char * foo)
{
  FILE * file = fopen(foo, "r");
  int a = 0, b;
  while ((b = getc(file)) != EOF)
    a++;

  fclose(file);
  return a;
}

int cmp(double foo, double bar)
{
  if (foo >= bar)
    return 1;
  else
    return 0;
}

double ratio(double foo, double bar)
{
  return (100*(foo - bar)/ foo);
}

void stat(char * file, double vector[256])
  {
    int c;
    FILE * ftopen = fopen(file, "r");
    while ((c = getc(ftopen)) != EOF)
      {
        if (c >= 0 && c <= 256)
            vector[c]++;
      }

      fclose(ftopen);
  }

void freq(char * foo, double vector[256])
{
  int i;
  for (i = 0; i < 256; i++)
  {
    if (vector[i] == 0)
      continue;
    else
      {
        vector[i] = (vector[i] / ccount(foo));
      }
  }
}

double shannon(double vector[256])
{
  int i;
  double shan = 0.0;
  for (i = 0; i < 256; i++)
  {
    if (vector[i] == 0.0)
      continue;
    else
      {
        shan = shan + (log2(pow(vector[i], vector[i])));
      }
  }
  return (shan * -1.0); //entropy of the file
}


texts: Iterating through each grid row and matching elements to largest height

texts:
I have a grid that lists products. The grid is three columns wide, but it could grow to be four or five columns wide. I've written my script to count the columns. The markup is something like this:

...

...

...

...

...

...

In the project, I can't change the markup. I can however write JavaScript/jQuery any which way I please. What I have is working, but I'm using four loops. Since my JS chops aren't too hot, I'm not convinced that what I have is particularly fast or concise.

jQuery(document).ready(function ($) {
"use strict";

var maxItemHeight,
    firstItem = $('.item.first'),
    gridRow = [],
    i;

firstItem.each(function () {
    gridRow.length = 0;
    maxItemHeight = 0;
    gridRow.push($(this));
    $(this).nextUntil(firstItem).each(function () {
        gridRow.push($(this));
    });
    for (i = 0; i < gridRow.length; i++) {
        maxItemHeight = (gridRow[i].find('h2').outerHeight() > maxItemHeight) ? gridRow[i].find('h2').outerHeight() : maxItemHeight;
    };
    for (i = 0; i < gridRow.length; i++) {
        gridRow[i].find('h2').css('height', maxItemHeight);
    };
});
});

How could this be improved?


texts: x as the sum of unique integers raised to power n

texts:
I've done this problem using recursion. But I'm not sure that could this be optimized for bigger values of x using memoization.

private static int allWaysM(int x, int n, int currNum, int currSum, int[][] storage){
    /*This is a helper function*/
    if(storage[currName][currSum] != -1)
        return storage[currNum][currSum];
    int result = 0;
    int p = power(currNum, n);
    while(currSum + p < x){
        result += allWaysM(x, n, currNum + 1, currSum + p, storage);
        currNum++;
        p = power(currNum, n);
    }
    if(currSum + p == x){
        result++;
        storage[currNum][currSum] = result;
    }
    return result;
}
public static int allWaysM(int x, int n){
    /*I'm also not sure about the size of the following array*/
    int[][] storage = new int[x][x];
    for(int i = 0; i < storage.length; i++)
        for(int j = 0; j < storage[i].length; j++)
            storage[i][j] = -1;
    return allWaysM(x, n, 1, 0, storage);
}

The function power(x, p) calculates the int value x raised to power p times. It is giving correct output until input: x = 1722, n = 2. Any other faster way, other than recursion, plus pointing out mistakes in this code will be helpful.


texts: Error handling with C-string input using get() and getline()

texts:
I've just learned the basics of c-strings and how to read line oriented input. I noticed that fail bits are set for each function. However, not every problem sends a fail bit, so I thought this would be a good exercise to try and target two user input errors:

The user enters no input
The user enters more input than the allocated number of elements

/*Simple Error handle using get() and getline()
 *with too much input or no input on c-style strings
*/
#include <iostream>
#include <string>
#include <limits>

int main() {

    const int size = 10;

    std::cout << "Please enter your name and hit enter. Then have your friend do the same\n\n";

    //Using get()
    std::cout << "Your name: ";
    char name1[size];

    while (!std::cin.get(name1, size) || std::cin.get() != '\n') {
        if (!std::cin) {
            std::cout << "No input\n";
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        else {
            std::cout << "Name entered was too large for allocated memory...\n";
        }
        std::cout << "Try again: ";
    }

    //using getline()
    std::cout << "Your friends name: ";
    char name2[size];

    while (!std::cin.getline(name2, size) || name2[0] == NULL) {
        if(name2[0] == NULL){
            std::cout << "No input\n";
        }
        else {
            std::cout << "Name entered was too large for allocated memory...\n";
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        std::cout << "Try Again: ";
    }

    std::cout << "\nNAME1: " << name1 << " NAME2: " << name2 << "\n";

    std::cin.get();

    return 0;
}


texts: small ticker class to execute a function at a regular inverval

texts:
I have written the following ticker class. You can find a description and example usage in its comments. However, it kind of feels like I am using too many thread synchronization tools (std::atomic, std::mutex and std::condition_variable). Is there a way to simplify this?

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <iostream>
#include <thread>

// Executes a function f in a fixed interval (given in microseconds).
// Call ticker::start() to run.
// The ticker stops when ticker::stop() is called
// or the instance runs out of scope.
//
// Example usage:
//
// void say_hi()
// {
//     std::cout << "hi " << std::endl;
// }
// int main()
// {
//     ticker hi_ticker( say_hi, 2 * 1000 * 1000 );
//     hi_ticker.start();
//     std::this_thread::sleep_for( std::chrono::milliseconds( 4500 ) );
// }
class ticker
{
public:
    typedef std::function<void()> function;
    void start()
    {
        if ( running_flag_ )
        {
            return;
        }
        running_flag_ = true;
        thread_ = std::thread( [this]() { thread_function(); } );
    }
    ticker( const function& f, std::int64_t interval_us ) :
        f_( f ),
        interval_us_( interval_us ),
        running_flag_( false ),
        thread_(),
        stop_mutex_(),
        stop_cv_()
    {}
    void stop()
    {
        if ( !running_flag_ )
        {
            return;
        }
        running_flag_ = false;
        {
            std::lock_guard<std::mutex> lock( stop_mutex_ );
            stop_cv_.notify_all();
        }
        if ( thread_.joinable() )
        {
            thread_.join();
            thread_ = std::thread();
        }
    }
    ~ticker()
    {
        stop();
    }
private:
    void thread_function()
    {
        auto last_time = std::chrono::high_resolution_clock::now();
        while ( running_flag_ )
        {
            auto current_time = std::chrono::high_resolution_clock::now();
            const auto wake_up_time =
                last_time + std::chrono::microseconds{ interval_us_ };
            while ( current_time < wake_up_time )
            {
                const auto sleep_time = wake_up_time - current_time;
                std::unique_lock<std::mutex> lock( stop_mutex_ );
                stop_cv_.wait_for( lock, sleep_time );
                current_time = std::chrono::high_resolution_clock::now();
                if ( !running_flag_ )
                {
                    return;
                }
            }
            const auto elapsed = current_time - last_time;
            last_time = current_time;
            const auto elapsed_us =
                std::chrono::duration_cast<std::chrono::microseconds>(
                    elapsed).count();
            f_();
        }
    }
    const function f_;
    const std::int64_t interval_us_;
    std::atomic<bool> running_flag_;
    std::thread thread_;
    std::mutex stop_mutex_;
    std::condition_variable stop_cv_;
};

edit: Here is the improved version, based on the excellent reviews here: https://gist.github.com/Dobiasd/99f3b5b0632d57d1f66c94658760c986


texts: Read and output a json object with the least server processing expenditure possible

texts:
On my server I have a large json that is accessed by several applications. One application only needs a certain part of the json, so presenting the whole json to the application is an unnecessary increase of bandwith. (Original JSON: about 40 KB, Optimized JSON: about 500 b)

What I came up with is a php script to which every application sends the application name. The script then reads the json on the server and prints out the shrinked json for the application to read. It works, but I'm concerned about wheter the php script could possibly put the server processing capabilities to its limits. Is there a more efficient solution over mine?

Note:
The part before the "ids" object is needed by all applications, that's why the php script just echo it out.
If an application fails to send its name to the server, the server just outprints the raw json.

The raw JSON as it exists on the server:

{
    "a": 0,
    "d": 0,
    "pD": "ok",
    "p": "ok",
    "an": "123",
    "slider_1": ["One Slider", "https://example.com/1"],
    "slider_2": ["Two Slider", "https://example.com/2"],
    "ids": {
        "Application One": {
            "info one": "210799155",
            "info two": "1544002021777"
        },
        "Application Two": {
            "info one": "211061341",
            "info two": "0000000",
        },
.
.
.
much more Applications

The PHP script to optimize:

<?php

//Read and decode the json file on the server
$txt = fread(fopen("json", "r"),filesize("json"));
$json =json_decode($txt,true);

//Echo the part needed by every applicaition
echo '{
    "a": 0,
    "d": 0,
    "pD": "ok",
    "p": "ok",
    "an": "123",
    "slider_1": ["One Slider", "https://example.com/1"],
    "slider_2": ["Two Slider", "https://example.com/2"],
    "ids": { "' . $_GET["id"] . '" :';

$s = json_encode($json["ids"][$_GET["id"]]);

//check if the application failed to send the name
if ($s === "null"){
ob_end_clean();
echo $txt;
exit();
}else{
//write the application specific part of the json
echo $s;
}

echo "}}";


texts:
I am still new to Scala and wrote a small snippet to find all the combinations with replacement of a sequence (e.g. cwr(ab, 3) should give aaa, aab, abb, bbb).
The slow way would be to generate all permutations, sort them, and throw out duplicates.  I'd like to know if this code is idiomatic Scala style, and if I'm making any bad performance mistakes.

def sortedRanges(lo: Int, hi: Int, reps: Int) : List[List[Int]] =
    if (reps == 0) List(Nil) else (
    List.range(lo,hi).flatMap(
        (x:Int) => (sortedRanges(x,hi,reps-1).map((xs:List[Int]) => x :: xs ))
    )
)

def combinations_with_replacement[T](stuff: List[T], reps: Int) : List[List[T]] =
  sortedRanges(0,stuff.length, reps).map( (xs:List[Int]) => xs.map(stuff(_)))


texts:
I built a small project using Django-Rest-Framework. Please comment on the best practice style for the code below, which will make it simpler.

class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if phone and password:
            user = authenticate(phone=phone, password=password)
            if user:
                if user.is_active:
                    data['user'] = user
                else:
                    raise exceptions.ValidationError('User is deactivated.')
            else:
                raise exceptions.ValidationError(
                    'Unable to login with given credentials.')
        else:
            raise exceptions.ValidationError(
                'Must provide username and password both.')
        return data

How I can make this more Pythonic?


texts:
I'm using cv::norm() to compute the L2 distance between row vectors in thousands of dimensions (at least 4096 dimensions). I'm using an AVX2 machine and icpc version 2017.

Since I'm computing this function millions of times, I need the possible most efficient version for this function and I highly doubt that cv::norm() exploits vectorization properly.

So I implemnted this function:

#include <opencv2/opencv.hpp>

float euclDist (const cv::Mat1f &first, const cv::Mat1f &second){
    float dist = 0;
    const float *firstp = first.ptr<float>(0);
    const float *secondp = second.ptr<float>(0);
    #pragma omp simd reduction(+:dist)
    for(size_t i=0; i<first.cols; i++)
        dist += std::pow(firstp[i]-secondp[i],2);
    return std::sqrt(dist);
}

int main (int argc, const char *argv[]){
    int codeSize = 4096;
    cv::Mat1f mat(1, codeSize);
    float low = 0;
    float high = 2.0;
     srand (0);
     cv::theRNG().state = cv::getTickCount() ;
    randu(mat, cv::Scalar(low), cv::Scalar(high));
    euclDist(mat, mat);
    return 0;
}

The example above is similar what the actually program does: it generates a row vector and it computes the distance with itself (i.e. 0). In the actual program generates a matrix and it randomly compute the distance between some rows. I don't think that I can get only that part of the code easily.

I already noticed an improvement w.r.t. cv::norm(), but scales badly when computing multiple distances in parallel. According to Intel VTune I fully use all the processors, but I get poor memory performance, as it shown from this general exploration analysis:

This is the result from: sudo lshw -short -C memory

H/W path       Device      Class          Description
=====================================================
/0/0                       memory         128KiB BIOS
/0/4/b                     memory         32KiB L1 cache
/0/4/c                     memory         256KiB L2 cache
/0/4/d                     memory         6MiB L3 cache
/0/a                       memory         32KiB L1 cache
/0/2a                      memory         12GiB System Memory
/0/2a/0                    memory         4GiB SODIMM DDR3 Synchronous 1600 MHz (0.6 ns)
/0/2a/1                    memory         DIMM [empty]
/0/2a/2                    memory         8GiB SODIMM DDR3 Synchronous 1600 MHz (0.6 ns)
/0/2a/3                    memory         DIMM [empty]

What I could do?


texts:
I have written a simple Caesar Cipher in Python in my efforts to learn a language that isn't C. It works much like any other Caesar implementation and takes various command line arguments to specify options such as the spacing of the output, whether to encrypt or decrypt the input, and whether or not to try and bruteforce the cipher.

This is my first ever Python program so I'm primarily looking to learn some best practices for the language as well as remove any inefficiencies or redundancies in my code.

Thanks!

import argparse
import re

def caesar(string, shift):
    output = ''
    for char in string:
        if char.isspace():
            output += ' '
        else:
            output += chr(((ord(char) - 65 + shift) % 26) + 65)
    return output

def main():
    parser = argparse.ArgumentParser(description = "Encrypt or decrpyt a string using the Caesar Cipher")

    parser.add_argument("--bruteforce", "--brute", "-b", help = "bruteforce mode", action = "store_true")
    parser.add_argument("--encrypt", "--enc", "-e", help = "encryption mode (default)", action = "store_true")
    parser.add_argument("--decrpyt", "--dec", "-d", help = "decryption mode", action = "store_true")
    parser.add_argument("--no-spacing", "--no-space", "-n", help = "no spacing in output (default)", action = "store_true")
    parser.add_argument("--preserve-spacing", "--preserve", "-p", help = "use same spacing as original string", action = "store_true")
    parser.add_argument("--shift", "-s", help = "value for the Caesar shift", type = int, choices = range(1, 26))
    parser.add_argument("--spacing", "-x", help = "specify the spacing in output", type = int)

    args = parser.parse_args()

    if args.bruteforce:
        bruteforce = True
    else:
        bruteforce = False
        shift = args.shift

    if args.decrpyt:
        shift = -shift

    if args.preserve_spacing:
        regex = re.compile('[^A-Z\s]')
    else:
        regex = re.compile('[^A-Z]')

    string = regex.sub('', input().upper())

    if args.spacing:
        string = ' '.join([string[i:i + args.spacing] for i in range(0, len(string), args.spacing)])

    if bruteforce:
        for shift in range(1, 26):
            print("%d: %s" %(shift, caesar(string, -shift)))
    else:
        print(caesar(string, shift))

if __name__ == "__main__":
    main()


texts:
Ran into this idea and I'm curious if it's possible.

I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a parameter and the algorithm will use the sorting function with it's own dynamic parameters. This is an example of what I'm trying to do:

class manyFunctions{
    int[] mergeSort(int[] myArray){
        ...work here;
        return sortedArray;
    }

    int[] otherSort(int[] myArray){
        ...work here;
        return sortedArray;
        }
}

class mainClass{
   public static void main(String[]Args){
      test(manyFunctions.mergeSort);
      test(manyFunctions.otherSort);

   }

     boolean test(function someSortFunction){
        int n; // number of trials
        for (int i=0; i<=n ; i++) {
        int[] A = generateArray() // another function I made
            if (isSorted(someSortFunction(A)) = false) {
                return false;
            }
        }
     return true;
 }

I can't figure out how to do this with the little bit I know about lambda expressions and function pointers. If it's possible, this technique would come in handy.


texts:
I'm working on a project in which I have a backend in nodejs and from there I need to call external APIs, those APIs require authentication token which is valid for 15 minutes. So if response status from external APIs is 401 then I need to generate a new token then call the request.

In my backend, I'm using request-promise package which doesn't provide any interceptor concept like axios, So tried creating my own mechanism, Below code is in typescript

class RequestHandler {

    private token: any = {

        promiseCreator: function () {
            return new Promise((resolve, reject) => {
                this.rejects.push(reject);
                this.resolves.push(resolve);
            });
        },
        rejects: [],
        resolves: [],
        v: null,
        get value() {
            return this.v;
        },
        set value(val) {
            this.v = val;
            if (val) {
                this.resolves.forEach((resolve: any) => resolve());
            } else {
                this.rejects.forEach((reject: any) => reject());
            }
            this.resolves = [];
            this.rejects = [];
        }

    };

    constructor() {
        this.authorize();
    }

    // Test Request
    public async test(reqBody) {

        const reqOptions = {
            dataType: "json",
            headers: {
                Authorization: `Bearer ${this.token.value}`
            },
            json: reqBody,
            method: "POST",
            url: "http://localhost:8080/test-async",
        };

        const { data } = await request(reqOptions);

        // on success return data
        if (data.status === "200") {
            return data;
        }

        // if authentication fails generate new token and then request again
        if (data.status === "401") {
            return await this.unAuthorizeRequestHandler(this.test.bind(this, reqBody));
        }

        // if status other than 200 and 401 then throw error
        throw new Error(data.message);

    }

    // To Get Authentication Token
    async authorize() {

        const reqOptions = {
            dataType: "json",
            json: {},
            method: "POST",
            url: "http://localhost:8080/auth",
        };

        const { token } = await request(reqOptions);
        this.token.value = token;

    }

    // handles retry logic
    async unAuthorizeRequestHandler(requestFunction: any) {

        if (this.token.value) {
            this.token.value = null;

            try {
                await this.authorize();
            } catch (err) {
                this.token.value = null;
                throw new Error(err.toString());
            }

        } else {
            await this.token.promiseCreator();
        }
        return await requestFunction();
    }

}

In the above code, unAuthorizeRequestHandler handles retry mechanism, it checks first if the token value is not null call authorize function to get the new token and make its value null, so when other requests come they will wait till authorize function sets new token ( it's done by promiseGenerator, it returns pending promise which will get resolve or reject when authorize function set token.value )

Please review my code guys


texts: Handler for jQuery DataTable search with filters and pagination

texts:
This AjaxCompound is invoked every time when the user types a key for search or click to sort. It contains 1million data 10 distinct rows by compound name. It takes 1.1 minutes and return only 1-5 KB data to search (general and column specific) or sort or pagination. Any way to reduce the execution time? Any wrong practice that I should correct in following code?

[OutputCache(Duration = 10, VaryByParam = "none")]
    public ActionResult AjaxCompound(JQueryDataTableParamModel param)
    {
        IQueryable<Compound> allCompounds = _context.Compounds.GroupBy(x => x.CompoundName).Select(x => x.FirstOrDefault());
        IEnumerable<Compound> filteredCompounds;
        if (!string.IsNullOrEmpty(param.sSearch))
        {
            filteredCompounds = allCompounds
                     .Where(c => c.CompoundName.Contains(param.sSearch)
                                 ||
                                 c.RI.Contains(param.sSearch)
                                  ||
                                 c.MolecularWeight.Contains(param.sSearch)
                                 ||
                                 c.MolecularFormula.Contains(param.sSearch)
                                 );
        }
        else
        {
            filteredCompounds = allCompounds;
        }

        var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
        Func<Compound, string> orderingFunction = (c => sortColumnIndex == 1 ? c.CompoundName :
                                                            sortColumnIndex == 2 ? c.RI :
                                                            sortColumnIndex == 3 ? c.MolecularFormula :
                                                            c.MolecularWeight);

        var name = Convert.ToString(Request["sSearch_1"]);
        var rI = Convert.ToString(Request["sSearch_2"]);
        var mW = Convert.ToString(Request["sSearch_4"]);
        var mF = Convert.ToString(Request["sSearch_3"]);
        //var areaPercent = Convert.ToString(Request["sSearch_6"]);

        if (!string.IsNullOrEmpty(name))
        {
            filteredCompounds = filteredCompounds.Where(c => c.CompoundName.Contains(name));

        }

        if (!string.IsNullOrEmpty(rI))
        {
            filteredCompounds = filteredCompounds.Where(c => c.RI.Contains(rI));

        }

        if (!string.IsNullOrEmpty(mF))
        {
            filteredCompounds = filteredCompounds.Where(c => c.MolecularFormula.Contains(mF));

        }

        if (!string.IsNullOrEmpty(mW))
        {
            filteredCompounds = filteredCompounds.Where(c => c.MolecularWeight.Contains(mW));

        }

        //if (!string.IsNullOrEmpty(areaPercent))
        //{
        //    filteredCompounds = filteredCompounds.Where(c => c.AreaPercent.Contains(areaPercent));

        //}

        var sortDirection = Request["sSortDir_0"];
        if (sortDirection == "asc")
            filteredCompounds = filteredCompounds.OrderBy(orderingFunction);
        else
            filteredCompounds = filteredCompounds.OrderByDescending(orderingFunction);

        var displayedCompounds = filteredCompounds
                           .Skip(param.iDisplayStart)
                           .Take(param.iDisplayLength).ToList();
        var result = from c in displayedCompounds
                     select new[] { c.PaperId, c.CompoundName, c.RI, c.MolecularWeight, c.MolecularFormula };
        return Json(new
        {
            sEcho = param.sEcho,
            iTotalRecords = allCompounds.Count(),
            iTotalDisplayRecords = filteredCompounds.Count(),
            aaData = result
        },
                         JsonRequestBehavior.AllowGet);
    }


texts: Vectorizing the product of an array of complex numbers

texts:
I am trying to write fast/optimal code to vectorize the product of an array of complex numbers.  In simple C this would be:

#include <complex.h>
complex float f(complex float x[], int n ) {
  complex float p = 1.0;
  for (int i = 0; i < n; i++)
    p *= x[i];
  return p;
}

However, gcc can't vectorize this and my target CPU is the AMD FX-8350 which supports AVX.  To speed it up I have tried:

typedef float v4sf __attribute__ ((vector_size (16)));
typedef union {
  v4sf v;
  float e[4];
} float4;
typedef struct {
  float4 x;
  float4 y;
} complex4;
static complex4 complex4_mul(complex4 a, complex4 b) {
  return (complex4){a.x.v*b.x.v -a.y.v*b.y.v, a.y.v*b.x.v + a.x.v*b.y.v};
}
complex4 f4(complex4 x[], int n) {
  v4sf one = {1,1,1,1};
  complex4 p = {one,one};
  for (int i = 0; i < n; i++) p = complex4_mul(p, x[i]);
  return p;
}

Can this code be improved for AVX and is it as fast as it can get?


texts:
In a WPF application I have the following event handler for PreviewTextInput event in ComboBox control. The main purpose of this code is to select an item in ComboBox via pressing a letter key. There is duplicated logic in this code and I want it removed.

private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var comboBox = sender as ComboBox;
    if (!comboBox.IsDropDownOpen)
    {
        return;
    }

    if (!comboBox.IsEditable || !comboBox.IsReadOnly)
    {
        return;
    }

    foreach (var item in comboBox.Items)
    {
        if (item == null)
        {
            continue;
        }

        var textSearch = TextSearch.GetTextPath(comboBox);

        var stringItem = item as string;
        if (stringItem != null)
        {
            if (stringItem.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
            {
                SelectItemInComboBox(comboBox, item);
                break;
            }

            continue;
        }

        var dependencyObjItem = item as DependencyObject;
        if (dependencyObjItem != null)
        {
            var textMember = TextSearch.GetText(dependencyObjItem);
            if (!string.IsNullOrEmpty(textMember))
            {
                var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);
                var textValue = selectorFunc(dependencyObjItem);

                if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
                {
                    SelectItemInComboBox(comboBox, item);
                    break;
                }

                continue;
            }
        }

        if (!string.IsNullOrEmpty(textSearch))
        {
            var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);
            var textValue = selectorFunc(item);

            if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
            {
                SelectItemInComboBox(comboBox, item);
                break;
            }
        }
    }

    e.Handled = true;
}

private void SelectItemInComboBox(ComboBox comboBox, object item)
{
    var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
    comboBoxItem.IsSelected = true;
}


texts:
This is my code to print letter 'F' with nested loop 2d array. Are there changes that could be made in it to make it look better or more efficient?

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

        for(int j=0;j<=4;j++){

            array[i][j]='*';
            if ( array[1][1]=='*' || array[1][2]=='*' || array[1][3]=='*' || array[1][4]== '*'||
                 array[3][1]=='*' || array[3][2]=='*' || array[3][3]=='*' || array[3][4]== '*'
               ||array[4][1]=='*' || array[4][2]=='*' || array[4][3]=='*' || array[4][4]== '*')
                {
                array[i][j]=' ';
            }
          }
        }
        for (int i=0;i<=4;i++){
          for(int j=0;j<=4;j++){
            System.out.print(" "+array[i][j]);
        }
            System.out.println("\n");
       }


texts: Character class with name, gender, and inventory list

texts:
I am trying to create a class to test my understanding, and it takes an ArrayList as parameter. The decision of choosing an ArrayList is because it does not have a fixed size and I can add more elements to it later.

I came out with this implementation:

public class Character {

    private String name;
    private char gender;
    private List<String> inventory = new ArrayList<String>();

    public Character(String name, char gender, List<String> inventory) {
        this.name = name;
        this.gender = gender;
        this.inventory.addAll(inventory); // Is this a good idea?
    }

    public String getName() {
        return name;
    }

    public char getGender() {
        return gender;
    }

    public List<String> getInventory() {
        return inventory;
    }

}

And in the main class:

public class Main {

    public static void main(String[] args) {

        Character coolKid = new Character("Cool Kid", 'f',
                                          Arrays.asList("just", "testing"));

        System.out.println(coolKid.getInventory());
        // returns [just, testing]

    }
}

My main concern is "dynamically" adding elements to the ArrayList when instantiating, as well as using addAll in the constructor, and List as the type for the inventory argument in the constructor.

Is there a better way to accomplish this?


texts: Extension method to run any async method synchronously

texts:
Sometimes I need to call async code from a synchronous method.  This leads to repetition in code to wait for the task to complete, then ensure that the expected exception is thrown instead of an aggregate exception (assuming there's only 1 exception returned, as is the case unless we're iterating through a list / something like that; in which case we preserve the AggregateException as that's then expected by the handling code).

To avoid repetition, would a helper function called and defined as below be appropriate?  Does something like this already exist in the framework?

Example calling code:

bool MySyncMethod (bool throwException)
{
    var task = MyAsyncMethod(throwException);
    return task.WaitResultUnwrapException<bool>();
    //or even
    //return MyAsyncMethod(throwException).WaitResultUnwrapException<bool>();
}
async Task<bool> MyAsyncMethod (bool throwException)
{
    if (throwException)
        throw new ArgumentException(nameof(throwException));
    return await Task.Run(() => true);
}

Example extension method:

using System;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;

namespace MyCompany.Threading.Tasks
{
    public static class TaskExtensions
    {
        public static T WaitResultUnwrapException<T>(this Task<T> task)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));
            try
            {
                task.Wait();
                return task.Result;
            }
            catch (AggregateException es)
            {
                if (es.InnerExceptions.Count == 1) {
                    var e = es.InnerExceptions[0];
                    ExceptionDispatchInfo.Capture(e).Throw();
                }
                throw;
            }
        }
        public static void WaitResultUnwrapException(this Task task)
        {
            if (task == null) throw new ArgumentNullException(nameof(task));
            try
            {
                task.Wait();
            }
            catch (AggregateException es)
            {
                if (es.InnerExceptions.Count == 1) {
                    var e = es.InnerExceptions[0];
                    ExceptionDispatchInfo.Capture(e).Throw();
                }
                throw;
            }
        }
    }


texts:
I have been trying to implement parallel merge sort in Scala. My current implementation is about as fast as .sorted, but I have no idea what would be the right aproach to parallelize it.

Input file with 1.2M integers:

1.333580 seconds (my implementation)
1.439293 seconds (.sorted)

How should I parallelize this?

object Mergesort extends App
{

//=====================================================================================================================
// UTILITY
  implicit object comp extends Ordering[Any] {
    def compare(a: Any, b: Any) = {
      (a, b) match {
        case (a: Int, b: Int)       => a compare b
        case (a: String, b: String) => a compare b
        case _                      => 0
      }
    }
  }

//=====================================================================================================================
// MERGESORT

  val THRESHOLD = 30

  def inssort[A](a: Array[A], left: Int, right: Int): Array[A] = {
    for (i <- (left+1) until right) {
      var j = i
      val item = a(j)
      while (j > left && comp.lt(item,a(j-1))) {
        a(j) = a(j-1)
        j -= 1
      }
      a(j) = item
    }
    a
  }

  def mergesort_merge[A](a: Array[A], temp: Array[A], left: Int, right: Int, mid: Int) : Array[A] = {
    var i = left
    var j = right
    while (i < mid) { temp(i) = a(i);   i+=1;       }
    while (j > mid) { temp(i) = a(j-1); i+=1; j-=1; }

    i = left
    j = right-1
    var k = left
    while (k < right) {
      if (comp.lt(temp(i), temp(j))) { a(k) = temp(i); i+=1; k+=1; }
      else                           { a(k) = temp(j); j-=1; k+=1; }
    }
    a
  }

  def mergesort_split[A](a: Array[A], temp: Array[A], left: Int, right: Int): Array[A] = {
    if (right-left == 1) a

    if ((right-left) > THRESHOLD) {
      val mid = (left+right)/2
      mergesort_split(a, temp, left, mid)
      mergesort_split(a, temp, mid, right)
      mergesort_merge(a, temp, left, right, mid)
    }
    else
      inssort(a, left, right)
  }

  def mergesort[A: ClassTag](a: Array[A]): Array[A] = {
    val temp = new Array[A](a.size)
    mergesort_split(a, temp, 0, a.size)
  }
}


texts:
I'm trying to implement pbkdf2 in Python 2.7/3.4 without needing the pbkdf2 module. (I'm also trying to avoid using classes.)

Any insight would be appreciated:

from binascii import hexlify, unhexlify
import hmac, struct, hashlib, sys

is_python2 = True if sys.version_info.major == 2 else False

def pbkdf_two(passwd, salt, iters=2048, keylen=64, digestmod=hashlib.sha512):
    """
    >>> hexlify(pbkdf_two(b'All n-entities must communicate with other n-entities via n-1 entiteeheehees', unhexlify('1234567878563412'), 500, 16, hashlib.sha1))
    '6a8970bf68c92caea84a8df285108586'
    """
    dgsz = digestmod().digest_size if callable(digestmod) else digestmod.digest_size
    if keylen is None: keylen = dgsz
    # Helper function which copies each iteration for h, where h is an hmac seeded with password
    def pbhelper(h, salt, itercount, blocksize):
        def prf(h, data):
            hm = h.copy()
            hm.update(data)
            return hm.digest()
        U = prf(h, salt + struct.pack('>i', blocksize))
        T = U
        for j in range(2, itercount+1):
            U = prf(h, U)
            T = "".join([chr( ord(x) ^ ord(y) ) for (x, y) in zip( T, U )]) \
                  if is_python2 else bytes([x ^ y for (x, y) in zip(T, U)])    # XORing
        return T
    L = int(keylen/dgsz) # L - number of output blocks to produce
    if keylen % dgsz != 0: L += 1
    h = hmac.new(key=passwd, msg=None, digestmod=digestmod )
    T = b""
    for i in range(1, L+1):
        T += pbhelper(h, salt, iters, i)
    return T[:keylen]


texts:
I just figured out Project Euler problem #12. I'm still really new to Python, so I'm putting my code up here in the hopes that someone will be able to give me some tips for optimizing my code to run faster. It took an incredibly long time to run, so I'm hoping that someone will be able to give me pointers.

If anyone is willing, would you mind looking over my solution and letting me know how I can improve on it, either through optimization or style?

The link to the problem is here: Project Euler #12

run = True
p = 2
numberInUse = 3

def checkDivisors(number):
    numberOfDivisors = 0
    for x in range(1, int(number+1)):
        if number%x ==0:
            numberOfDivisors += 1
    return(numberOfDivisors)

while run == True:
    if checkDivisors(numberInUse) > 500:
        run = False
        print(numberInUse, "is the answer!")
    else:
        p += 1
        numberInUse += p


texts:
The mall management is trying to figure out what was the busiest
  moment in the mall in the last year. Each data entry includes a
  timestamp (seconds in Unix Epoch format), an amount of people and
  whether they entered or exited.

  Example:

{ time: 1440084737,  count: 4,  ActionType: "Entry" }

How can I refactor this code?

public class MallTimeWithMaximumPeople
{
    public class DataComparision implements Comparator<EntryData>
    {
        @Override
        public int compare(EntryData data1, EntryData data2)
        {
           return (data1.epochTime - data2.epochTime);
        }
    }

    public class EntryData
    {
       private int count, epochTime;
       private ActionType actionType;

    public EntryData(int count, int epochTime, ActionType actionType)
    {
        this.count = count;
        this.epochTime = epochTime;
        this.actionType = actionType;
    }

    public int getCount()
    {
        return count;
    }

    public long getEpochTime()
    {
        return epochTime;
    }

    public ActionType getActionType()
    {
        return actionType;
    }
  }

  public enum ActionType
  {
     ENTRY, EXIT;
  }

  public long[] getTimeWithMaximumPeople(List<EntryData> data)
  {
      long[] result = { 0, 0, 0 };

      if (data == null || data.size() == 0)
        return result;

      Collections.sort(data, new MallTimeWithMaximumPeople.DataComparision());

      int dataSize = data.size();
      int count = 0, maxCount = 0;

      for (int i = 0; i < dataSize; i++)
      {
        EntryData currentData = data.get(i);

        if (currentData.getActionType() == ActionType.ENTRY)
            count += currentData.getCount();
        else
            count -= currentData.getCount();

        if (i < dataSize - 1 && currentData.getEpochTime() == data.get(i + 1).getEpochTime())
            continue;

        if (count > maxCount)
        {
            maxCount = count;
            result[0] = currentData.getEpochTime();

            if (i < dataSize - 1)
                result[1] = data.get(i + 1).getEpochTime();
            else
                result[1] = data.get(i).getEpochTime();

            result[2] = maxCount;
        }
    }

    return result;
  }

  public static void main(String args[])
  {
      MallTimeWithMaximumPeople instance = new MallTimeWithMaximumPeople();

      List<EntryData> data = new ArrayList<EntryData>();
      EntryData data1 = instance.new EntryData(100, 0, ActionType.ENTRY);
      EntryData data3 = instance.new EntryData(1, 1, ActionType.EXIT);
      EntryData data2 = instance.new EntryData(20, 2, ActionType.EXIT);
      data.add(data1); data.add(data2); data.add(data3);

      long[] result = instance.getTimeWithMaximumPeople(data);
  }
}


texts:
I'm trying to get my head in the Scala game, and would welcome feedback on the following code, which produces a table from data.

class TabulatorTest extends FunSuite with ShouldMatchers {

  test("format") {
    Tabulator.format(List(
      List("head1", "head2", "head3"),
      List("one", "two", "three"),
      List("four", "five", "six"))) should be ("""
+-----+-----+-----+
|head1|head2|head3|
+-----+-----+-----+
|  one|  two|three|
| four| five|  six|
+-----+-----+-----+
""".trim)
  }

  test("format empty") {
    Tabulator.format(List()) should be ("")
    Tabulator.format(List(List())) should be ("""
++
||
++
++
""".trim)
  }

  test("uneven rows") {
    try {
      Tabulator.format(List(
        List("head1", "head2", "head3"),
        List("one", "two")))
      fail()
    } catch {
      case e: IllegalArgumentException =>
    }
  }
}

object Tabulator {

  def format(table: Seq[Seq[Any]]) = table match {
    case Seq() => ""
    case _ =>
      val cellSizes = for (row <- table) yield
        (for (cell <- row) yield
          if (cell == null) 0 else cell.toString.length)
      val colSizes = for (col <- cellSizes.transpose) yield col.max
      val rows = for (row <- table) yield formatRow(row, colSizes)
      formatRows(rowSeparator(colSizes), rows)
  }

  def formatRow(row: Seq[Any], colSizes: Seq[Int]) = {
    val cells = (for ((item, size) <- row.zip(colSizes)) yield
      if (size == 0) "" else ("%" + size + "s").format(item))
    cells.mkString("|", "|", "|")
  }

  def formatRows(rowSeparator: String, rows: Seq[String]): String = (
    rowSeparator ::
    rows.head ::
    rowSeparator ::
    rows.tail.toList :::
    rowSeparator ::
    List()).mkString("\n")

  private def rowSeparator(colSizes: Seq[Int]) =
    colSizes map { "-" * _ } mkString("+", "+", "+")
}


texts: Duplicate like a weapon, arrays like heaven

texts:
Challenge:

  Find the duplicated entry.

Specifications:

  Your program should accept as its first argument a path to a filename.
  Each line in this file is one test case.

  Each line begins with a positive integer(N), the size of the array,
  then a semicolon followed by a comma separated list of positive numbers
  which range from 0 to N-2, inclusive.

  The array contains exactly one duplicated entry which appears exactly twice.
  Print out the duplicated entry, each one on a new line.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayAbsurdity {
    public static void main(String[] argument) throws FileNotFoundException {
        Scanner input = new Scanner(new File(argument[0]));
        String[] args;

        while (input.hasNextLine()) {
            args = input.nextLine().split(";");
            printDuplicate(args[0], args[1].split(","));
        }
    }

    private static void printDuplicate(String size, String[] nums) {
        boolean[] absurd = new boolean[Integer.parseInt(size)];
        int value;
        Arrays.fill(absurd, false);

        for (int i = 0; i < absurd.length; i++) {
            value = Integer.parseInt(nums[i]);

            if (absurd[value]) {
                System.out.println(value);
                break;
            }

            absurd[value] = true;
        }
    }
}

Sample Input:

  5;0,1,2,3,0
  20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14

Sample Output:

  0
  4

I usually write two auxiliary methods, but this time I did some of the work within main's loop, and only wrote one print method. Does the print method do too much? With and without considering its name.

I was going to use two arrays and/or two loops at first, but considering all that was given the question's purpose surely is to create the most efficient solution and thanks to learning of Arrays.fill on one of my previous answers, courtesy of @rolfl, I came up with this. Is it optimal?

For anyone interested, I maintain my current implementation here, and the implementation of the accepted answer here, also the source for the title since a few people asked in chat.


texts: Memory release after joblib.Parallel [python]

texts:
Stuck with the issue with memory consumption - after running joblib's Parallel, deleting results and gc.collect() -ing I still have increased memory (checking by htop for process line). Found no way to free memory back. To broaden yangqch answer I use such code to isolate memory for parallel computations:

Imports -

import multiprocessing as mp
n_cores = mp.cpu_count()
import time
import datetime
from sklearn.externals.joblib import Parallel, delayed
import sklearn
from functools import partial
import pickle

joblib progress bar -

class BatchCompletionCallBack(object):
    # Added code - start
    global total_n_jobs
    global jobs_start_time
    # Added code - end
    def __init__(self, dispatch_timestamp, batch_size, parallel):
        self.dispatch_timestamp = dispatch_timestamp
        self.batch_size = batch_size
        self.parallel = parallel

    def __call__(self, out):
        self.parallel.n_completed_tasks += self.batch_size
        this_batch_duration = time.time() - self.dispatch_timestamp

        self.parallel._backend.batch_completed(self.batch_size,
                                           this_batch_duration)
        self.parallel.print_progress()
        # Added code - start
        progress = self.parallel.n_completed_tasks / total_n_jobs
        elapsed = int((time.time() - jobs_start_time) / self.parallel.n_completed_tasks * (total_n_jobs - self.parallel.n_completed_tasks))
        print(
            "\r[{:50s}] {:.1f}% - Elapsed time {} ".format(
                '#' * int(progress * 50)
                , progress*100
                , datetime.timedelta(seconds=elapsed))
            , end="", flush=True)
        if self.parallel.n_completed_tasks == total_n_jobs:
            print('\n')
        # Added code - end
        if self.parallel._original_iterator is not None:
            self.parallel.dispatch_next()

sklearn.externals.joblib.parallel.BatchCompletionCallBack = BatchCompletionCallBack

Parallel wrapper -

def parallel_wrapper(func, *args, **kwargs):
    global total_n_jobs, jobs_start_time
    total_n_jobs = len(args[0])
    jobs_start_time = time.time()

    if kwargs:
        mapfunc = partial(func, **kwargs)
    else:
        mapfunc = func

    with open('file.pkl', 'wb') as file:
        pickle.dump(Parallel(n_jobs=n_cores)(map(delayed(mapfunc), *args)), file)
    print('Operating time - ', datetime.timedelta(seconds=int(time.time() - jobs_start_time)))

Class to use in 'with' construction -

class isolate:
    def __init__(self, func):
        self.func = func

    def __enter__(self):
        return self

    def run(self, func, *args, **kwargs):
        self.p = mp.Process(target=self.func, args=(func, *args), kwargs=kwargs)
        self.p.start()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.p.join()

Example -

def dummy(i, keyword_argument=None):
    return (i.shape, keyword_argument)

import numpy as np
tmp = np.ones((5,5))

with isolate(parallel_wrapper) as isolated:
    isolated.run(dummy, [tmp, tmp], keyword_argument=2)

with open('file.pkl', 'rb') as file:
    tmp = pickle.load(file)

tmp

import importlib
importlib.reload(sklearn.externals.joblib.parallel)

So questions are:

is there an easier way
how to make local variable 'total_n_jobs' from 'parallel_wrapper' viewable in 'BatchCompletionCallBack' without 'global'
any improvements


texts: Get the next bigger number by rearranging the digits of the input integer

texts:
from itertools import permutations
def next_bigger(n):
    nlist = list(str(n))
    perm = permutations(nlist,len(str(n)))
    perm = set(perm)
    listofperm = []
    nlist = int("".join(nlist))
    for x in perm:
        form = int("".join(x))
        if form < nlist:
            continue
        else:
            listofperm.append(form)
    listofperm = sorted(listofperm)

    if (listofperm.index(n) + 1) == len(listofperm):
        indexofn = listofperm.index(n)
    else:
        indexofn = listofperm.index(n) + 1
    return listofperm[indexofn]

I'm trying to get the next bigger number by rearranging the digits of n but my code is very inefficient can you suggest ways to make my code more efficient and faster?
Inputs would be any integer.


texts: Have I coded this small object grouping script Pythonically?

texts:
I have a small script that takes a list of objects from an SQL table and groups them if the date-time on the object has less than 60 second difference with the last object.

It does this by converting the date-time to epoch and then subtracting the epoch of the previous object from the epoch of the current object. The code works but I feel as if it is too convoluted for such a simple task.

rows = cur.fetchall() #gets all the objects from table

source = []
list1 = []
old_epoch = 1404413062 #I use the same epoch time as the first object but this isn't very pythonic

for a in rows:
    date_time = a[12] #gets date_time

#strips date_time with regex to match the proper pattern format
#sample date_time from db "2014-07-07 11:10:18.867024-04"
    date_time = re.match(r'^.*?\.', date_time).group(0)
    date_time = date_time.replace(".", "")
    pattern = '%Y-%m-%d %H:%M:%S'

    #converts date_time to epoch
    epoch = int(time.mktime(time.strptime(date_time, pattern)))

    #had to add this small part to force the iterator to append the last chunk since no new epoch_time to compare and get difference as difference would be zero
    if a == rows[-1]:
        source.append(a[11])
        list1.append(source)

    else:
        if epoch - old_epoch < 60:
            source.append(a[11])

        else:
            list1.append(source)
            source = []
            source.append(a[11])

    old_epoch = epoch

EDIT: Updated this post for those asking what it does. It returns a list of categorized groups  based on the timestamp as displayed below when printing out list1. I replaced the actual objects with only their timestamp property for readability purposes. :

['2014-07-07 06:21:51.011377-04', '2014-07-07 06:21:51.347373-04', '2014-07-07 06:21:51.678615-04']
['2014-07-07 06:26:54.01491-04', '2014-07-07 06:26:54.347479-04', '2014-07-07 06:26:54.671736-04']
['2014-07-07 06:31:57.107409-04', '2014-07-07 06:31:57.437156-04', '2014-07-07 06:31:57.804104-04']
['2014-07-07 06:37:00.178693-04', '2014-07-07 06:37:00.509359-04', '2014-07-07 06:37:00.828529-04']
['2014-07-07 06:42:03.268083-04', '2014-07-07 06:42:03.594742-04', '2014-07-07 06:42:03.921035-04']
['2014-07-07 06:47:06.389844-04', '2014-07-07 06:47:06.717987-04', '2014-07-07 06:47:07.035479-04']
['2014-07-07 06:52:09.516735-04', '2014-07-07 06:52:09.846621-04', '2014-07-07 06:52:10.171093-04']
['2014-07-07 06:57:12.623216-04', '2014-07-07 06:57:12.952604-04', '2014-07-07 06:57:13.278989-04']


texts: Longest palindrome code in C# takes time out on LeetCode

texts:
I like to request a review of the code below, which is my attempt at answering the question here on LeetCode site. The code passes 43 tests, but it times out on the next one. I copied and ran the test on my machine using visual studio and it seems to give me an answer. I wonder if there is something about the site LeetCode that I should know like a config setting somewhere.

Regardless the problem asks to find the longest palindrome in a string. I have seen and read other posts about this problem, like this one, but I would really like to see answers in C#, because I originally converted my code from Java to C# and found out about the slight difference in the .Substring() method between the two languages. I tried to address it by creating my own method, and wonder if the time out is due to this adjustment.

private static string LongestPalindrome(string s)
{
    int length = s.Length;
    if (s.Length < 2 || s == null)
    {
        return s;
    }
    Boolean[,] isPalindrome = new Boolean[length, length];
    int left = 0;
    int right = 0;
    for (int j = 0; j < length; j++)
    {
        for (int i = 0; i < j; i++)
        {
            Boolean isInnerWordPalindrome = isPalindrome[i + 1, j - 1] || j - i <= 2;
            if (s.ElementAt(i) == s.ElementAt(j) && isInnerWordPalindrome)
            {
                isPalindrome[i, j] = true;
                if (j - i > right - left)
                {
                    left = i;
                    right = j;
                }
            }
        }
    }
    return JavaStyleSubstring(s, left, right + 1);
}

private static string JavaStyleSubstring(string s, int beginIndex, int endIndex)
{
    // simulates Java substring function
    int len = endIndex - beginIndex;
    return s.Substring(beginIndex, len);
}


texts:
This is a problem from here where you're given a magic die, and the objective is to find the minimum number of dice throws (hops) to go from the start point to the end of the board, and win the game.

I am representing the board as a matrix as follows. If the value at a cell is 0, you could go to any of the next 6 places using your magic die. If the value at a cell is non-zero, you compulsorily have to go to the cell that is represented by the value (think there is a snake or ladder at that cell which is taking you to the cell represented by the value). For example, if you land at (0,1), you are forced to go to 11, which is (2,1).

int[][] a = {
                     {0,11,0,0,0},
                     {0,0,0,0,0},
                     {0,0,1,23,0},
                     {0,0,4,0,0},
                     {10,0,0,0,0}
        };

Background

I have implemented this using Depth First Search / Recursion. Someone who reviewed my code said this solution is incorrect, and this problem is not a good candidate for Depth First Search / Recursion, and can only be done by using Breadth First Search, the reason being that, there are cells which are interdependent on each other. For example, this is a valid path, (0,0) -> (0,1) -> (2,1) -> (2,2) -> (0,1). However, you are trying to find the minimum number of hops from each cell, and here, (0,1) depends on (2,1) which in turn depends on (0,1).

I am not completely sure this is a valid argument, since if you go from (0,1) to (2,1), there is no reason, to go back to (0,1) since it anyways cannot be the shortest path, since if you go back, you're basically going back to a point you previously were in except that you have made two more hops. So, this is not useful, and I have handled this by using a visited[][] state to capture that.

public class SnakesAndLadders {

    /**
     * @param args
     */
    public static void main( String[] args ) {
        // TODO Auto-generated method stub
        int[][] a = {
                     {0,11,0,0,0},
                     {0,0,0,0,0},
                     {0,0,1,23,0},
                     {0,0,4,0,0},
                     {10,0,0,0,0}
        };
        boolean[][] visited = new boolean[a.length][a[0].length];

        System.out.println( shortestPath( a, 0, 0, visited ) );
    }

    static int shortestPath(int[][] a, int i, int j, boolean[][] visited)
    {
        if(i >= a.length || j >= a[0].length)
            return Integer.MAX_VALUE-100;

        if( i == a.length-1 && j == a[0].length-1)
            return 0;

        if(visited[i][j] == true )
            return Integer.MAX_VALUE-100;

        visited[i][j] = true;
        int min = Integer.MAX_VALUE-100;
        if(a[i][j] == 0)
        {
            int pos = i*a[0].length + j;
            for(int k = pos+1;k<=pos+6;k++)
            {
                min = Math.min( min, shortestPath( a, k/a[0].length, k%a[0].length, visited ) + 1) ;
            }

        }
        else
            return shortestPath( a, a[i][j]/a[0].length, a[i][j]%a[0].length, visited ) + 1;

        visited[i][j] = false;
        return min;
    }
}

Please review my code, and give me your thoughts on whether this would work, or if depth first search cannot be used for this class of problems where you could go back to a previous recursion state.


texts:
I have created a piece of code for a live pagination, but I don't like the code. It works it does the job, but I guess I could done it better.

$('.show-content').livequery(function() {
    $(this).find('.page-me:not(:first)').hide();
    var totalPage = $(this).find('.page-me').length;

    for (var i = 0; i <= totalPage - 1; i++) {
        $('.modal-pagination').append('Page ' + (i + 1) + '')
    }

    $('.modal-pagination a').live('click', function() {
        var thePag = $(this).attr('id');

        $('.show-content').find('.page-me').hide();
        $('.show-content').find('.page-me:nth(' + thePag + ')').show();

        return false;
    });
});


texts: Populate a networkx graph with tuples of varying lengths

texts:
I've got a list with tuples of variable length containing nodes, out of which I want to build a network:

node_list = [("one", "two"), ("eins", "zwei", "drei"),
             ("un", "deux", "trois", "quattre"), ("two", "zwei", "deux")]

Each tuple represents a subgroup in the network. I want to add each node with edges to any other member of the same tuple.

It is straightforward to use .add_edges_from(), which only expects a tuple with two nodes. For a tuple with three entries one would have to write .add_edges_from(("eins", "zwei"), ("eins", "drei"), ("zwei", "drei")). Tuples with four members require even more code.

Now I am looking for the most efficient way to populate a network given a list like node_list. My idea is:

import networkx as nx

G = nx.Graph()
for node_tuple in node_list:
    for node1 in node_tuple:
        for node2 in node_tuple:
            G.add_edge(node1, node2)

It's probably very inefficient because it sees every node twice and also adds self-loops.


texts:
I asked a similar question yesterday and got a brilliant answer, but unsure how I could adapt these methods.

The methods perform a BFS on a state and then store the values in a multi-dimensional array.

You can see that the code is repeating itself, just with different array dimensions.

Method 1:

    public void bfs2(int[][][] three, PDB15Tile.State s, int[] storedNums, String fileName) throws IOException {
        Queue<PDB15Tile.State> q = new LinkedList<>();
        int[] positions = new int[storedNums.length];
        for (int i = 0; i < storedNums.length; i++) {
            positions[i] = getPatternPosition(storedNums[i], s.getState());
        }
        three[positions[0]][positions[1]][positions[2]] = 0;
        q.add(s);
        PDB15Tile.State current;
        while (!q.isEmpty()) {
            current = q.poll();
            // System.out.println(Arrays.toString(current.getState()));
            for (PDB15Tile.State neighbour : current.findNeighbours2()) {
                // System.out.println(Arrays.toString(neighbour.getState()));
                for (int i = 0; i < storedNums.length; i++) {
                    positions[i] = getPatternPosition(storedNums[i], neighbour.getState());
                }
                if (three[positions[0]][positions[1]][positions[2]] == 0) {
                    three[positions[0]][positions[1]][positions[2]] = neighbour.getH();
                    q.add(neighbour);
                }

            }

        }
        serializeArrayToFile(three, fileName);
    }

Method 2:

    public void bfs2(int[][][][][][] six, PDB15Tile.State s, int[] storedNums, String fileName) throws IOException {
        Queue<PDB15Tile.State> q = new LinkedList<>();
        int[] positions = new int[storedNums.length];
        for (int i = 0; i < storedNums.length; i++) {
            positions[i] = getPatternPosition(storedNums[i], s.getState());
        }
        six[positions[0]][positions[1]][positions[2]][positions[3]][positions[4]][positions[5]] = 0;
        q.add(s);
        PDB15Tile.State current;
        while (!q.isEmpty()) {
            current = q.poll();
            // System.out.println(Arrays.toString(current.getState()));
            for (PDB15Tile.State neighbour : current.findNeighbours2()) {
                // System.out.println(Arrays.toString(neighbour.getState()));
                for (int i = 0; i < storedNums.length; i++) {
                    positions[i] = getPatternPosition(storedNums[i], neighbour.getState());
                }
                //System.out.println(six[positions[0]][positions[1]][positions[2]][positions[3]][positions[4]][positions[5]]);
                if (six[positions[0]][positions[1]][positions[2]][positions[3]][positions[4]][positions[5]] == 0) {
                    six[positions[0]][positions[1]][positions[2]][positions[3]][positions[4]][positions[5]] = neighbour.getH();
                    q.add(neighbour);
                }

            }

        }
        serializeArrayToFile(six, fileName);
    }

How do I determine the number of dimensions of the object that is passed in and then manipulate the array accordingly?


texts:
I'm working on a biometric matching system and I would like to have few suggestions regarding vectorizing the following code:

% tpol and ipol
% column 1: x co-ordinate of the feature
% column 2: y co-ordinate of the feature
% column 3: angle orientation
% column 4: type of feature

ref_points=size(tpol,1); %number of rows=number of reference image points
   in_points=size(ipol,1); %number of rows=number of input image points
   radsize=7*ones(ref_points,1); %Radius size
   angsize=11* ones(ref_points,1); %Angle size
   radlow=-radsize./2;  % Lower Radius
   radhigh=radsize./2; % Upper Radius
   anglow=-angsize./2;  % Lower Angle
   anghigh=angsize./2; % Upper Angle
   epsillon=10;
   mscore=0; % initializing the matching score

   for i=1:ref_points
      for j=1:in_points
        rdiff=tpol(i,1)-ipol(j,1);    % Difference between the x-coordinate
        ediff=tpol(i,2)-ipol(j,2);      % Difference between the y-coordinate
        thetadiff=tpol(i,3)-ipol(j,3);   %Difference between the orientation
        if ((radlow(i) < rdiff) && (rdiff < radhigh(i)) && (anglow(i) < ediff) && ...
            (ediff < anghigh(i)) && (abs(thetadiff) < epsillon) && ...
            (tpol(i,4)==ipol(j,4)))
            mscore=mscore+1;
            tpol(i,4)=3; %Change type of the feature to know that the line was used
        end
      end
    end
  end

ipol and tpol are the input image and reference image points respectively. They are both a matrix of size (A x 4) each, A being the number of features detected in each image.

I asked this question on Mathworks for which I received the following answer:

    r = [-3.5 3.5];  % Lower Radius and Upper Radius
    a = [-5.5 5.5];  % Lower Angle and Upper Angle
    epsillon=10;

    % Vectorized computation of rdiff,ediff,thetadiff i.e. x,y-co-ordinate
    % and orientation
    pol = bsxfun(@minus,tpol,permute(ipol,[3 2 1]));
    p = all([bsxfun(@gt,pol(:,1:2,:),[r(1),a(1)]) & bsxfun(@lt,pol(:,1:2,:),[r(2),a(2)]),...
     pol(:,3,:) < ep, pol(:,4,:) == 0],2);
    mscore = nnz(p);
    tpol(any(p,3),4) = 4;

I checked the mscore received from the original code and verified it with the solution provided by plugging in one "if condition" at a time. All the "if conditions" provided me the same mscore except for:

if ((tpol(i,4)==ipol(j,4))

  and

p= all ([pol(:,4,:) == 0],2);

It would be very helpful if someone could help me out with this. The for loop takes a long time when the points detected are many.

The input data can be downloaded from Google Drive


texts:
I made an example for learning Dependency inversion principle in JavaScript OOP programming .

String.prototype.ucfirst = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function textHandler(){

    this.printRedbox = function( ){
        return ' Red Box text ';
    }

    this.printBluebox = function( ){
        return ' Blue Box text ';
    }
};

function htmlHandler( handler ){

    var block = [],
        box  = document.getElementById('container');

    this.boxContentHandler =  handler ;

    this.setType = function( handler ){
        this.boxContentHandler = handler
    };

    this.appendBlock = function( html ){

        block.push( html );
        box.innerHTML = block.join('');
    };

    this.printBox = function ( action ){

        var title = this.printTitle() ,
            text  = this.boxContentHandler[ 'print'+ action.ucfirst() ](),
            html  = '
'
                        +   title + text
                    +'
' ;

        this.appendBlock( html );
    };

    this.printTitle = function( ) {
            return 'Title ' + block.length + '
';
    };
};

Here I am doing the action handling part

var htmlHandle = new htmlHandler(  new textHandler()  );

document.getElementById('bluebox').addEventListener( 'click', function(){
    htmlHandle.printBox(  this.id );
},false );

document.getElementById('redbox').addEventListener( 'click', function(){
    htmlHandle.printBox(  this.id );
},false );

I would like to know, is there a way to make it better. Did I miss anything here ?


texts:
How can I improve the following working SQL statement for better performance and consistency?

SELECT if(roll is null,0,roll) as roll,
       if(cpapername is null,0,cpapername) as compulsory,
       if(corepapername is null,0,corepapername) as Core,
       if(e1papername is null,0,e1papername) as Elective1,
       if(e2papername is null,0,e2papername) as Elective2
       FROM(
       Select student.univ_roll as roll, student.name as name, student.rollno as rollno,
       (CASE WHEN student.compulsory = paper.subject
         THEN (paper.paper_name) END) AS cpapername,
       (CASE WHEN student.core= paper.subject
         THEN (paper.paper_name) END) AS corepapername,
       (CASE WHEN student.elective_I= paper.subject
         THEN (paper.paper_name) END) AS e1papername,
       (CASE WHEN student.elective_II= paper.subject
         THEN (paper.paper_name) END) AS e2papername
        FROM student, paper WHERE student.semester='First'
        AND student.batch='2014' AND student.class='BSc'
        AND student.semester=paper.semester AND student.batch=paper.batch
        AND student.class=paper.class  AND student.regd='1')r

Any suggestions and alternative solution are greatly welcome and appreciated as I am looking for better ways to code.


texts: Division without using division, multiplication, or modulus operators

texts:
The task

  Implement division of two positive integers without using the
  division, multiplication, or modulus operators. Return the quotient as
  an integer, ignoring the remainder.

My solution

const division = (dividend, divisor) => {
    let remainder = null;
    let quotient = 1;
    const sign = ((dividend > 0 && divisor < 0) ||
                 (dividend < 0 && divisor > 0)) ?
                 ~1 : 1;

    let tempdividend = Math.abs(dividend);
    let tempdivisor = Math.abs(divisor);

    if (tempdivisor === tempdividend) {
        remainder = 0;
        return sign;
    } else if (tempdividend < tempdivisor) {
        remainder = dividend < 0 ?
            sign < 0 ? ~tempdividend : tempdividend :
            tempdividend;
        return 0;
    }
    while (tempdivisor << 1 <= tempdividend) {
        tempdivisor = tempdivisor << 1;
        quotient = quotient << 1;
    }

    quotient = dividend < 0 ?
        (sign < 0 ? ~quotient : quotient) + division(~(tempdividend-tempdivisor), divisor) :
        (sign < 0 ? ~quotient : quotient) + division(tempdividend-tempdivisor, divisor);
    return quotient;
 }


texts: Pure PHP array_diff_assoc_recursive function

texts:
For my application, I was using array_diff_assoc, when I noticed it was returning the wrong value.  I was using multidimensional arrays, therefore I needed a array_diff_assoc_recursive method.

I Googled around and found a few, but they all only took 2 parameters.  The official array_diff_assoc can take an infinite number of params.  I wanted mine to, so I wrote my own array_diff_assoc_recursive function.

<?php
class Tools{
    /**
     * Recursive version of array_diff_assoc
     * Returns everything from $a that is not in $b or the other arguments
     *
     * @param $a The array to compare from
     * @param $b An array to compare against
     * @param ... More arrays to compare against
     *
     * @return An array with everything from $a that not in $b or the others
     */
    public static function array_diff_assoc_recursive($a, $b){
        // Get all of the "compare against" arrays
        $b = array_slice(func_get_args(), 1);
        // Initial return value
        $ret = array();

        // Loop over the "to" array and compare with the others
        foreach($a as $key=>$val){
            // We should compare type first
            $aType = gettype($val);
            // If it's an array, we recurse, otherwise we just compare with "==="
            $args = $aType === 'array' ? array($val) : true;

            // Let's see what we have to compare to
            foreach($b as $x){
                // If the key doesn't exist or the type is different,
                // then it's different, and our work here is done
                if(!array_key_exists($key, $x) || $aType !== gettype($x[$key])){
                    $ret[$key] = $val;
                    continue 2;
                }

                // If we are working with arrays, then we recurse
                if($aType === 'array'){
                    $args[] = $x[$key];
                }
                // Otherwise we just compare
                else{
                    $args = $args && $val === $x[$key];
                }
            }

            // This is where we call ourselves with all of the arrays we got passed
            if($aType === 'array'){
                $comp = call_user_func_array(array(get_called_class(), 'array_diff_assoc_recursive'), $args);
                // An empty array means we are equal :-)
                if(count($comp) > 0){
                    $ret[$key] = $comp;
                }
            }
            // If the values don't match, then we found a difference
            elseif(!$args){
                $ret[$key] = $val;
            }
        }
        return $ret;
    }
}

I was wondering what you thought of my attempt.  It seems to work ok for my application, and in the few tests I tried with it.

DEMO: http://ideone.com/5GZ8Tn


texts:
This method converts a string to mixed case, id est mixedCase("hello, world!") -> "HeLlO, wOrLd!".

// Any input string is lower case already
private static String mixedCase(String input) {

    // getAsCharacterList() simply turns a string into a List of Characters.
    List<Character> charactersAsList = getAsCharacterList(input);
    StringBuilder result = new StringBuilder();
    int index = 0;

    for (Character character : charactersAsList) {
        if (Character.isLetter(character)) {
            if (index % 2 == 0) {
                result.append(Character.toUpperCase(character));
            } else {
                result.append(character);
            }
            index++;
        } else {
            result.append(character);
        }
    }

    return result.toString();
}

It works, but admittedly it looks terrible and I have difficulties making it more concise. I would have preferred to use streams if I didn't had to reference indices...


texts:
I want to group an array of structs only using arrays into an array of new structs. In this example I want to group the Person structs by Job and put them in new Department structs and put them in an array.

enum Job {
    case developer
    case programmer
    case coder
}

struct Person {
    let id: Int
    let job: Job
}

struct Department {
    let job: Job
    var staff: [Person]

    mutating func addStaff(_ person: Person) {
        staff.append(person)
    }
}

let initial = [
    Person(id: 0, job: .developer),
    Person(id: 1, job: .developer),
    Person(id: 2, job: .programmer),
    Person(id: 3, job: .programmer),
    Person(id: 4, job: .coder)
]

func combinator(accumulator: [Department], current: Person) -> [Department] {
    var accumulator = accumulator

    if let index = accumulator.index(where: { $0.job == current.job }) {

        var department = accumulator[index]
        department.staff.append(current)
        accumulator[index] = department
    } else {
        accumulator.append(Department(job: current.job, staff: [current]))
    }

    return accumulator
}

var departments: [Department] = initial.reduce([], combinator)

I feel like the if statement in the combinator(accumulator:current:) function is a bit clunky, is there a better way to write that part or any other part of this piece of code?


texts:
Task description:
Write a function commonPrefix, which takes two strings as parameter and returns the common prefix.
Example: parameters abcdef and abc1gv would return abc.
My implementation:
fun commonPrefix(str1: String, str2: String): String {
    var sRet = ""
    var i = 0
    val length = if (str1.length >= str2.length)
        str1.length else str2.length

    while (i < length) {
        if (str1.take(i + 1) != str2.take(i + 1)) {
            return sRet
        }

        sRet += str1[i++]
    }

    return sRet
}

val first = "abcdef"
val sec = "abc1ef"

println(commonPrefix(first, sec))

Is my implementation done in a good way? Where could it be optimized?


texts:
I have the following code that takes user input "path" and adds the current time into the filename after the name part and before any extension (if it exists).
It seems a little hacky to me just looking at it. What do you think?
#include <string.h>
#include <stdio.h>
#include <libgen.h>

int main() {
    char buf1[256] = {0};
    char path[] = "/var/log/mine.log";
    char *tmp = NULL;
    char time[] = "20201110120305";
    char *dir = NULL;
    char *base = NULL;
    char *file = NULL;
    char *ext = NULL;
    //split path to base and dir
    tmp = strdup(path);
    dir = dirname(tmp);
    tmp = strdup(path);
    base = basename(tmp);
    //split base to file and ext
    tmp = strchr(base,'.');
    if (tmp) {
        ext = strdup(tmp);
        file = strndup(base,(strlen(base)-strlen(ext)));
    }
    else
        file = strdup(base);
    // concat dir / file / time / ext
    if (dir)
        strcat(buf1,dir);
    strcat(buf1,"/");
    if (file)
        strcat(buf1,file);
    strcat(buf1,"-");
    if (time)
        strcat(buf1,time);
    if (ext)
        strcat(buf1,ext);
    printf("%s\n",buf1);
}

This will output /var/log/mine-20201110120305.log


texts:
This is rather toy example of immutable datatype in C++. I've tried to follow functional languages like Scheme, Racket - making list as a cons cell: list is list or is empty.

/*
 * Abstract class
 */
template <class T>
class ImmutableList {

public:
~ImmutableList() {std::cout << "base class destructor";}
virtual bool is_empty() = 0;
virtual T head() = 0;
virtual ImmutableList<T> * tail() = 0;
virtual int length() = 0;
};

/*
 * class non empty List
 */

template <class T>
class List: public ImmutableList<T> {

int size = 1;
T first;
ImmutableList<T> * rest;
public:

List(T _first, ImmutableList<T> * _tail){
    first = _first;
    rest = _tail;
    size += _tail->length();
}
~List() {std::cout << "List class destructor";}
bool is_empty() { return false; }

T head(){
    return first;
}

ImmutableList<T>* tail(){
    return  rest;
}

int length() {return size;}
};

/*
 * class empty list
 */
template <class T>
class Nil: public ImmutableList<T> {
    public:
    ~Nil();
    bool is_empty() {return true;}
    int length() {return 0;}
    T head() {
        throw std::logic_error("Head of empty list!");
    }
    ImmutableList<T> * tail() {
        throw std::logic_error("Tail of empty list!");
    }
};

There is more functions, like a reverse, there is also cons function - constructs a list.
Do this really need destructors? Will be better to use smart pointers?


texts: Efficiency Heuristics for Adding Elements to Lists in Python

texts:
Suppose my goal is to add elements to list in python if they pass a conditional. There are many ways to do this and I show some. Would it be possible if you could review each block and describe its performance in context of the other blocks? Additionally, if possible, can you provide some performance heuristics for the task of appending these elements to my lists?

For each of these lists, the output is the same

[0,1,2,3]

Block 01

my_list = []
for num in range(10):
     if num < 4:
          my_list.append(num)

Block 02

my_list = [num for num in range(10) if num < 4]

Block 03

cond = lambda num: num < 4
my_list = [num for num in range(10) if cond]

Block 04

my_list = list(filter(lambda num: num < 4, list(range(10))))


texts: Binary tree implemented using references

texts:
I implemented a binary tree using references because I couldn't see why people don't use references instead of pointers to implement data structures such as binary trees:

#include <iostream>

struct Node {
  Node(Node& l, Node& r, const char* v) : left_child(l), right_child(r), value(v) {}
  const char* value;
  Node& left_child;
  Node& right_child;
};

Node null_node(null_node, null_node, "END_OF_TREE");

bool is_leaf(Node& node){
  return &node.left_child == &null_node && &node.right_child == &null_node;
}

void post_order(Node& node){
  if (is_leaf(node)){
    std::cout << node.value;
  }
  else{
    if (&node.left_child != &null_node){
       post_order(node.left_child);
    }
    if (&node.right_child != &null_node){
       post_order(node.right_child);
    }
    std::cout << node.value;
  }
}

int main(){
  Node n1(null_node, null_node, "1");
  Node n2(null_node, null_node, "2");
  Node n3(n1, n2, "3");
  Node n4(null_node, null_node, "4");
  Node n5(n3, n4, "5");
  post_order(n5);
}

I still can't see why references are inferior to pointers. What's wrong with using references for binary tree (other than that you can't insert or delete elements)?

Also I'm completely new to C++ so any feedback on the code itself is appreciated as well. Thank you.


texts:
I was wondering if I could solve the problem here (mostly unrelated) using only simple binary operators since it is just mapping 100 different inputs to a boolean. For this I wrote this, but I have no real way to test, and I was also hoping it could be faster.

#include <iostream>
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX_VAL 100

bool CODES[] = {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1};

int op(int a, int b, int index) {
    switch (index) {
        case 0: return a + b; break;
        case 1: return a - b; break;
        case 2: return a * b; break;
        case 3: return a / b; break;
        case 4: return a & b; break;
        case 5: return a | b; break;
        case 6: return a ^ b; break;
        case 7: return a % b; break;
    }
}

int main(int argc, char const *argv[]) {
    for (int A=1; A < 2; A++) {
        std::cout << A << std::endl;
        for (int B=1; B < 2; B++) {
            std::cout << A << " " << B << std::endl;
            for (int C=1; C < 2; C++) {
                for (int D=1; D < MAX_VAL; D++) {
                    std::cout << A << " " << B << " " << C << " " << D << std::endl;
                    for (int E=1; E < MAX_VAL; E++) {
                        for (int opA = 0; opA < 8; opA++) {
                            for (int opB = 0; opB < 8; opB++) {
                                for (int opC = 0; opC < 8; opC++) {
                                    for (int opD = 0; opD < 8; opD++) {
                                        for (int opE = 0; opE < 8; opE++) {
                                            bool good = true;
                                            int index = 1;
                                            for (bool item : CODES) {
                                                int val = op(index, A, opA);
                                                val = op(val, B, opB);
                                                val = op(val, C, opC);
                                                val = op(val, D, opD);
                                                val = op(val, E, opE);
                                                val &= 1;
                                                if (val != item) {
                                                    good = false;
                                                    break;
                                                }
                                                index++;
                                            }
                                            if (good) {
                                                std::cout<<"GOOD "<<A<<" "<<opA<<" "<<B<<" "<<opB<<" "<<C<<" "<<opC<<" "<<D<<" "<<opD<<" "<<E<<" "<<opE<<std::endl;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return 0;
}

I am specifically looking for help for optimization, but of course style, correctness, or anything else is much appreciated.