Roll a die according to the number of sides that the user enters

Your variables dice4. dice6 and dice12 are essentially the same variables, so let's give them the same name. It now happens that three of the cases are identical, and can be shortened to:

if dicesides != 4 or dicesides != 6 or dicesides != 12:
    print("That number is invalid. Please try again.")
    var()
else:
    score = int(random.randrange(1, dicesides))
    print(dicesides, " sided dice, score", score)

The test for allowed numbers of sides can be shortened to dicesides not in [4, 6, 12], which more clearly shows what you are trying to express. This would allow you to include the number of sides as an optional parameter to the function – some people use 20-sided dices a lot. And actually, there is no reason why you would constrain the user to a certain number of sides anyway.

It is not clear to me what advantage recursion via the var method has over an ordinary loop. One disadvantage is that an avid player could theoretically overflow the stack….

It is also not clear why random is a parameter to the script.

You are using random.randrange wrong. The help() output on my system gives me:

  Choose a random item from range(start, stop[, step]).

  This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.

This means that rolling a 6-sided die, you will invoke random.randrange(1, 6), which returns a random int in the range [1, 6) – this excludes the number 6, and you actually pick from 1, 2, 3, 4, 5. Fix this either by 1 + random.randrange(0, dicesides) or preferably random.randint(1, dicesides).


Implementation of arbitrary-precision integer addition

How can I improve this implementation?

You could extract the string parsing to a separate int[] ToIntArray(String) method.
You could add a separate int[] Add(int[],int[]) method.
You could add a separate String ToString(int[]) method.

Right now your method is

parsing the String's to int[]
adding two int[]
composing a string out of the adding

So after extracting the methods your former Add() method would look like

string Add(string a,string b)
{
    int maxLen = Math.Max(a.Length,b.Length);
    a = a.PadLeft(maxLen+1,'0');
    b = b.PadLeft(maxLen+1,'0');

    int[] arr1 = ToIntArray(a);
    int[] arr2 = ToIntArray(b);

    int[] sum = Add(arr1,arr2);

    return ToString(sum);
}

But wait, we can do much better using more OOP.

Let us introduce a new class IntArray ( which can be private ). In this class we override the ToString() method, add constructors for int[] and string and also add a + operator.

private class IntArray
{

    public int[] array { get; private set; }
    public IntArray(int[] arr)
    {
        array = arr;
    }

    public IntArray(String s)
    {
        array = s.Select(x => int.Parse(x.ToString())).ToArray();
    }

    public static IntArray operator +(IntArray summand1, IntArray summand2)
    {
        int[] sum = new int[summand1.array.Length];
        int carry = 0;

        for (int i = sum.Length - 1; i >= 0; i--)
        {
            int total = summand1.array[i] + summand2.array[i] + carry;
            sum[i] = total % 10;
            if (total > 9)
            {
                 carry = 1;
            }
            else
            {
                carry = 0;
            }
        }

        return new IntArray(sum);
    }
    public override string ToString()
    {
        return string.Concat(array.SkipWhile(x => x == 0));
    }

}

This will simplify your former Add() method to

string Add(string a, string b)
{
    int maxLen = Math.Max(a.Length, b.Length);
    a = a.PadLeft(maxLen + 1, '0');
    b = b.PadLeft(maxLen + 1, '0');

    IntArray arr1 = new IntArray(a);
    IntArray arr2 = new IntArray(b);

    return (arr1 + arr2).ToString();
}

Update: Based on d347hm4n's comment and after checking the reference source, I changed to implementation of ToString() from String.Join() to String.Concat() method.


Can I make this code shorter?

If you use the ORG 7C00h directive, then loading the segment registers will be shorter code.
You can choose to setup the stack below the bootloader and shave off that addition. Even if you leave the stack where you placed it before (above the bootloader), with SS=0 the change would become mov sp, 9E00h.
You avoid having to load the string address (and the need to come up with suitable label names) if you store the actual string directly beneath the call instruction and have the print_string routine jump back to behind the terminating zero.
This technique becomes more interesting if more than 1 string is to be printed.

    BITS  16
    ORG   7C00h

start:
    cld                          <--- Not shorter but better!
    xor   ax, ax
    mov   ds, ax
    mov   ss, ax
    mov   sp, 7C00h

    call  print_string
    db    'OS', 0
    jmp   $

print_string:
    pop   si
    mov   bx, 7                  <--- Not shorter but better!
    mov   ah, 0Eh
.repeat:
    cs lodsb ; Need CS override since SI is an offset in code segment!
    cmp   al, 0
    je    .done
    int   10h
    jmp   .repeat
.done:
    jmp   si

    times 510-($-$$) db 0
    dw 0xAA55

The CS segment override on the LODSB instruction is required unless you know that DS == CS. Many bootloaders will have a far jump at the top to ensure that this is the case. e.g. jmp 0000h:7C05h as the very first instruction. This will set CS=0.
Not shorter but better

Adding a CLD instruction makes sure that the LODSB instruction will function correctly.
Passing all the required parameters to the BIOS.Teletype function is best. BH is DisplayPage and BL is GraphicsColor. If you know that the screen is in a text video mode then you can drop the setting for BL and just write mov bh, 0 to select the video page.


Testing

Personally I think it’s conceptually easier to test this code if you are returning a string – rather than a void: what if you decided to change the out put device from a console window to your printer – it would not be easy to change that. What if sometimes you wanted a console window and other times you wanted to send the same thing via text message? I guess it’s easier to separate what is being done vs how it is being done. E.g. Output key is the abstract concept but this could be done a number of different ways: (i) to the console, or (ii) through a voice synthesiser etc. I wrote some tests but then i threw it once it broke when i changed the API.

Naming

What is data? It’s harder to think of a more abstract name. I’ve changed this to keywords.
Personally I like to see the type along with the variable declaration.

Refactoring the code:

I simplified and extracted some methods.
The The HandleKeyInput and the HandleTabInput both seem to be doing conceptually similar things: a key is inputted and then a result is obtained. If it’s a tab then do X, but if it’s a key then do Y. There’s a common abstraction here that can be extracted.
What I want to do is to make the two methods: HandleTabInput and HandleKeyInput to look and be absolutely identical.
Data (renamed to keywords) can be a field so there’s no need to pass it in as a variable.
I want to make two of your methods to basically be the same. They’re kinda doing this same things. After some refactoring this is what I got:

public void HandleTabInput(StringBuilder builder, ConsoleKeyInfo keyInput)
{
        // Perform calculation
    string match = ExtractMatch(builder);

        // Alter the builder
    builder.Clear();
    builder.Append(match);

        // Print Results
    PrintMatch(match);
}

And then this:

    private void HandleKeyInput(StringBuilder builder, ConsoleKeyInfo keyInput)
    {
        if (keyInput.Key == ConsoleKey.Backspace && builder.ToString().Length > 0)
        {
                // Perform Calculation (nothing here)

                // Alter the builder
            builder.Remove(builder.Length - 1, 1);

                // Print Results
            ClearCurrentLine();
            Console.Write(builder.ToString().Remove(builder.ToString().Length - 1));
        }
        else
        {
                // Perform calculation (nothing here)

                // Alter the Builder
            var key = keyInput.KeyChar;
            builder.Append(key);

                // Print Reuslts
            Console.Write(key);
        }
    }

We can abstract out the calculation, and then the printing. After some work this was the result. It’s starting to look pretty similar:

    private void HandleKeyInput(StringBuilder builder, ConsoleKeyInfo keyInput)
    {
        if (keyInput.Key == ConsoleKey.Backspace && builder.ToString().Length > 0)
        {
            Program.KeyInput backSpaceKey = new Program.KeyInput.BackspaceInput(builder, keywords);
            backSpaceKey.AlterBuilder();
            backSpaceKey.PrintResult();
        }
        else
        {
            KeyInput input = new KeyInput.StandardKeyInput(builder, keywords, keyInput.KeyChar);
            input.AlterBuilder();
            input.PrintResult();
        }
    }

You could probably tidy things up a little more.

The final Result:

    public void RunProgram()
    {
        StringBuilder builder = new StringBuilder();
        ConsoleKeyInfo capturedCharacter = Console.ReadKey(intercept: true);

        while (EnterIsNotThe(capturedCharacter))
        {
            KeyInput key = KeyInput.GetKey(builder, keywords, capturedCharacter);
            builder = key.UpdateBuilder();
            key.Print();

            capturedCharacter = Console.ReadKey(intercept: true);
        }

        Console.Write(capturedCharacter.KeyChar);
    }

Concluding Thoughts

It reads marginally better. Still If you want to reuse the code you’ll have to make changes, but at least it will be a little easier to do when the time comes.
Encapsulation could be a little better – typically speaking you want the KeyInput class to be instantiated via the factory only.

A link to see the full code.


Adding two numbers, each digit as a single element of array

I see some things that may help you improve your code.

Use const where practical

The sumOfTwo() function doesn't (and probably shouldn't) modify the passed integer arrays, so they should be declared const.

Show all required headers

The code uses malloc and free but the code does not show a the required include file.  For code reviews (and job interviews!), it's best to list the required includes.  This code needs only:

#include <stdlib.h>

Use stdbool.h when needed

This code contains lines like this:

int a1IsLongest = TRUE;

However, there are already bool types and values supported in the stdbool.h header.  Prefer those to non-standard types and values.  The line above would then be:

bool a1IsLongest = true;

Fix formatting

The indentation is not consistent, and in one case, there's a space between else and the following { but in other case there's no space.  Which convention you use is less important than choosing one and following it consistently.

Simplify your code

There are a number of extra variables and comparisons to determine which array is larger.  Why not instead simply assume that a1 is longer than or equal in length to a2 and then make that true?  It would simplify the code a lot.  For example, one could start the code this way:

if (lengthOfA1 < lengthOfA2) {
    // swap the arguments to ensure a1 is not shorter than a2
    int *temp = a1;
    int templen = lengthOfA1;
    a1 = a2;
    lengthOfA1 = lengthOfA2;
    a2 = temp;
    lengthOfA2 = templen;
}

Assume a convenient data structure unless otherwise specified

It's not clear whether you were told that the data structure had the least significant or most significant digit first or whether either had leading zeroes.  The most convenient data structure would actually be to store the data with the least significant digit first, as I'll demonstrate in the next suggestion.

Allocate memory only once

The current code allocates some memory and then may allocate again if more is needed, copying the elements from the old to the new array.  There are several strategies that would allow you to allocate memory only once.

The first is to note that the maximum additional memory required would be exactly one int and to simply allocate enough space for that, with the understanding that there would be, potentially, a leading zero in the answer.

The second would be to determine if a carry will be required and allocate space accordingly.  One way to do that would be to make two passes through the data.

