Generate List of Integers Differing From Input By 1 bit

To make a hypercube graph it is necessary to connect vertices that have ID’s that differ by 1 bit. I did not readily find any algorithms to do this, so here is my own written in JavaScript.

let pad = (str, max) => {
    return str.length < max ? pad("0" + str, max) : str; 

let generateDifferByOne = (input, numBits) => {
    let inputBits = pad((input).toString(2), numBits).split("").reverse();
    let allDiffer = [];

    for(let b = 0; b < numBits; b++){
        if(inputBits[b] === "0"){
            let newNum = inputBits.slice();
            newNum[b] = "1";
            allDiffer.push(parseInt(newNum.reverse().join(""), 2));

    return allDiffer;

The method above does not generate any values lower than the input, but that can be fixed by adding an “else” inside the loop to switch 1’s to 0’s and push it into allDiffer.

Dynamically Set Deep Dictionary Values

If you have ever needed to set some values of a dictionary in JavaScript or PHP, then you know that you have to do something like myArray[a][b][c] = 0. But what if we don’t know that the subkeys will be “a->b->c” until runtime? You would need a way to index into the dictionary dynamically and return the resulting modified dictionary. Below are code snippets in JavaScript and PHP that do exactly that.

Continue reading → Dynamically Set Deep Dictionary Values

Regex to Make Text Links HTML Links

Regex used to select and replace URLs in plain text with clickable links



$regex = '(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#~\@!]*(\?\S+)?)?)?)';
$text = mb_ereg_replace($regex, '<a href="\\1">\\1</a>', $text);

Python Multiprocessing

The following code will enable you to implement multiprocessing in any Python project that contains a for loop. Take your for loop that has a long-running function in it and replace “for i in iterable” with your for loop conditions. Change “function_name” to the name of the function that will be executed. Change the list of function arguments to what you need.

import multiprocessing
number_cores = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=number_cores)
r = [pool.apply_async(function_name, args=(function_arg1, function_arg2)) for i in iterable]
output = [p.get() for p in r]

The above code would be the multiprocessing implementation of the following.

output = []
for i in iterable:
    output += function_name(function_arg1, function_arg2)

Regex Sentence Splitter

Regex to match the end of sentences in order to split a block of text into sentences.


Python Code

sentence_regex = ur'([\.\?!][\'\"\u2018\u2019\u201c\u201d\)\]]*\s*(?<!\w\.\w.)(?<![A-Z][a-z][a-z]\.)(?<![A-Z][a-z]\.)(?<![A-Z]\.)\s+)'
regex = re.compile(sentence_regex, flags=re.UNICODE)
sentences = regex.split(TEXT_BLOCK)