The other possibility is to adjust the allocated length after calculation.  This could be done very simply using the realloc function.

Prefer "less expensive" to "more expensive" operations

If the digits are decimal digits (not stated, but assumed), then the largest possible sum will be 9+9=18, so the largest possible carry value is 1.  If the resulting value is greater than 10, the current code uses this code:

answer[i] = result % 10;

The % operator typically does a division which is computationally expensive on many platforms.  Better is to simply use subtraction and the fact that the carry can only possibly be equal to 1 or 0.

if (result >= 10) {
    result -= 10;
    carry = 1;
}

Check for memory allocation failure

Calls to malloc can fail.  Robust code should check for that and handle the out-of-memory condition appropriately.

Putting it all together

Here's a version incorporating all of these suggestions:

int *sumOfTwo(const int *a1, const int *a2, int lengthOfA1, int lengthOfA2, int *lengthDest)
{
    if (lengthOfA1 < lengthOfA2) {
        // swap the arguments to ensure a1 is not shorter than a2
        const int *temp = a1;
        int templen = lengthOfA1;
        a1 = a2;
        lengthOfA1 = lengthOfA2;
        a2 = temp;
        lengthOfA2 = templen;
    }
    *lengthDest = lengthOfA1 + 1;
    int *result = malloc(*lengthDest*sizeof(a1[0]));
    if (result == NULL) {
        *lengthDest = 0;
        return NULL;
    }
    // copy a1 into result
    memcpy(result, a1, lengthOfA1*sizeof(a1[0]));
    result[lengthOfA1] = 0;
    int carry = 0;
    int *end = result + *lengthDest;
    int val;
    // add in place
    for (int *digit = result; digit != end; ++digit) {
        val = carry + *digit;
        if (lengthOfA2) {
            val += *a2++;
            --lengthOfA2;
        }
        if (val >= 10) {
            val -= 10;
            carry = 1;
        } else {
            carry = 0;
        }
        *digit = val;
    }
    return result;
}

Test harness

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

// sumOfTwo() goes here

void printnum(const int *num, int len, int desiredlen)
{
    for (; desiredlen > len; --desiredlen) {
        printf(" ");
    }
    for (num += len - 1; len; --len, --num) {
        printf("%u", *num);
    }
    puts("");
}

struct number {
    int len;
    int digits[5];
};

struct test {
    struct number n1, n2, expected;
};

struct test tests[] = {
    { { 1, {9} }, { 1, {9} }, { 2, { 8, 1 } }},
    { { 3, {8, 9, 9}}, {2, {1, 9}}, { 4, { 9, 8, 0, 1}}},
    { { 3, {8, 9, 9}}, {3, {0, 0, 1}}, { 4, {8, 9, 0, 1}}},
};

bool doTest(const struct test* t) {
    int lengthDest;
    int *answer = sumOfTwo(t->n1.digits, t->n2.digits, t->n1.len, t->n2.len, &lengthDest);
    printnum(t->n1.digits, t->n1.len, 5);
    printnum(t->n2.digits, t->n2.len, 5);
    puts("-----");
    printnum(answer, lengthDest, 5);
    if (lengthDest != t->expected.len) {
        free(answer);
        return false;
    }
    for (int i = 0; i < lengthDest; ++i) {
        if (t->expected.digits[i] != answer[i]) {
            free(answer);
            return false;
        }
    }
    free(answer);
    return true;
}

int main()
{
    int testcount = sizeof(tests) / sizeof(tests[0]);
    for (int i=0; i < testcount; ++i) {
        printf("Test %d: %s\n\n", i+1, doTest(&tests[i]) ? "OK " : "BAD");
    }
}

Test result

Here is the output of the test program:

    9
    9
-----
   18
Test 1: OK

  998
   91
-----
 1089
Test 2: OK

  998
  100
-----
 1098
Test 3: OK


So I kind of figured this out. The db connector can be passed around like just another variable. Silly I didn't realise this before. I created a new file to abstract the model.

dbOperations.js

exports.addToDB = async function (model, dataObj, listName, res) {
  model.update({
      userid: dataObj.userID
    }, {
      $addToSet: {
        listName: {
          $each: dataObj.playerID
        }
      }
    }, {
      upsert: true
    },
    function (err, data) {
      if (!err && data) {
        util.successResponder(res, successText);
      } else {
        util.serverErrorResponder(res, errorOccured);
      }
    });
};

teamController.js

var mongoose = require('mongoose');
const teamModel = mongoose.model('teamModel');
const dbOperations = require('../../helper/dbOperations');

exports.addPlayerToTeam = function (req, res) {
  let dataObj = {teamID: req.body.teamID, playerID: req.body.playerList};
  dbOperations.addToDB(teamModel,dataObj,'teamList',res);
}

And similarly for the other file as well. Any other files which follow a similar schema can use it. There is probably a better way to do this so that this can be generalised further to accommodate other schema types.


Restrict file types:
As your concern is security, you should make sure that the file type is one of those you allow.
For that you must implement a file type checker, that validates file type is allowed, then you let the user upload the file. Learn how to do that here or at stackOverflow.
Upload Size  You may like to have max upload size, so users do not upload too large files. Find how to do that at phpmaster.
Check the referrer: Check to make sure that the information being sent to your script is from your website and not an outside source. While this information can be faked, it's still a good idea to check.
Rename files: You can rename the files that are uploaded. In doing so, check for double-barreld extensions like yourfile.php.gif and eliminate extensions you don't allow, or remove the file completely.
Change permissions: Change the permissions on the upload folder so that files within it are not executable. Your FTP program probably allows you to chmod right from it.
Login and Moderate: Making your users login might deter some deviant behavior. You can also take the time to moderate all file uploads before allowing them to become live on the web.
Keep away from root: If your document root is /var/www/html, create a directory /var/www/uploads and use it to store uploaded files. That way, an attacker will not be able to retrieve the file directly. This will allow you to provide fine grained access control. The file will not be parsed by the server's application language module but the source of the file will be streamed.
Malware Scan:
The extension is right, and you checked that the file is actually a valid JPEG file per it's header. However, it could still be a malicious JPEG using one of the many image parser bugs to exploit clients downloading the file. There is no great defense against this as far as I am aware. One possible work around is to "rebuild" the file. Convert the JPEG to a GIF and back to a JPEG. This will likely strip out any malicious feature. But this technique could expose your servers to just the same image parser bugs.

Here are some links to help,

http://software-security.sans.org/blog/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/

http://webcheatsheet.com/PHP/file_upload.php


How can I Implement a better version of my function find the closest number to zero?

Your reviewers are correct. You are doing way too much work here. To find the number closest to zero you only need to find the smallest absolute value in the list. You should also clarify in the interview if the list can contain non-numeric values. There's no reason to test that the values are numbers unless you need to for the purpose of the review, although asking about this shows that you are thinking about edge cases, which is good.

Either way, this can be done in a single loop with no storage other than keeping track of the current minimum:

function absSmallest(arr){
   if (!arr || arr.length === 0 ) return 0            // address requirement to return 0 when arr is undefined or empty
   let res = undefined                                // smallest value seen so far
   for (let i = 0; i < arr.length; i++){
      if (res === undefined || Math.abs(arr[i]) <= Math.abs(res)){
         res = Math.abs(arr[i]) === Math.abs(res)    // address requirement of positive value when there's a tie
         ? Math.max(res, arr[i] )
         : res = arr[i]
      }
   }
   return res
}

console.log(absSmallest([5, 4, -9, 6, -10, -1, 8] ))
console.log(absSmallest([8, -2, 3, 2] ))
// check order of tied values
console.log(absSmallest([8, 2, 3, -2] ))

// edge case empty list returns 0:
console.log(absSmallest())
console.log(absSmallest([]))


Bad performance of the unsorted list (nearly quadratic time)

For now I'm asking how to optimise deleting of MaxIndex from unsorted list

MaxIndex looks fine. Hard to optimize that further. Maybe you can write a normal for loop that goes from zero to less than the array length so that the JIT can optimize away the range check. You then need to insert if (i >= size) break;. The .NET JIT is not good at optimizing so you have to help. RyuJIT, though, does range checks in loops much, much better.

Your delete is highly inefficient. First of all LINQ is the slowest way to create a new array. Better would be to new it manually and then use Array.Copy to copy over the relevant two sections.

Doing it in-place would be again much faster, at least 2x.

The DeleteAt is probably worse than Array.Copy. It is not very good. It does a lot per item and it does not use memcpy like Array.Copy does. Also, there is no need to create a new array. Just copy in place and do size--.


type=number inputs can be error-prone because it's easy to mistakenly adjust a value with the mouse wheel.  Unless you specifically intend to enter grades with a mouse wheel, or have some other use for that interface, go with regular text fields.

You're testing the truth of element.value as a string and then adding it as a number.  It's good practice to be explicit about these kinds of conversions.

It would be nice to generalize the code to handle any subject, without the use of hard-coding or copy-and-paste.

We only need the subject name to put a label next to the inputs; the code doesn't need to know it at all.   The code snippet below uses the name=... attribute to label the inputs (via CSS) and class=subject to denote an average-eligible set of inputs.  The number of inputs is determined solely by the HTML.

document.getElementById('calculator').addEventListener('click', function() {
    Array.from( document.getElementsByClassName('subject') ).forEach(subject => {
        const scores=Array.from( subject.getElementsByTagName('input') ).map( e => ""+e.value.trim() ).filter( s => s.length ).map( n => parseFloat(n) ),
          output=subject.getElementsByTagName('output'),
          sum=scores.length ? scores.reduce((partial_sum, a) => partial_sum + a) : 0,
          average=scores.length ? ( sum / scores.length ).toFixed(2) : "No assessment made!"
      if (output.length) output[0].textContent = average;
  })
});

.subject::before {  text-transform: capitalize; content: attr(name) ": " }
.subject > input { width:3em }
<form>

   <input> <input> <input> <output/>

   <input> <input> <input> <output/>

 <input> <input> <input> <input> <output/>

   <input> <output/>

  <button type=button id=calculator>Calculate</button>
</form>


in the constructor it's better to allocate an empty array to avoid an unexpected null pointer.

In maxHeapify you should just at least initialize heapSize to 0 before the loop.

You have no other way to add a element to the heap. This would be something like this:

public void add(int value){
    int index = heapSize+1;
    if(index >= heap.length) heap = Arrays.copyOf(heap, heapSize + 16);
    heap[index] = value;

    while (index > 1 && heap[index/2] < heap[index]){
        //swap parent with child
        int temp= heap[index/2];
        heap[index/2]= heap[index];
        heap[index]=temp;

        index/=2;
    }
}

heapify depends on value being the same as the value at heap[heapSize+1] instead you can use the add above.

removeMax should throw a better exception than either returning -1 or throwing NullPointerException if the heap is empty (from being emptied or never being filled).

public  int removeMax() {
    if(heapSize == 0)
        throw new NoSuchElementException("The heap is empty");

    //...
}


Rational Approximation for e with Matlab

Continued fractions are an easy way to calculate good rational approximations to real numbers. You can find a disussion of an algorithm to convert a floating point number into a fraction in my blog, with code in JavaScript which should be easy to convert to matlab:

function float2rat(x) {
  var tolerance = 1.0E-6;
  var h1=1; var h2=0;
  var k1=0; var k2=1;
  var b = x;
  do {
     var a = Math.floor(b);
     var aux = h1; h1 = a*h1+h2; h2 = aux;
     aux = k1; k1 = a*k1+k2; k2 = aux;
     b = 1/(b-a);
  } while (Math.abs(x-h1/k1) > x*tolerance);
  return h1+"/"+k1;
}

If you're specifically interested in e you can take a shortcut and use the regularities in its continued fraction representation to produce rational approximations that are far more accurate than the machine epsilon. This method is described here.


First SO chat message in Haskell followup

body is unused in searchLast.

I don't like explicit recursion as it is used in searchLast. MaybeT has the correct behavior for what you want.

ala X turns a function like foldMap into a function like fold by applying the newtype constructor X to it and unwrapping the result of the resulting function so that it looks like the type wrapped in the newtype has all the instances defined on the newtype.

alaf X works the same, except that it turns a function like foldMap into a function like foldMap, so that further ala-functions can be applied.

Control.Lens.Wrapped (ala)

Alt is the newtype wrapper that gives Alternatives like Maybe a Monoid instance, therefore ala Alt foldMap would be asum, and alaf Alt foldMap is something like "asumMap", being to asum as foldMap is to fold.

(ala MaybeT . alaf Alt) foldMap = ala MaybeT (alaf Alt foldMap) = ala MaybeT asumMap (except that asumMap doesn't exist) takes [m (Maybe a)] and combines it into m (Maybe a) using MaybeT's Alternative instance.

getFirstMessagePage :: UserID -> IO String
getFirstMessagePage uid = (ala MaybeT . alaf Alt) foldMap
    . map fetchMonologue
    . reverse . enumFromTo 0 . ceiling . (/100)
    =<< (fmap fromIntegral $ getMessages uid) where

    fetchMonologue :: Int -> IO (Maybe String)
    fetchMonologue pg = do

        let lnk = concat [ hostname
                         , "/users/"
                         , uid
                         , "/?tab=recent&pagesize=100&page="
                         , show pg ]

        body' <- getURLContent lnk

        return $ mfilter (isInfixOf "monologue") $ Just body'


Formatting:

First of all, indent your code properly; each level of identation should include four spaces. So instead of

class Dequeue
{
int arr[];
...

Rewrite it as

class Dequeue
{
    int arr[];
    ...

What comes to braces, according to Java coding conventions, you should have the opening curly brace on the same line with the token it belongs to; also, you should have one space between the relevant token and the opening brace:

class Dequeue {
    int arr[];
    ...

Naming:

Dequeue is not what you think it is called; it's Deque (double-ended queue). And in a FIFO queue data structure, the operation popping the first element is actually (and conventionally) called dequeue; don't mix the terminology.

What comes to method names, please stick to camel-case. For example,

addRear instead of addrear

Visibility:

Declare your fields (arr, lim, front, rear) private:

class Dequeue {
    private final int arr[];
    private int lim;
    ...

You can make arr final, since you do not reassign to it.

Also, you might consider declaring your class both public and final:

public final class Deque {
    private final int[] arr;
    ...

lim:

You don't need this field, as you can always rely on arr.length.

Algorithm:

Consider removing rear and replace it by a field, say, size. That way you always know the size of your deque, and you don't have to allocate additional array component in order handle the logic gracefully.

Proposal:

After working a bit on your code, I got this implementation. Hope that helps.

import java.util.NoSuchElementException;
import java.util.Random;

public class Deque {

    private final int arr[];
    private int head;
    private int size;

    public Deque(int capacity) {
        arr = new int[capacity];
    }

    public void addLast(int element) {
        checkCapacity();
        arr[(head + size++) % arr.length] = element;
    }

    public void addFirst(int element) {
        checkCapacity();

        if (head == 0) {
            arr[(head = arr.length - 1)] = element;
        } else {
            arr[(--head) % arr.length] = element;
        }

        size++;
    }

    public int removeFirst() {
        checkNotEmpty();

        int ret = arr[head];
        head = (head + 1) % arr.length;
        size--;
        return ret;
    }

    public int removeLast() {
        checkNotEmpty();

        int ret = arr[(head + size - 1) % arr.length];
        size--;
        return ret;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");

        for (int i = 0; i < size; ++i) {
            sb.append(arr[(head + i) % arr.length]);

            if (i < size - 1) {
                sb.append(", ");
            }
        }

        return sb.append("]").toString();
    }

    public int size() {
        return size;
    }

    private void checkCapacity() {
        if (arr.length == size) {
            throw new IllegalStateException("No more space is available.");
        }
    }

    private void checkNotEmpty() {
        if (size == 0) {
            throw new NoSuchElementException("Trying to pop an empty deque.");
        }
    }

    public static void main(String args[]) {
        Deque deque = new Deque(10);
        Random random = new Random();

        for (int op = 0; op < 30; ++op) {
            if (deque.size() == 0) {
                int num = random.nextInt(100);
                System.out.print("Adding " + num + " to front: ");
                deque.addLast(num);
                System.out.println(deque);
            } else {
                boolean add = random.nextBoolean();

                if (add) {
                    boolean front = random.nextBoolean();
                    int num = random.nextInt(100);

                    if (front) {
                        System.out.print("Adding " + num + " to front: ");
                        deque.addFirst(num);
                        System.out.println(deque);
                    } else {
                        System.out.print("Adding " + num + " to back:  ");
                        deque.addLast(num);
                        System.out.println(deque);
                    }
                } else {
                    boolean front = random.nextBoolean();

                    if (front) {
                        System.out.print("Removing from front: ");
                        deque.removeFirst();
                        System.out.println(deque);
                    } else {
                        System.out.print("Removing from back:  ");
                        deque.removeLast();
                        System.out.println(deque);
                    }
                }
            }
        }
    }
}


Find the length of the longest consecutive elements

Complexity

The sort is about  \$O(n log(n))\$ depending on the JS engine so this makes your function above \$O(n)\$

Redundancies

Your code is full of redundancies.

compare and ascending can just be ascending and if you needed descending you would just swap the arguments.
The object named maxObj has redundant naming. The max prefix is not needed in the properties. If you use it for minObj would you thus need to rename the two properties?
Does the max object need the name Obj ?
You ignor the second argument of reduce and then index the array to find it. The indexing is redundant as you already have the value stored in _.
The function getMax is not used.
The () around src[idx] + 1 is not needed, the operator + has precedence over ===
You can use Math.max if only complexity is important rather than the ternary that only gives a slight performance benefit over Math.max
The line maxObj.maxResult = ++maxObj.maxCurrent > maxObj.maxResult ? maxObj.maxCurrent : maxObj.maxResult; is redundant. Each time you call it maxCurrent is always greater than maxResult. Not only is the line redundant but it makes the need for maxObj redundant as well.

Same function without the redundant code

You can thus remove most of the code, wrap it in a function, use closure to access samples to get 4 line and many fewer objects, arguments, and overhead to do the same thing. More readable and faster, (not less complex)

From about 16 lines to 4 for the same result.

const countConsecutive = arr => {
    const count = (count, val, i) => count += val + 1 === arr[i + 1] ? 1 : 0;
    return sample.sort((a, b) => a - b).reduce(count, 1);
}

However

With all that said I am not sure that the result is correct?

For [1, 100, 2, 90, 3, 88, 4, 9, 5]

  "...the longest consecutive element sequence..."

is 5 items.

That makes sense 1,2,3,4,5

But you return 7 for [1, 100, 2, 90, 3, 88, 89, 4, 9, 5]?

To me 1, 2, 3, 4, 5, 88, 89, 90 is not a "consecutive... sequence" ???

An example solution

For a \$O(n)\$ solution you need to join sequences as you find them.

Use a Set to do the lookups (if the next number exists). Iterate the set deleting numbers as you go lets you only check values you have not encountered.

Counting forwards sequences as you find them and storing the result in a map. When the next in a sequence is in the map add to the sequence length.

That brings the solution to \$O(2n + m)\$ The \$2n\$ as one pass is needed to create the Set and where \$m\$ is the number of broken sequences that at max is \$n\$. So \$O(3n)\$ is the same as \$O(n)\$

There is room for performance improvement as you can do some of the counting as you create the Set

const longestSequence = (arr) => {
    const numbers = new Set(arr), counts = {};
    var max = 1;
    for (const num of numbers.values()) {
        let counting = true, next = num + 1;
        numbers.delete(num);
        while (counting) {
            counting = false;
            while (numbers.has(next)) { numbers.delete(next++) }
            if (counts[next]) { counting = numbers.has(next += counts[next]) }
        }
        max = Math.max(counts[num] = next - num, max);
    }
    return max;
}


JavaScript function to create 2 soccer teams as even as possible, from a list of players

First I would make each team an object with a score and players rather than an object for scores and one for players:

var teams = [ { name:'A'; score: 0, players:[] },
              { name:'B', score: 0, players:[] };

Once you have sorted the players by score it might be simpler to pick them off the list two at a time and assign the one with the higher score to the lower scoring team:

// Note: slice is probably better than Object.assign
let input = this.players.slice();
assert(input.length % 2 == 0, 'Need an equal number of players');

while (input.length > 0) {
  let [strongerTeam,   weakerTeam]   = teams;
  let [strongerPlayer, weakerPlayer] = input.slice(0,2);
  addPlayer(strongerTeam, weakerPlayer);
  addPlayer(weakerTeam,   strongerPlayer);
  sortTeams(teams);
}

function addPlayer(team, player) {
  team.players.push(player);
  team.score += player.score;
}

// Sort highest scoring team first
function sortTeams(teams) {
  teams.sort(function(a, b) { return b.score - a.score;});
}

return teams;

One advantage is this always returns the more powerful team first.

This algorithm is not ideal in that it doesn't always choose the most balanced team, for example given players with scores of 8, 4, 3, 3, 1 and 1, Team A will have players 8, 3 and 1 (score of 12) while team b will have players with scores of 4, 3 and 1 (totaling 8). It might be more reasonable to balance them as Team A: 8, 1, 1 and Team B 4, 3, 3 so that both teams have a score of 10. The logic for that might be:

while (input.length > 0) {
  let [strongerTeam,   weakerTeam]   = teams;
  let nextPlayer = input.slice(0,1)[0];
  addPlayer(weakerTeam,   nextPlayer);
  if (strongerTeam.length - weakerTeam.length == input.length) {
    addPlayers(strongerTeam, input);
    input = [];
  }

  sortTeams(teams);
}

function addPlayers(team, players) {
  for (let player of players) {
    addPlayer(team, player);
  }
}


Python's variable names are conventionally named lowercase_width_underscores.

Loop using .items() not .keys() if you will need the values, so your final loop can be:

for numberServed, numberServedStats in masterStats.items():
    print(numberServed)
    for timeToServe, timeToServeStats in numberServedStats,items():
        print("    " + str(timeToServe))
        print("        " + str(timeToServeStats))

The whole thing can be made more efficient by using numpy:

askStats = numpy.array([0, 1, 2])

x = askStats[None,None,:] # put askStats in the third dimension
y = numpy.arange(3)[:, None, None] # put number served in the first dimension
z = numpy.arange(3)[None, :, None] # put time to serve in the second dimension

stats = x + y + z # same as in alter

We create a new array by adding together three existing arrays. The [:,None, None] parts control how they are added. Essentially, the colon indicates the column the data will be spread across. The None indicates where the data will be duplicated. So numpy.arange(3)[:,None] gets treated like

[
    [0, 0, 0],
    [1, 1, 1],
    [2, 2, 2]
]

Whereas numpy.arange(3)[None, :] gets treated like

[
    [0, 1, 2],
    [0, 1, 2],
    [0, 1, 2]
]

This lets us do the complete loop and adjust function in just that one expression.

for line in stats.min(axis=2).flatten():
    print(line)

The min method reduces the 3 dimensional array to 2d array by minimizing along dimension 2. Flatten() converts that 2d array into one long one dimensional array.

for row_index, row in enumerate(stats):
    print(row_index)
    for col_index, col in enumerate(row):
        print("    ", col_index)
        print("        ", col)

It probably won't help much here, but for bigger cases using numpy will be more efficient.


Building a 64 × 64 particle accelerator frame in Minecraft with a computercraft turtle

First of all, use more local. It will save you a lot of headache in the future.

Instead of the three place functions, you could just do

local function selectAnyBlock()
  for i=1,16 -- 4 x 4 inventory
    if turtle.getItemCount(i) > 0 then
      return true
    end
  end
  os.reboot() -- No idea why you'd want to reboot here though
end

and then call turtle.place[up|down]() after that. That saves you two functions and some code.

As for the last two functions, I have no idea what they are supposed to do. They seem to place a block up or down, then turn left and place a block in front?

They also make use of that construct that selects a block in the inventory, so you could replace that with the above selectAnyBlock() function. There's also some places where you have the same instruction (turtle.turnLeft()) in both code paths of a condition. Just place them after the if and you'll only have to write them once.

You don't have to compare booleans to true or false; you can just check for them directly in a condition:

if turtle.compareUp() == false then
  placeup()
  turtle.turnLeft()
else
  turtle.turnLeft()
end

turns into

if not turtle.compareUp() then
  placeup()
end
turtle.turnLeft()

I don't really see a need for object orientation here. Maybe it makes sense in the program overall, but your example works well with just functions. Same goes for anonymous functions; useful as they are, sometimes you just don't need them.

Overall, try indenting your code like everybody else does (each new scope has its own indentation level) and add some comments to clarify your intentions. This not only helps others reading your code, but also yourself in the future :)


How to compare the the Algorithms:

Either determine the complexity of your algorithm and the complexity of the solution in the tutorial.

If you want to avoid to determine the complexity based on the source code you can simply implement the tutorial solution and compare the runtime of your algorithm and the runtime of the of the tutorial-algorithm.
To get a good idea of the complexity behavior of both algorithms you need inputs of different lengths to approximate the runtime related to the size of the input.

How to improve yours
If your approach is very different you might not be able to improve your algorithm by looking on the tutorial-algorithm because they are too different.
If the Tutorial-algorithm is better at all, you can try to understand the steps it does and try to memorize the general idea of this steps for your next algorithms that address similar problems.


Generic and accurate floating point "equality"

Consider using std::nextafter()

The math library includes the function std::nextafter() that will give you the next floating point number with the smallest possible, strictly positive difference with the given number. This is much safer than union-casting a float into an int, because there is no guarantee that two close floating point numbers will also be close as integers. In particular, that is only true if the exponent of both floating point numbers is the same. For example:

bool closeEnough = false;

if (left <= right) {
    do {
        if (left >= right) {
            closeEnough = true;
            break;
        }
        left = std::nextafter(left);
    } while (maxUlpsDiff--);
} else {
    // handle the left > right case
}

return closeEnough;

You'd obviously only want to use this method for small values of maxUlpsDiff.

Is it really what you need?

You are trying to check whether two floating point numbers are close, for two possible ways of closeness: floating point difference, and ULP distance. Is that really what you need? Are you sure that the values you choose for maxDiff and maxUlpsDiff are exactly right? If not, you might get false positives or negatives.

Can you reformulate your floating point calculations into integer calculations? Integers may have a limitted range, but at least they are exact. Maybe you can use them to perform fixed-point arithmetic, or perhaps you can use two integers to form a rational number.


Code bloat

A simple task is simple. Almost 150 lines of code are not justified for such an easy task. You imported Linq so you arguably know about it, actually using it may do very good to your code.

A general, pseudo-code view of the caesarCipher function may be:

public static string caesarEncrypt(string text, int key) {
    return text.Map( x -> alphabet.include?(x) ? shiftChar(x, key) : x );
}

shiftChar may be written as:

return alphabet [ alphabet.index(char) % alphabet.length ]

And you are done.

And caesarDecrypt is just caesarEncrypt with key = 26 - key, there is no need to write the whole thing again.


I would appreciate all criticism relevant to code, style, flow, camelCase vs underscore, and so forth.

First, (contrary to Loki Astari's answer) I think your style is correct (i.e. please do not capitalize the first letter of your classes - keep them matching the std:: style).

Regarding the APIs of your code:

Your code doesn't enforce const correctness
For argument types, consider the following convention:

Observed parameter (no modification of the value in the function)

void function(const argument& a);

I/O parameter (function modifies the parameter, not owner):

void function(argument& a); // a is modified in the function (I/O parameter)

Owned parameter:

void function(argument a); // function "owns" a (gets it's own exclusive copy)

Following this, push() and top() should be written like this:

template<typename T>
void stack<T>::push(T data) // pass by value here
{
    root = new node{ std::move(data), root }; // and move the value here
    ++elements;
}

template<typename T>
const T&                // return a const T&
stack<T>::top() const   // and function is const
{
    if (!root)
        throw std::runtime_error("stack<T>::top: empty stack");
    return root->data;
}

Taking a parameter by value in push has these advantages:

specifies ownership in the interface
enables you to use all constructors of type T here
is exception safe (if the instance of the arg cannot be created, code will fail before entering the function body).
The size API:

int size();

Should be:

std::size_t size() const;

The print API has more problems:

It clears the list (either rename to "destructive_print", or ensure the iteration is not destructive). If you implement it in a non-destructive way, mark it const.
It introduces a dependency on std::cout that has nothing to do with the functionality of objects. Ideally, it shouldn't be a member. If you still want to have it as a member, pass the output stream instance as a parameter.

The constructor of the node class should construct a fully valid instance in one step. To decide on it's parameters, you should look at how you use it:

Usage example (your old code):

root_node = new node;
root_node->node_data = data;
root_node->next = nullptr;

Optimal example (new client code):

root_node = new node{ std::move(data), root_node }; // use std::move on the data

implies the node should be implemented like this:

template <class T>
class stack {
    // ...
    struct node { // struct, because it is internal and only
                  // access will be in stack
                  // (i.e. we can guarantee correct use in client code)

         T *node_data;
         node* next;
    };
}

The size should also be of std::size_t type.

Your stack doesn't have a destructor. The destructor should call delete on each node, in an iteration).

Your print element skips the last element in the list, as you begin indexing from 1 instead of 0, to less than number of elements. This means you iterate [elements - 1] times.

The pop() implementation can be written with no special case for one element:

template <class T>
void stack<T>::pop() {
    if(empty())
        throw std::runtime_error{"stack<T>::pop(): empty stack"};

    node* new_root = root_node->next;
    delete root_node;
    root_node = new_root;
    --elements;
}

Regarding the implementation of your class:

Do not print error messages, throw exceptions (this allows client code to decide what to do in case of an error, instead of forcing client code to get messages printed into it's application's output stream).


Simple Bash Parallel Tool (env_parallel dies on big env)

A couple of things could be written better, let's go from top to bottom.

It's recommended to double-quote variables when used as paths,
to avoid globbing and word-splitting.
Even if you're certain that $TMP_FILE won't have any troublesome characters, it's a good practice to double-quote anyway:

touch "$TMP_FILE"

Similarly, you should double-quote $prog in $prog 1>$PROG_TMP 2>&1.

You can simplify for arg in "$@"; do loop as for arg; do.

In Bash, instead of prog 1> somewhere 2>&1 you can write prog &> somewhere.

Instead of this:

RESULT_COUNT=$(wc -l ${TMP_FILE} | awk '{ print $1 }')

You could write simpler without awk like this:

RESULT_COUNT=$(wc -l < "$TMP_FILE")

The trick is that when wc is used with stdin,
it won't print a file name, only the number.
Although RESULT_COUNT will have some whitespace padding,
if you use it in [ ... ] without double-quoting,
it will behave as expected.

Notice again that I double-quoted $TMP_FILE.

Don't use -eq in [[ ... ]], use == or = instead.

This is pretty ugly:

if [[ $(cat $TMP_FILE) == *"1"* ]]; then

A better way to achieve the same thing is using grep:

if grep -q 1 "$TMP_FILE"; then


One simple improvement would be to restructure the for() loop:

for(int i = input.length() - 1; i >= 0; --i){
    std::cout << input[i];
}

A simple decrement operation might lead to more efficient machine code than calculating input.length() - i in every iteration.

Another improvement would be to use a more c++-ish way. But that means to change the string itself:

 std::getline(std::cin,input);
 std::reverse(std::begin(input),std::end(input));
 std::cout << input << '\n';

Or using the reverse iterators in the loop:

 for(auto it = input.rbegin(); it != input.rend(); ++it) {
      std::cout << *it;
 }

As I've mentioned in my comment, the most generic (and c++stylish) way to achieve that is to write your own adapter to achieve iterating a sequence in the reverse order. So I'm citing that solution here:

 // -------------------------------------------------------------------
 // --- Reversed iterable
 using namespace std; // for rbegin() and rend()

 template <typename T>
 struct reversion_wrapper { T& iterable; };

 template <typename T>
 auto begin (reversion_wrapper<T> w) { return rbegin(w.iterable); }

 template <typename T>
 auto end (reversion_wrapper<T> w) { return rend(w.iterable); }

 template <typename T>
 reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; }

Above taken from here.


Calculate "average", "median" and "percentile" from a long array

Validate your inputs

The median and average methods will throw an exception if the input array is empty. Think of the preconditions and if there are safe assumptions (input will never be empty) then document it, possibly with an assert statement, for example:

assert numbers.length > 0;

Note that the primary purpose of asset statements is documentation. Although a failed assert will crash the program, but only during development, as assert statements are removed from release builds, and so don't get executed in production. If you want to validate input, use exceptions instead.

Watch out for corner cases

This statement may overflow if the two numbers are too big:

return (numbers[middle - 1] + numbers[middle]) / 2.0;

To avoid overflow, you could divide each by 2 and then sum.

Simplify

If you omit the second and third parameters of Arrays.sort, by default it will use 0 and the length of the array. So you can omit these parameters in all your examples.

There is already a library method to calculate average:

return LongStream.of(numbers).average();


In your HTML View you can use this
<file name="upload[]" accept="image/*" multiple> multiple and accept attribute is only available in HTML5 dosen't work in old browsers.

<?php
    $files = null;
    $errors = null;

    define('IMAGE_TARGET',SITE_ROOT.'j2reimage'.DS.'image');

    if(!empty($_POST['submitImage']))
    {
        $files = $_FILES['upload'];
        $errors = array();

        if(!empty($files))
        {
            //Move extension list to here you don't need redeclarate variables inside loop
            $valid_extensions = array('jpeg','jpg','png','gif');

            foreach($files as $file)
            {

                    //Don't use explode for extensions
                    //$file_ext = explode('.',$file['name'][$key]);
                    //Use pathinfo
                    $path_parts = pathinfo($file);
                    $file_ext = $path_parts['extension'];

                    //$file_ext=strtolower(end(explode('.',$file['name'][$key])));

                    if(in_array($file_ext,$valid_extensions) === false)
                    {
                        $errors[] = ".$file_ext extension not allowed";
                    }
                    else
                    {
                        $filetmp = $file['tmp_name'][$key];

                        $dat = strftime("%Y-%m-%d %H:%M:%S", time());

                        if(file_exists(IMAGE_TARGET.DS.$file['name']))
                        {
                            //move_uploaded_file( $filetmp, $terget_path.'/'.$file['name'][$key]);
                            mysql_query("INSERT INTO 4j2memberimage VALUES ('', $memmem->id,'{$file['name']}', '$dat')");

                            //if(move_uploaded_file($filetmp, $terget_path.'/'.$file['name'][$key] ))

                            //Use copy insteds of  move_uploaded_file sometimes you have right problems in some servers.

                            if(copy($filetmp, IMAGE_TARGET.DS.$file['name'] ))
                            {
                                $exe = explode(".", $file['name']);
                                $ext = $exe[1];
                                $w = 250;
                                $h = 250;
                                $target  = IMAGE_TARGET.DS.$file['name'];
                                $newcopy = IMAGE_TARGET.DS.'thumb_'.DS.$file['name'];

                                list($w_orig, $h_orig) = getimagesize($target);
                                $scale_ratio = $w_orig / $h_orig;

                                if (($w / $h) > $scale_ratio)
                                {
                                    $w = $h * $scale_ratio;
                                }
                                else
                                {
                                    $h = $w / $scale_ratio;
                                }

                                $img = '';
                                $ext = strtolower($ext);

                                switch($ext) {
                                    case 'gif':
                                        $img = imagecreatefromgif($target);
                                        break;
                                    case 'png':
                                        $img = imagecreatefrompng($target);
                                        break;
                                    case 'jpeg':
                                    case 'jpg':
                                        $img = imagecreatefromjpeg($target);
                                        break;
                                }

                                $tci = imagecreatetruecolor($w, $h);
                                imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);

                                if(@imagejpeg($tci, $newcopy, 80))
                                {
                                    //return true;
                                    $target_path = $target;
                                    //$terger_path = SITE_ROOT.DS.$this->img_path.DS.$this->filename;
                                    file_put_contents($target_path,$img);
                                    //return unlink($target_path) ? true : false;
                                }
                            }
                            //end of if file_exists
                        }
                        else
                        {
                            $errors[] = 'Upload extention could not be located';
                        }
                    }
                    //redirect_to('inb.php');
                }//foreach
        }
        else
        {
            $errors[] = ' The file could not be empty ';
        }//if
    }//if


GET and POST with Flask - optimum performance

You can avoid the Content-Type check by using request.get_json() method.

from werkzeug.wrappers import BaseRequest
...

try:
    data = request.get_json()
except BadRequest:
    return (jsonify(message="Bad Request"), 400)

message = data['message']
digest = sha256(message.encode('utf-8')).hexdigest()
redis.set(sha, message)
return (jsonify(digest=digest), 201)

Use better variable names, message can be replaced with data and message variable can be used to store the actual message from data. Similarly sha can be replaced with digest.
The else blocks in both functions can be removed as the corresponding if blocks are already returning. I personally find lesser indented code much easier to read and it also helps in keeping the Cyclomatic complexity low.
There are no check against the data being passed by the user, for example message can be passed as an empty string, None, integer etc. You probably want to use some sort of validation here.


Complementary multiply with carry in Rust

Run rustfmt.

When the preceding thing fits on a single line, curly braces go on the same line:

pub fn get_random_cmwc() -> u32 {

Binary operators have space on both sides:

self.c += 1;

Curly braces always have whitespace around them:

for i in 3..CMWC_CYCLE as usize {

Run clippy:

warning: unneeded return statement
  --> src/lib.rs:55:13
   |
55 |             return self.q[self.i];
   |             ^^^^^^^^^^^^^^^^^^^^^^ help: remove `return` as shown: `self.q[self.i]`
   |
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#needless_return

warning: the loop variable `i` is used to index `q_init`
  --> src/lib.rs:22:13
   |
22 | /             for i in 3..CMWC_CYCLE as usize {
23 | |                 q_init[i] = q_init[i - 3] ^ q_init[i - 2] ^ PHI ^ seed;
24 | |             }
   | |_____________^
   |
   = note: #[warn(needless_range_loop)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#needless_range_loop
help: consider using an iterator
   |             for (i, <item>) in q_init.iter().enumerate().take(CMWC_CYCLE as usize).skip(3) {

You really should have some tests. Without them, you cannot tell that refactoring hasn't changed anything, or that you are producing the same value as other implementations of the algorithm. Also, running even a single test would have shown..
You need to think about integer overflow semantics! By default, Rust will panic if an integer overflows in debug mode. Setting q[2] in the initializer causes such an overflow!
The module is providing no obvious benefit. Since you already have the namespace of the crate, just use that directly.
use statements belong at the top of the file, unless they are scoped within a method.
CMWC_CYCLE is always used as a usize, so just make the constant a usize.
Many of the places that CMWC_CYCLE is used could be replaced with an equivalent call to .len().
Your struct takes over 16K of space, which seems very large for the stack. You may wish to consider switching q to a vector.
Instead of Clippy's suggestion, I might slice out a little mutable window of q. To me, this better expresses the initialization logic.
The initial value of i really looks likes CMWC_CYCLE - 1
(self.i + 1) & (CMWC_CYCLE - 1) looks to be a cutesy way of saying (self.i + 1) % CMWC_CYCLE. If so, I'd rely on the optimizer to do the right thing.
Your reset is just replacing self with the result of new, so its usefulness seems low. See mem::swap.
I really don't like global state. If your C code needs to have it, I'd only use the singleton in those two exported functions, inlining the Rust functions. If Rust code calling this needs to create a singleton, it should do so itself.
If you really want to solidly avoid name conflicts, you should add the major and potentially the minor version of your library to any extern "C" functions in addition to the library name. Otherwise you cannot link in multiple conflicting major versions.
Avoid usage of unwrap. Generally, you should favor handling the error. In terminal cases, prefer to use expect so that when the impossible case happens, you have a hint where the problem was.
In general, you often want to split the Rust code and the exposed C shims into different crates. In this case, only the C shims need lazy-static.

#[macro_use]
extern crate lazy_static;

const CMWC_CYCLE: usize = 4096;
const PHI: u32 = 0x9e3779b9;

use std::sync::Mutex;

struct ComplementaryMultiplyWithCarryGen {
    q: [u32; CMWC_CYCLE],
    c: u32,
    i: usize,
}

impl ComplementaryMultiplyWithCarryGen {
    fn new(seed: u32) -> ComplementaryMultiplyWithCarryGen {
        let mut q = [0; CMWC_CYCLE];

        q[0] = seed;
        q[1] = seed.wrapping_add(PHI);
        q[2] = seed.wrapping_add(PHI).wrapping_add(PHI);

        for i in 3..CMWC_CYCLE {
            let window = &mut q[i - 3..i + 1];
            window[3] = window[0] ^ window[1] ^ PHI ^ seed;
        }

        ComplementaryMultiplyWithCarryGen {
            q: q,
            c: 362436,
            i: 4095,
        }
    }

    fn reset(&mut self, seed: u32) {
        *self = ComplementaryMultiplyWithCarryGen::new(seed);
    }

    fn random(&mut self) -> u32 {
        const A: u64 = 18782;
        const R: u32 = 0xfffffffe;

        self.i = (self.i + 1) & (CMWC_CYCLE - 1);
        let t = A * self.q[self.i] as u64 + self.c as u64;

        self.c = (t >> 32) as u32;
        let mut x = (t + self.c as u64) as u32;
        if x < self.c {
            x += 1;
            self.c += 1;
        }

        self.q[self.i] = R - x;
        self.q[self.i]
    }
}

// Lazy singleton random number generator
lazy_static!{
    static ref GLOBAL_CMWC_GEN: Mutex<ComplementaryMultiplyWithCarryGen> =
        Mutex::new(ComplementaryMultiplyWithCarryGen::new(0));
}

// Public exports for PointGenLib
// All prefixed with pointgen_ to avoid name conflicts
#[no_mangle]
pub extern "C" fn pointgen_set_cmwc_seed(seed: u32) {
    GLOBAL_CMWC_GEN.lock()
        .expect("Cannot lock to set seed")
        .reset(seed);
}

#[no_mangle]
pub extern "C" fn pointgen_random_cmwc() -> u32 {
    GLOBAL_CMWC_GEN.lock()
        .expect("Cannot lock to produce number")
        .random()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn i_didnt_change_anything() {
        let mut rng = ComplementaryMultiplyWithCarryGen::new(0);
        let n: Vec<_> = (0..10).map(|_| rng.random()).collect();
        assert_eq!(n, [4294604858, 367747001, 735501178, 4294962861, 735512785, 3666536092, 3666528614, 4294955383, 367747001, 735501178]);
    }
}

  having q_init be mut seems like a hack

It's not, really. The trick is that an entire array has to be guaranteed to be initialized. There's no way for the compiler to tell that some later code will finish initializing the array, especially in the presence of panics. Thus you need to initialize the array with something and then go back and fill in the real values. As mentioned above, you could also switch to using a Vec. Since a Vec has a dynamic size, you can construct it from an iterator, allowing you to avoid mutability at the call site.

  Is this an appropriate struct to use the Default trait? I read that it's not recommended to use that.

Where did you read that? I'd like to check out to understand why it says so.

In general, Default is fine — so long as there's a reasonable default! Does a random number generator have a reasonable default? My gut feeling is "yes", but only if you have access to a true RNG that you can use to seed yourself. If you don't have access to a true source of entropy, then not implementing Default is a sign to the user that it's up to them.

  There's a lot of as usize around, I don't quite have the feel for casting types as I would do in C++.

Rust generally requires you to be more explicit. After the previous change to CMWC_CYCLE's type, there are a lot fewer of these. The remaining ones deal with cases where you are adding values to a u32 that will exceed the capacity and thus you temporarily need a u64. This seems like nice indication that something "non traditional" is happening there.


If you're aiming for KISS at the level of maintenance, this looks like a reasonable solution, although there are some minor details which IMO could be improved.

public class UniqueBufferBlock
{
    private readonly BufferBlock<string> _buffer = new BufferBlock<string>();
    private readonly HashSet<string> _hashSet = new HashSet<string>();

Why not genericise the class?

    public string Recieve()

Fix that spelling. Incorrectly spelt names are one of the banes of the maintenance programmer.

    public Task<bool> OutputAvailable(CancellationToken cancelToken)

Follow conventions: this should have a name ending Async, like the method it wraps.

There are a couple of other directions which might be worth considering. One is to go the full hog and implement IPropagatorBlock. The other is to slim down the dependencies by removing _buffer and implementing OutputAvailableAsync with TaskCompletionSource. Both would make the implementation of UniqueBufferBlock more fiddly, and it's reasonable to decide not to go in either direction.

PS on a point of English language pedantry: distinct is a better choice of word than unique. Perhaps deduplicated would be better still in this context.


One major drawback...

public void Insert(T entity)
{
    context.Set<T>().Add(entity);
    context.SaveChanges();
}

...is that you've just destroyed the usefulness of a unit of work. DbContext wraps a database transaction, and what's great about transactions, is that they allow you to commit a "set" of changes all at once.

But you're calling SaveChanges every time anything happens to any entity, which means if you have 1 request doing 20 calls into that repository, you're effectively committing 20 transactions.

A new unit of work instance should be created, and die with each request: SaveChanges should be called, ideally, exactly once in the lifetime of the DbContext.


It is generally not a good idea to do this type of processing in the .ctor.  Move it to a Load (or some such name) method.  This however means your object is not really loaded after instantiated which is another issue.  As such, I would recommend separating the entity information (HasFullControl, Creator, GroupName, etc) type from the type that loads the information from the database.  You could change PermissionGroup type to just have the data properties and then move the loading logic to a data layer that is responsible for creating the instance a loading the data.

Concatenating text to the end of a sql string leaves you open to Sql Injection attacks (though not in this specific case).  Use a parameter instead:

using (SqlCommand cmd = new SqlCommand("SELECT creatorUserID, group_name,
    fullControl FROM tblATPermissionGroups WHERE ID = @id", cn))
{
    cmd.Parameters.AddWithValue("@id", id);
    ...
}

You need to wrap the SqlDataReader in a using block.

Use public readonly properties rather than public fields.

Consider using a IDbConnection rather than SqlConnection.  Doing so will allow you to more easily mock the data call when testing this method and makes it easier to support other RDBMS's should the need arise.

Throw helpful exceptions if something goes wrong when populating the data fields.

Follow the .Net Framework naming guidelines


Check source code of the GSL library that is really well designed.
It includes implementations of many numerical integration algorithms.


Using matlabpool: Is my embedding correct?

Seems to be fine according to the documentation.

The only things you need to try are whether 12 is the best number for you, and whether it makes sense to close the matlabpool earlier (you might not gain anything from it for a postprocessing part). Furthermore it is of course always good to check whether it actually gives the speed increase that you are looking for.


Kattis, Speed limit; read irregular input

Your approach to the problem seems very imperative and whole-problem focused. Thinking in Haskell generally benefits from considering more bottom-up strategies, using smaller, easily tested, reusable pieces.

Right off the bat, your representation of the core datatype (a log of speeds and timestamps) seems ill-fitted. A list of list of Ints doesn't capture the fact that you know you will only be receiving pairs of numbers at a time.

type Speed = Int
type Timestamp = Int
type LogLine = (Speed, Timestamp)
type Log = [LogLine]

-- Less vitally...
type Logs = [Log]

Type aliases help provide documentation to readers of your code (including you as you write it, or come back to it after any significant stretch of time), use them liberally when working with the basic datatypes. The above set of aliases captures the input as it will be given to you (post- the act of parsing). Lists of pairs of numbers in the string input become []s of (,)s of Ints in Haskell.

Next we have to determine what sort of format we want to transform the data into in order to calculate an answer from it. The problem would be simple if we could replace those timestamps with durations, so we'll figure out a way to do that.

type Duration = Int

durations :: [Timestamp] -> [Duration]

Note that speeds won't be relevant when converting timestamps to durations, but we will need all of the timestamps in a log in order.

Once we have speed and duration pairs, solving for the solution should be easy.

type Distance = Int

calculate :: [(Speed, Duration)] -> Distance
calculate = sum . map (uncurry (*))

And if we hop in GHCi and test that definition with some hand-crafted data (i.e., the worked example given in the problem statement)—

λ sum . map (uncurry (*)) $ [(20, 2), (30, 4), (10, 1)]
170

Looks good. Now we work backward, filling in the pieces we left undefined, and combining them together as appropriate.

durations :: [Timestamp] -> [Duration]
durations ts = zipWith (-) ts (0:ts)

solve :: Log -> Distance
solve ls =
  let (speeds, timestamps) = unzip ls
  in  calculate $ zip speeds (durations timestamps)

With a little more consideration (and certainly if we were willing to pull in the lens library) we could code golf the unzip/zip away and end up with a pithy one liner for solve, but often the most straightforward solution is more than adequate.

Now we need only deal with the parsing and pretty-printing aspects of the problem. Given that all of these code challenge tasks are similar, much of this is boilerplate you reuse from problem to problem, just make sure you're familiar with the contents of the Control.Monad module.

main :: IO ()
main = do
  n <- readLn
  if n == -1
  then return () -- End flag, don't recurse
  else do
    log <- replicateM n $ do
      [speed, timestamp] <- map read . words <$> getLine
      return (speed, timestamp)
    let distance = solve log
    putStrLn $ (show distance) ++ " miles"
    main -- recurse, look for the next trip


You should prepare a set of sentences to slugify and verify by yourself if your function is ok.

Below are the step I use to slugify text:

Use iconv() if available:

$slug = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
Lowercase the text, taking Unicode into account:

$slug = mb_strtolower($slug);
Remove unwanted characters like you do:

$slug = preg_replace('/\W+/', '-', $slug);

These are the steps used in Propel ORM or symfony framework for example.
The complete code can be:

function slugify($text, $separator = '-')
{
  // transliterate
  if (function_exists('iconv'))
  {
    $slug = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  }

  // lowercase
  if (function_exists('mb_strtolower'))
  {
    $slug = mb_strtolower($slug);
  }
  else
  {
    $slug = strtolower($slug);
  }

  // remove accents resulting from OSX's iconv
  $slug = str_replace(array('\'', '`', '^'), '', $slug);

  // replace non letter or digits with separator
  $slug = preg_replace('/\W+/', $separator, $slug);

  // trim
  $slug = trim($slug, $separator);

  return $slug;
}

I think $text is a better name than $input for the string to slugify.


Well you may or may not considered this a simplification but this is how I would approach it.

You could use a set to handle the duplication part.

You can't store a dict in a set though so we need to create a tuple from the values. (It looks like you're doing something similar with filtered)

We then reformat result to get the desired final structure.

from collections import defaultdict

result = defaultdict(set)

for item in json_data:
    parent   = {'name': 'NoLevel_1'}
    children = []
    for tag in item['tag']:
        if tag['taglevel'] == 1:
            parent = tag
        else:
            children.append((tag['taglevel'], tag['name']))
    result[parent['name']].update(children)

result = [
    {
        'name': parent,
        'tag_child': [
            {'name': name, 'taglevel': taglevel} for taglevel, name in tags
        ],
        'taglevel': 1,
    } for parent, tags in result.items()
]

You could use next() and a list comprehension for the parent and child creation however it iterates the tags twice and may not be as "readable"

parent   = next((tag for tag in item['tag'] if tag['taglevel'] == 1), {'name': 'NoLevel_1'})
children = [(tag['taglevel'], tag['name']) for tag in item['tag'] if tag['taglevel'] != 1]


JavaScript has an array data type that acts like different data structures. It can be a list, a stack, or even a queue depending on how you use it. If this code is merely for learning purposes, then it's fine. Otherwise, try using available native data structures instead of reinventing them.

Now to your code. First off, I would suggest against using constructors and use basic object literals and functions instead. It is simpler to think of data simply as a structure of arrays and objects.

this.add

Very vague name. It's not clear whether we're adding a new node (where we pass in a new instance of Node) or adding a value (that the method will wrap for us, which it currently does). It's best if you make it more verbose, like addValue.

if(this.length == 0)

length is a function of the number of nodes in the list. A common problem I had in data structures class is if the length value was out of sync with the actual node count value. This made very interesting bugs when length and the actual node count didn't match up.

To get the length, it's better, although inefficient, to actually count the nodes present. Alternatively, a list without a head is essentially an empty list. if(!this.head) is sufficient to determine an empty list.

temp = this.head;
while(temp.next){
  temp = temp.next;
}

This can be extracted to a findTail function which can be really useful. Alternatively, keeping track of the tail like you're doing with head is also a convenient and more efficient way to do this. Not sure if there are standards to linked lists, but it's an optimization you can take advantage.

this.search = function (value){}

I don't really get the point of search. Is it supposed to just print a message if it exists? If it does, it's better named like printMessageIfValueExists. Otherwise, one would take it as a function that takes a value and returns a boolean representing its existence.

Also, a linked list best remain a data structure. It shouldn't handle printing as this makes it dependent on printing capabilities of the environment, an unnecessarily coupled dependency. Leave that to whatever code is using the linked list. Same goes for your print method.

this.removeAtIndex = function (index)

Again, another one of those vaguely-named functions. Why? It's because we're not sure what "remove" exactly means. It could mean removing the value or removing the node entirely. I see that it's removing a node, so it should be removeNodeAtIndex.


Determine if a String can be parsed to LocalDateTime or Int

(Disclamer: I only know Kotlin theoretically)

You can avoid the second try/catch by using String.toIntOrNull instead of String.toInt.

And by extracting the LocalDateTime conversion into a separate function, that also returns null when it fails (which also would help fulfill the single responsibility principle), you could then use a functional approach with the safe call operator (?.), the Elvis operator (?:) and the run extension method:

enum class RangeValueType {
    INT,
    DATE,
    STRING
}

fun parseLocalDateTime(value: String): LocalDateTime? {
    try {
        return LocalDateTime.parse(value)
    } catch (dtpe: DateTimeParseException) {
        return null;
    }
}

fun parseValue(value: String): Pair<RangeValueType, Any> {
    return parseLocalDateTime(value)?.run { Pair(RangeValueType.DATE, this) } ?:
             value.toIntOrNull()?.run { Pair(RangeValueType.INT, this) } ?:
             value.run { Pair(RangeValueType.STRING, this) }
}

Runable version

(NB: enum constants should be written all capitalized so they are not confused with types.)


Change all pixels that lie in a given color range to a new color

Improving the general implementation

Generally we want to avoid appending to a list too many times if we can help it. This is because lists are dynamic arrays, so appends can be unnecessarily expensive (though the dynamic part helps with the efficiency). Instead, when we know the size of the input set (i.e. the number of pixels in the image), we can take advantage of that information. But in this case, that will be unnecessary because Image provides us with some handy helper methods to handle this very situation:

from PIL import Image

def picture_reset_pixels(filename, from_color, to_color, target_color):
    img = Image.open(filename)
    pixels = img.load()
    for i in range(img.size[0]):
        for j in range(img.size[1]):
            if all(from_color[k] <= pixels[i, j][k] <= to_color[k] for k in range(3)):
                pixels[i, j] = target_color + (255,)
    return img

Assigning pixels to img.load() allows us to take advantage of directly editing the image. Since copying the image into another list was unnecessary originally (to clarify, the img variable doesn't affect the file on disk that img originated from, i.e. the file at location filename), editing directly is the best way.

Edit 2: Looking at it again, I think @Reinderien's point about clarity has merit because range has an exclusive upper bound, which may be confusing because it is asymmetric relative to both of its arguments. I have edited to use the comparison operators <= and >= instead of the range check I mention ahead. The caveat only I have is that using the in range form is more similar to how I think a dedicated ColorRange object (mentioned ahead in the section Going beyond the current form) should handle a range check, since it's not necessary to expose the object's implementation details (though internally, it could still use comparison operators for the check).

Another general improvement I've taken advantage of in this implementation is using range to check if each of the RGB values of a pixel are between the two pixel boundaries of the input arguments. all() serves the purpose that the and statements in the original version served: it requires that all the pixels compared in the iterator pixels[i, j][k] in range(from_color[k], to_color[k] + 1) for k in range(3) are in the required range for the condition to be true.

Edit 1: the concern was raised in comments that testing for in range(from_color[k], to_color[k] + 1) would be extremely inefficient. However, this is mistaken and arises from a misunderstanding of how Python 3.x implement the range object. Checking if a number is in a range is a constant time operation. I would recommend reading this answer to understand Python 3.x's range implementation.

Going beyond the current form

While I've shown you a way to use your current parameter requirements in a more efficient implementation, I think there are some improvements you can make so picture_reset_pixels has more functionality. I think combining from_color, to_color, and target_color into a single dict parameter color_replacements could make this more versatile (where the key-value pairs would derive something like {(from_color, to_color): target_color}; you could even create a custom ColorRange class to encapsulate the idea of a range of colors).

There's also another issue I find with your current implementation: it can only support certain image types. I tried your algorithm on a GIF file and it failed because the pixels in a GIF file are ints, not four-tuples like PNGs. You also do not support the fourth alpha channel of PNG, because your pixel range bounds are only 3-tuples. You might want to consider investigating that further if you want to support multiple image types.


free(pStr) is misplaced. Once it is freed, you may not touch it anymore. Calling check_palindrome2(pStr) after freeing causes an undefined behavior.

Consider

    int rc = check_palindrome2(pStr, i);
    free(pStr);
    return rc;

check_palindrome2 could be called with a null pointer, but doesn't test it.
current_size += len_max is more clear than current_size = i+len_max.
read_palindrome is a misnomer. It doesn't read a palindrome. It reads a string of an unknown length. Now, SRP mandates splitting it into independent read_line and is_palindrome functions.
You test malloc for a failure. Keep in mind that realloc may fail as well.

    char * tmp = realloc(....);
    if (tmp == NULL) {
        free(pStr);
        return error;
    }
    pStr = tmp;

NB: a simple pStr = realloc(....) is not good. If realloc fails, you'd have a memory leak.


Inefficient Python script eating up memory (I believe)

#!/usr/bin/python
# -*- coding: utf-8 -*-

import wx, sqlite3, datetime, threading
from appscript import *

import * is frowned upon as it makes it difficult to trace where names came from.

it = app('iTunes')

I recommend avoiding abbreviated names like it its hard to figure out what it means later.

from AppKit import *

# Create the DB
Tapedeck = sqlite3.connect('Tapedeck.db', check_same_thread = False)
TapedeckQuery = Tapedeck.cursor()
Tapedeck.execute('''CREATE TABLE IF NOT EXISTS plays (id INTEGER PRIMARY KEY, track_id TEXT, track TEXT, artist TEXT, album TEXT, genres TEXT, play_count INTEGER, rating INTEGER, skip_count INTEGER, year_released INTEGER, date_played DATE)''')
Tapedeck.commit()

Generally, performing actions at the module level is frowned upon. You should do it in a main function.

def getSec(s):

Python style guide recommends lowercase_with_underscores for function names. Also, don't needlessly abbreviate.

    l = s.split(':')
    return int(l[0]) * 60 + int(l[1])

I'd have done:

minutes, seconds = s.split(':')
return int(minutes)*60 + int(seconds)

I think its easier to see what's going on

def addTrack(track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating):
    #print '        --\n        Position: {}\n      Length: {}'.format(it.player_position(),getSec(it.current_track.time()))
    TapedeckQuery.execute('''INSERT INTO plays (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating) VALUES (?,?,?,?,?,?,?,?,?,?)''',
    (track_id, track, artist, album, genres, play_count, skip_count, year_released, date_played, rating))
    Tapedeck.commit()

loop_int = 1.0
last_track = '0'

def listen():

    global loop_int, last_track

Avoid global variables. You should generally only be using globals as constants.

    threading.Timer(loop_int, listen).start()

Python isn't Javascript. Instead of playing with threads, use time.Sleep(1) to sleep for a second between each attempt. Put everything in a loop. It'll be easier to follow.

    if it.player_state() == k.playing:
        # check to see if track was restarted
        if it.player_position() < getSec(it.current_track.time())/2 and last_track == it.current_track.persistent_ID():
            self.last_track = '0'

self?

        # has the track played beyond the halfway mark?
        if it.player_position() >= getSec(it.current_track.time())/2 and last_track != it.current_track.persistent_ID():
            today = datetime.datetime.today()
            now = '{}-{}-{} {}:{}:{}'.format(today.year, '%02d' % today.month, '%02d' % today.day, '%02d' % today.hour, '%02d' % today.minute, '%02d' % today.second)

The datetime has a formatting function which may be better suited to that

            print '\nArtist:        {}\nTrack:      {}\nAlbum:      {}\nGenres:     {}\nDatetime:   {}'.format(it.current_track.artist().encode('ascii','ignore'), it.current_track.name().encode('ascii','ignore'), it.current_track.album().encode('ascii','ignore'), it.current_track.genre().encode('ascii','ignore'), now)
            last_track = it.current_track.persistent_ID()
            addTrack(it.current_track.persistent_ID(), it.current_track.name(), it.current_track.artist(), it.current_track.album(), it.current_track.genre(), it.current_track.played_count(), it.current_track.skipped_count(), it.current_track.year(), now, it.current_track.rating())

listen()

As for your actual problem. I don't know this appscript/AppKit you are using. But I'll speculate that under some circumstances iTunes stops responding. Maybe a dialog gets popped or something. As a result, each thread gets stuck waiting for iTunes. But because you set the timer as your first action, a new thread keeps getting started which also gets stuck. Eventually, your poor scripts piles many many threads and that explains the hang.

If you use the sleep method I suggested above, that should prevent the script from running many threads.


Ideally I'd like to use termcap or terminfo or the like to clear the terminal without shelling out. Alas, it seems Chicken doesn't have an egg for either termcap or terminfo. (It does have an egg for curses, but I consider that to be too heavyweight for just clearing a terminal.)
I'd probably use for-each for iterating through the items in show-sequence, rather than the recursive approach you have:

(define (show-sequence seq)
  (for-each (lambda (x)
              (clear-screen)
              (make-delay)
              (display x)    ;; not write
              (make-delay))
            seq)
  (clear-screen)
  (display "GO!\n"))

Not a huge fan of making a get-player-input function that's exactly the same as read-line. I'd just call read-line directly.
Your definition of make-sequence is quite clever, but it's not very idiomatic. Since you have SRFI 1 loaded, I'd just use list-tabulate:

(define (make-sequence len)  ;; not length
  (list-tabulate len (lambda (_) (random button-count))))

You can simplify player-sequence-matches? by using SRFI 1's every:

(define (player-sequence-matches? seq)
  (every (lambda (x)
           (= (string->number (read-line)) x))
         seq))

And since Chicken has cut builtin, you can simplify even further:

(define (player-sequence-matches? seq)
  (every (cut = (string->number (read-line)) <>) seq))

For calculating the total score, I'd rather accumulate the score, rather than use recursion to hold the score. Like so:

(define (simon-says difficulty)
  (let loop ((difficulty difficulty)
             (score 0))
    (define seq (make-sequence difficulty))
    (show-sequence seq)
    (if (player-sequence-matches? seq)
        (loop (add1 difficulty) (add1 score))
        score)))

This way, the function is totally tail-recursive.


Function that checks two objects with same fields and assigns old non-null values to new object if new values are empty or null

Very bad code

Your code is very poorly written making it difficult to workout what your intent is.

The try catch was a red flag and immediately told me not to trust the code.

Looking further at your code I found it full of redundant code and conflicting logic.

List of problems

if (reference[prop] != undefined || reference[prop] != null) {

Is the same as if(A == true || A == false) {

This is always true, if A is not true, then it is true that A is false

That makes the else and the associated block redundant (will never happen)
if ( /*...*/ && typeof Array.isArray(originalReference[prop])) {

typeof creates a non empty string. Thus the second half of the above statement is always true and thus redundant.
if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object')   and

if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {

If reference[prop] is an array, null, or an object and originalReference[prop] is an array, null, or object then both the above statements are true, which I think is not your intent.
var length = Object.keys(reference[prop]).length;

length is never used making this line redundant.
reference[prop].forEach((item, index) => vm.evaluateEmptyValues(item, originalReference[prop][index]))

It is common for objects to contain references to themselves, or have properties that reference them selves. Thus this type of recursion can end up in an infinite loop. Luckily JS has a finite call stack that will cause an exception to be thrown, but as you catch the errors rather than stop, it will grind to a stop as it throws overflow error after error till it gets past all the self references.

Minor points

var vm = this;

The reference to vm is used in the previous point. The forEach is using an arrow function that maintains the outer context of this. The variable vm is thus redundant.
referenceLength = Object.entries(reference).length;

Object.entries creates an array of arrays. [[key, value], [key, value], ...] You should use Object.keys or Object.values if you want the number of properties.
typeof (reference[prop]) == 'string'

typeof is a token not a function and does not need to be followed by a pair of ()
Use === or !== rather than == or !=

Comments just add to the mess

Your comments are noise if they repeat what is self evident in the code.

Or worse, comments are lies when in direct conflict with the code

You should only comment when the code can not represent the higher level abstraction that the logic is implementing. This is usually rare.

The better the code the less comments are needed to understand what is going on.

Some examples

// Do another loop

for (var property in reference[prop]) {

Really!... a loop you say.
// Check if current prop in both objects is an object

if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object') {

Again the comment is repeating what is self evident in the code.
if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {

// Recurse if both are arrays

No its not?... The comment is in direct conflict the the statement above it.

Summing up

Sorry to be so harsh, but your code is boarder line on topic for code review. You need to be much more careful when writing code.

I think part of the problem is the very long naming and indirect referencing (eg originalReference[prop][property]) you are using which is making it hard to see the logic from the referencing.

Your code is nested up to 10 times, and one line is over 120 characters long. In that line of the 100 characters (ignoring indent/white spaces) 71 characters are naming, and only 29 are part of the logic. Little wonder you are making obvious logic mistakes in the code, you can not see the wood from the trees.

There are a variety of other problems in your code that I did not address.


Looks pretty good to me. Regarding conn.close(), definitely don't put this in its own try statement, because if there's a problem with the earlier code, the connection might not get closed. I know you're not using Python 3, but ss an alternative, you might consider using the with statement and let Python handle the closing for you. See http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects (end of section) and http://docs.python.org/2/library/contextlib.html#contextlib.closing

Your code might look like this:

import httplib
import json
from contextlib import closing

def getReviewStatus(reviewboardUrl, id):
    try:
        with closing(httplib.HTTPConnection(reviewboardUrl, 80)) as conn:
            headers = {
                'Accept': 'application/json',
                'Content-Type': 'application/json; charset=UTF-8'
            }
            conn.request("GET", "/api/review-requests/%s/" % id, headers=headers)
            return json.loads(conn.getresponse().read())['review_request']['status']
    except:
        return ""

I find it's good to get into the habit of using with to open resources so don't have to worry about forgetting to close the connection.


Efficiency

As someone else mentioned, the inner loop only needs to run up to m-1.
The standard optimization is that if an entire inner loop runs without ever swapping, then the array is now sorted and you can quit early.  Notice how it prints the same thing the last 4 times.

Style

If you've done bullet point 1 above, the only usage of n will be for (int m = n..., so you can just replace that with its definition and get rid of int n = array.length; above.
You don't need to declare 'int k;' at the top, Java is smart enough to make that optimization.  You can just use int k = i + 1;.
In swapNumbers, combine the first two lines into int temp = array[i];

Looking Forward

Right now, it's difficult to reuse bubbleSort because it spews output to the console.  I get that you want to see what it's doing, but once it's working you should take that out.  The sort function should only be responsible for sorting; the user of the function (in this case, the main method) can decide what to do with the results (e.g., print them).

If you want to be able to debug it in the future, then put it behind a debugging flag:

// this goes top-level in the BubbleSort class:
private static final boolean DEBUG = false;
// then, inside bubbleSort:
if (DEBUG)
    printNumbers(array);


Proposed changes:

To shorten that huge switch statement a little bit you could extract the offsets into a few constant arrays, since those are not dependent on the function inputs.

const int offsets_BGGR[4] = { 2, 1, 1, 0 };
const int offsets_RGGB[4] = { 0, 1, 1, 2 };
const int offsets_GBRG[4] = { 1, 2, 0, 1 };
const int offsets_GRBG[4] = { 1, 0, 2, 1 };

Then just grab a pointer to the appropriate array in the switch cases.

But going further, I would also extract the switch statement into a separate helper function. Something like a GetColorSpaceConversionOffsets().

The BayerChannel parameter is only read from, so it should be marked const. This will be a valuable hint to callers of the function, since they can rest assured that the source data will remain unchanged upon function completion (unless there is a bug, of course).

Input parameter validation?

At the moment you are not doing any, which means that if a null pointer is passed as one of the parameters, the code would crash without much information about the error. Consider at the very least asserting to validate the inputs and help catching errors early.

A couple other minor points:

Avoid throwing native types, such as raw strings and integers. The C++ Standard provides a set of throwable classes in the <stdexcept> standard header, that you can use instead. Most commonly you will throw a runtime_error for generic runtime problems, but you can also define a custom exception class to make error reporting more detailed.
Use camelCase with the first letter lowercase for variables and function parameters, reserving PascalCase for types. For instance, in your function the ColorSpace type name confuses itself with the variable instance name:

void static ConvertBayerToRgbImageDemosaic(T* BayerChannel, T* RgbChannel,
             int Width, int Height, ColorSpace ColorSpace) { ...
                                    ^^^^^^^^^^ ^^^^^^^^^^

Updated code:

#include <vector>
#include <algorithm>
#include <stdexcept>

enum class ColorSpace
{
    BGGR, RGGB, GBRG, GRBG
};

// Local data and helpers "hidden" inside an anonymous namespace.
namespace
{

const int offsets_BGGR[4] = { 2, 1, 1, 0 };
const int offsets_RGGB[4] = { 0, 1, 1, 2 };
const int offsets_GBRG[4] = { 1, 2, 0, 1 };
const int offsets_GRBG[4] = { 1, 0, 2, 1 };

void GetColorSpaceConversionOffsets(ColorSpace colorSpace, int width, std::vector<int> colorOffsets[4], const int *& offsets)
{
    // Calculate offsets according to color space
    switch (colorSpace)
    {
    case ColorSpace::BGGR:
        offsets = offsets_BGGR;
        colorOffsets[0].push_back(0);
        colorOffsets[0].push_back(1);
        colorOffsets[0].push_back(width);
        colorOffsets[0].push_back(width + 1);
        colorOffsets[1].push_back(-1);
        colorOffsets[1].push_back(0);
        colorOffsets[2].push_back(0);
        colorOffsets[2].push_back(1);
        colorOffsets[3].push_back(-width - 1);
        colorOffsets[3].push_back(-width);
        colorOffsets[3].push_back(-1);
        colorOffsets[3].push_back(0);
        break;
    case ColorSpace::RGGB:
        offsets = offsets_RGGB;
        colorOffsets[0].push_back(0);
        colorOffsets[0].push_back(1);
        colorOffsets[0].push_back(width);
        colorOffsets[0].push_back(width + 1);
        colorOffsets[1].push_back(-1);
        colorOffsets[1].push_back(0);
        colorOffsets[2].push_back(0);
        colorOffsets[2].push_back(1);
        colorOffsets[3].push_back(-width - 1);
        colorOffsets[3].push_back(-width);
        colorOffsets[3].push_back(-1);
        colorOffsets[3].push_back(0);
        break;
    case ColorSpace::GBRG:
        offsets = offsets_GBRG;
        colorOffsets[0].push_back(0);
        colorOffsets[0].push_back(1);
        colorOffsets[1].push_back(-1);
        colorOffsets[1].push_back(0);
        colorOffsets[1].push_back(width - 1);
        colorOffsets[1].push_back(width);
        colorOffsets[2].push_back(-width);
        colorOffsets[2].push_back(-width + 1);
        colorOffsets[2].push_back(0);
        colorOffsets[2].push_back(1);
        colorOffsets[3].push_back(-1);
        colorOffsets[3].push_back(0);
        break;
    case ColorSpace::GRBG:
        offsets = offsets_GRBG;
        colorOffsets[0].push_back(0);
        colorOffsets[0].push_back(1);
        colorOffsets[1].push_back(-1);
        colorOffsets[1].push_back(0);
        colorOffsets[1].push_back(width - 1);
        colorOffsets[1].push_back(width);
        colorOffsets[2].push_back(-width);
        colorOffsets[2].push_back(-width + 1);
        colorOffsets[2].push_back(0);
        colorOffsets[2].push_back(1);
        colorOffsets[3].push_back(-1);
        colorOffsets[3].push_back(0);
        break;
    default:
        throw std::runtime_error("Unsupported ColorSpace. Only bayer supported.");
    }
}

} // namespace {}

template<typename T>
void ConvertBayerToRgbImageDemosaic(const T* bayerChannel, T* rgbChannel, int width, int height, ColorSpace colorSpace)
{
    // Translates index offset in Bayer image to channel offset in RGB image
    std::vector<int> colorOffsets[4];
    const int * offsets = nullptr;
    GetColorSpaceConversionOffsets(colorSpace, width, colorOffsets, offsets);

    #pragma omp parallel for
    for (auto row = 0; row < height; row++)
    {
        for (auto col = 0, bayerIndex = row * width; col < width; col++, bayerIndex++)
        {
            auto offset = (row % 2) * 2 + (col % 2); // 0...3

            std::for_each(colorOffsets[offset].begin(), colorOffsets[offset].end(),
                [&](int colorOffset)
                {
                    auto rgbIndex = (bayerIndex + colorOffset) * 3 + offsets[offset];
                    rgbChannel[rgbIndex] = bayerChannel[bayerIndex];
                });
        }
    }
}