Creating an array with quarter hour times

var quarterHours = ["00", "15", "30", "45"];
var times = [];
for(var i = 0; i < 24; i++){
  for(var j = 0; j < 4; j++){
    times.push(i + ":" + quarterHours[j]);
  }
}

That's the really quick way without thinking. There might be better ways, but this is what I come up with in 2 minutes.

After testing, you'll find out that it doesn't have a 0 prefix for hours 1 through 9. They show up as "9:45". You could either add a check for that, like so:

var quarterHours = ["00", "15", "30", "45"];
var times = [];
for(var i = 0; i < 24; i++){
  for(var j = 0; j < 4; j++){
    if(i < 10){
      times.push("0" + i + ":" + quarterHours[j]);
    } else {
      times.push(i + ":" + quarterHours[j]);
    }
  }
}

Some more minor cleanup...

var quarterHours = ["00", "15", "30", "45"];
var times = [];
for(var i = 0; i < 24; i++){
  for(var j = 0; j < 4; j++){
    var time = i + ":" + quarterHours[j];
    if(i < 10){
      time = "0" + time;
    }
    times.push(time);
  }
}

Or declare another array with "00", "01", "02"... "23".

Basically what you end up doing is creating every combination of hours and 15 minutes to recreate that big array of yours.


First off: If you want a range that goes from 1 to x, inclusive, write (1..x), not (1...x+1).

Second, if it's the last line executed in a method, it's automatically returned -- so in get_text, you don't need return in the last line, just the actual code.

Also, get_text should return the text to be printed, not what it might be. Move the empty check (fb_text.empty ? i : fb_text) to get_text instead of having it at the puts call. See the code at the end for clarification.

if statements with just one line should be expressions at the end. Again, see the modified code for what I mean.

Methods defined in a class are generally talking about the object they're run on. I'd pull is_number_divisible_by? out of the class and dropping it at the beginning of your code instead, and renaming it to something like divisible_by? instead (since it's shorter and carries the same information).

Aside from that (and an odd extra newline at the beginning of your class definition), it looks good! Here's your code with these suggestions:

def divisible_by?(number, divisor)
  number % divisor == 0
end

class FizzBuzz
  def initialize(fizz = 'Fizz', buzz = 'Buzz')
    @fizz = fizz
    @buzz = buzz
  end

  def get_text(number)
    fizz_buzz_text = ''
    fizz_buzz_text += @fizz if divisible_by? number, 3
    fizz_buzz_text += @buzz if divisible_by? number, 5
    fizz_buzz_text.empty? ? number : fizz_buzz_text
  end

end

fb = FizzBuzz.new
(1..100).each do |i|
  puts fb.get_text i
end

Note: Personally, I wouldn't do this in an OOP way. Ruby is much more oriented towards functional programming, though of course OOP is perfectly valid; besides, functional is a bit simpler. My preferred way to do it would be something like this:

(1..100).each do |num|
  output = ''
  output += 'Fizz' if num % 3 == 0
  output += 'Buzz' if num % 5 == 0
  puts output.empty? ? num : output
end


Calculating "element-wise" the angles between two lists of vectors

Here's a way of packing the calculation into on call to einsum.

def findAnglesBetweenTwoVectors1(v1s, v2s):
    dot = np.einsum('ijk,ijk->ij',[v1s,v1s,v2s],[v2s,v1s,v2s])
    return np.arccos(dot[0,:]/(np.sqrt(dot[1,:])*np.sqrt(dot[2,:])))

for random vectors of length 10, the speed for this function and yours is basically the same.  But with 10000, (corrected times)

In [62]: timeit findAnglesBetweenTwoVectors0(v1s,v2s)
100 loops, best of 3: 2.26 ms per loop

In [63]: timeit findAnglesBetweenTwoVectors1(v1s,v2s)
100 loops, best of 3: 4.24 ms per loop

Yours is clearly faster.

We could try to figure out why the more complex einsum is slower (assuming the issue is there rather than the indexing in the last line).  But this result is consistent with other einsum testing that I've seen and done.  einsum on simple 2D cases is as fast as np.dot, and in some cases faster.  But in more complex cases (3 or more indexes) it is slower than the equivalent constructed from multiple calls to np.dot or einsum.

I tried tried factoring out the array construction, and got a speed improvement.

In [12]: V1=np.array(v1s)  # shape (3,10000,3)
In [13]: V2=np.array(v2s)
In [22]: timeit findAnglesBetweenTwoVectors2(V1,V2)
100 loops, best of 3: 2.63 ms per loop

I've corrected the times, using v1s.shape==(10000,3)


window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.onclick = resetTimer;
window.onscroll = resetTimer;
window.onkeypress = resetTimer;

First, I'd suggest not binding handlers this way. The problem is that some other code might override the property and completely replace the handler. Even if you take steps not to override an existing one, there's no guarantee that yours won't get overridden. Use addEventListener instead.

Also, document and window have different events. document related to the DOM elements (i.e.: click, mouseover) and window related to window events (i.e. resize, scroll etc.). See this answer for details.

var IdleListeners = new function(){

You're not benefiting from the perks of constructor-created objects. What your code essentially does is create an instance of an anonymous constructor which has no methods nor properties. You merely created a closure that wraps the initialization code and your timer reset.

var IdleListener = function(idleFunction, timeout){

For this one, you almost got it, except for the this.reset. The goal of prototypal inheritance is to share methods among instances. Defining reset in this instead of the prototype means that each instance gets its own copy of reset, not shared.

this.interval = setInterval(this.idleFunciton, this.timeout);

I believe you want setTimeout. You wouldn't want the handlers to fire periodically, especially when they're bound to an alert. It would be endless.

  But what I have heard about javascript is you have to completely forget how classical inheritance works.

Not really. You just need to know how classical inheritance is different from prototypal inheritance. Also, you shouldn't force JS to do what it doesn't do natively. While it can emulate, it's not pretty.

Keep the code simple. As much as possible, work with just functions, objects (maps) and arrays (lists). Don't jump into OOP or inheritance directly. For instance, I can simplify your code with a singleton and a list of handlers.

;(function(ns){

  // An array for our "listeners"
  var listeners = [];

  // An add function which accepts a delay and handler
  ns.add = function add(handler, timeout){

    // All we're doing here is create an entry in the array containing our
    // settings, and preparing the timer as null. Reset will build it for us.
    listeners.push({
      handler: handler,
      timeout: timeout,
      timer: null
    });
  }

  // Now when you call reset (as a result of an action), it loops through all
  // the handler definitions, clears any existing timers, and rebuilds them.
  ns.reset= function reset(){
    listeners.forEach(function(listener){
      clearTimeout(listener.timer);
      listener.timer = setTimeout(listener.handler, listener.timeout);
    });
  }

  // Add handlers
  document.addEventListener('click', reset);

// Use an existing global or create one
}(this.IdleListener = this.IdleListener || {}));

// Usage
IdleListener.add(function(){
  console.log('idle!');
}, 1000);


Recursive function and memorization to find minimum operations to transform n to 1

The problems you've encountered usually signal that the approach is not the best.

Consider the very first step in your algorithm: you are definite that if the number is even, the best action is \$n\rightarrow \frac{n}{2}\$ (why?).

Try to apply the same logic one step further. Let \$n\$ be odd. Either \$\frac{n+1}{2}\$ or \$\frac{n-1}{2}\$ is also odd (why?). The best action is to pick that which is even (why?).

As soon as you prove all the why statements, a straight-forward non-recursive algorithm is easy to obtain.


Could random unique selection using while cause an infinite loop?

Your first attempt is indeed in danger of getting into an infinite loop if a certain value never gets returned from rand (but any half decent PRNG will return all of them eventually).

Your second attempt is very close to the (most optimal) Fisher-Yates shuffle, with the difference that you use a separate array to store the shuffled result while shrinking the original pool.


Stack data structure implementation in Java

I'd like to give some thoughts which spring to my mind when I read your given code. Now, you have an implementation specific for primitive ints. A more advanced step would of course be to implement a generic Stack like the one in the JDK, just mentioning it.

First up, I like that you use clear variable names, and that you reuse methods like isEmtpy \ isFull. Kudos for that! As an aside, you do not need the maxSize variable, as it is the same as stack.length.

It is a fixed size stack, so it does mean you have to know beforehand how much elements it would take up, in order to not waste space (or run out of it). Perhaps for a follow up exercise you could try and make it dynamically resizable?

Now, for the push method. I would not let it silently succeed if the stack is already full. Seeing as it is a fixed size stack, I would probably opt to throw an Exception, because to me it looks like a programming error. A possible second idea could be to return a boolean, signaling succes or failure (though I don't think it is the better solution).

Same with peek. It now silently succeeds and returns 0, which is very well a valid value which could reside in the stack (EmptyStackException exists by the way!). The boolean solution would not work here of course. Also, I personally do not think the extra new line is an improvement, on the contrary.

Finally, to me pop means taking off the top element of the stack. So why not return it?


Program for converting a boring text into a stylish written text

Finally. A program to help me speak the same language as the cool kids. Thanks for that.

Use an array when it's good enough

The second part of convertToTrendyText needlessly uses a StringBuilder instance.
The power of StringBuilder is to efficiently build strings whose size is not known in advance.
In this method we do know in advance,
so there's no need for a StringBuilder,
an array from string.toCharArray() would be more than enough.
After replacing characters in the char[],
you could return it in a new String(...).

Destructive uppercasing

The first part of convertToTrendyText inserts some random smileys.
The second part of the method randomly uppercases some letters.
That risks ruining the following smileys: o.O, x3, xD.
I'm wondering if that's intended or not.
With this potential unintended side effect,
the text might become completely unreadable.

To avoid such destruction,
you could swap the first and second parts:
do the uppercasing first,
and insert smileys after.
That way the smileys will be unaffected by design.

One Random is enough

There's no need to create multiple instances of Random in a program.
It would be better to use just one.
That could be a good step in the direction of making the program testable,
because you will be able to set a seed to get reproducible output.

Getting a random value out of n values

The switch statement in generateRandomSmiley is a bit troublesome.
If you add a new smiley, you have to remember to increment the number in the random.nextInt(...) call, and add a correctly numbered case statement. Such a hassle.

If you use an array of smileys,
then the process of adding or removing values becomes a lot simpler,
more compact,
without having to worry about indexes.

private static final String[] SMILEYS = {
    ":)", ":D", ":*", "<3", "o.O", "x3", ";D", "xD", ":o", ";D"
};

public static String generateRandomSmiley() {
    return SMILEYS[random.nextInt(SMILEYS.length)];
}

Btw, did you notice that there is no case 6 line in your original switch statement?
That leads to getting the same value for it as the default case.
Not sure if that was intentional.
To preserve the behavior of the posted code,
I duplicated the default value ;D at index 6 (in addition to its natural index 9).

A word on performance

Every call like string = string.replace("...", "..."); has to iterate over all the content of the string.
That seems a bit wasteful.
In a toy program like this,
it doesn't really matter,
but it's worth keeping in mind.


How can I speed up this solution to the "Rock-Paper-Scissors Tournament"

The choice of data structure is fundamentally sound (but more on that later).

The first thing that jumped out to me in your code is actually not directly related to performance: you could drastically improve readability by declaring variables where you use them rather than at the beginning, and by assigning better names. Don’t be afraid that declaring variables inside a loop will lead to performance degradation! First off, in most cases it doesn’t. And secondly, where it does the difference in performance is usually negligible, and will not contribute sufficiently to be noticed. If, and only if, that’s not the case does it make sense to change this.

Some more points regarding readability:

Since you’re already using uniform initialisation, use {…} instead of (…) in your initialisation of result. Writing ({…}) is pretty unusual and consequently tripped me up.
Since C++11 there’s no need to put a space between template argument list terminators (> > vs. >>).
Don’t use integer literals in place of boolean values: don’t write while (1), write while (true).
Your (C-style) casts to float are unnecessary. Remove them.
Make more variables const — in particular result! You don’t want to accidentally modify that. You will also need to change your lookup to using find then, unfortunately.

Now on to performance improvements. There are effectively two things to improve.

First off, two things about unordered_map:

Although the choice of this structure is algorithmically correct, C++’s standard library specification of it is poor due to a fault in the standard wording, which forbids efficient implementations. The structure is therefore a cache killer.
In your case a general string hash is overkill: you only need to check the first letter of each word to determine which move was played.

You could exploit the second point by providing a custom Hash template argument to std::unordered_map which only returns the first character. But given the first point, I would suggest ditching std::unordered_map altogether and just using a 256×256 array as a lookup table (or, if you want to optimise space, subtract some common value from the first character or find a perfect hash function for the letters “r”, “p” & “s”).1

And now something more mundane, since the execution time of your program is at any rate completely dominated by IO: std::cin and std::cout are by default synchronised with C’s buffered standard IO, which makes them excruciatingly slow. To fix this, put std::ios_base::sync_with_stdio(false) a the beginning of your main function. Similarly, untie standard output from standard input via std::cin.tie(nullptr). Secondly, replace std::endl with "\n". std::endl flushes the stream each time, which is slow. It’s also unnecessary to set the stream format manipulators in every loop (although I don’t expect this to change the performance).

— It’s worth noting that none of that had a measurable impact on the performance of the code on my machine. In fact, formatted input via std::cin totally dominates the runtime. This is surprising and disappointing (because there’s no reason for it: it hints at a broken standard library implementation). Using scanf is significantly faster, which should not happen. Of course using scanf also requires changing the type of m1 and m2 (you can use a static buffer of size sizeof "scissors"). It’s worth emphasising that it’s really IO that’s slow, and not the std::strings: simply replacing the std::strings with static buffers has almost no perceptible impact on runtime (likely due to SSO). It’s really std::cin vs scanf.

1 We’re in luck, and the character codes of “r”, “p” and “s” in common encodings differ in the lower two bits, so that we only need a 4×4 lookup and minimal recoding:

static int const result[4][4] = {
//    p      r   s
    { 0, 0,  1, -1},     // paper
    { 0, 0,  0,  0},
    {-1, 0,  0,  1},     // rock
    { 1, 0, -1,  0}      // scissors
};

…

int const winner = result[move1[0] & 3][move2[0] & 3];

But of course given what I said about the IO bottleneck that’s completely unnecessary obfuscation.


Here is how you can improve your code:

Define a class instead of using an array for unrelated numbers (0 to 100 vs. 0.1 or 0.2)
Use a std::vector instead of a fixed size array
Prefer double over float, since it has higher precision
Prefer integer arithmetic over floating point arithmetic, since it won't lead to strange results that easily
Group your global functions into a class, to express that they belong together
Add error checking for all calls to std::cin >> var

By the way, you don't look like a beginner since you

don't import the complete std namespace
use \n instead of std::endl

This is already quite good.


Bank account number validation in IBAN format

I'm pretty sure this will fail for some IBANs. You convert the country code to digits, but I don't see you doing the same for any other letters in the IBAN - and there might well be others. The example Wikipedia gives is GB82WEST12345698765432. The "WEST" should be converted to numbers as well (same procedure as the country code; 'A' = 10, B = 11, etc.).
Not sure why getLengthMap is a function - it's basically a constant value, and might as well be declared as a simple variable.
The regexes have some redundancy.This one, /^[a-zA-Z0-9]+$/, checks for lowercase letters, though the line before has already called toUpperCase(). And the next regex accepts trailing whitespace and dashes, though those have been removed.
And while you're using regexes, you might as well use that to pick the string apart, rather than substring plus magic numbers.
Your modulo function seems fine, though there's little reason to have it accept a divisor argument. Since it's an internal helper function specifically for IBAN, it'll always be mod 97. So in this case, I might actually prefer that that was hard-coded (and the function was named mod97 or something equally explanatory).

In all, I think you can do a lot more with fewer regexes, which would help streamline the code.

To sanitize the input:

var iban = value.toUpperCase().replace(/[^A-Z0-9]/g, '');

To "parse" the IBAN:

var match = iban.match(/^([A-Z]{2})(\d{2})(.+)$/);

if match is null the code's automatically invalid. Otherwise, match[1] will be the 2-letter country code, match[2] will be the check digits, and match[3] will be the rest of the IBAN. Provided there's a match it should then rearranged as match[3] + match[1] + match[2]

Alternatively, you can check and rearrange in one go:

var code = iban.replace(/^([A-Z]{2})(\d{2})(.+)$/, "$3$1$2");

if code === iban, nothing's been rearranged, which means there wasn't a match, and the code's invalid. You'd still have to extract the country code, though, so not much is won by doing this.

Finally, to convert letters to numbers:

 var digits = iban.replace(/[A-Z]/g, function (letter) {
   return String(letter.charCodeAt(0) - 55);
 });

Here's my take

var validIBAN = (function () { // use an IIFE
  // A "constant" lookup table of IBAN lengths per country
  // (the funky formatting is just to make it fit better in the answer here on CR)
  var CODE_LENGTHS = {
    AD: 24, AE: 23, AT: 20, AZ: 28, BA: 20, BE: 16, BG: 22, BH: 22, BR: 29,
    CH: 21, CR: 21, CY: 28, CZ: 24, DE: 22, DK: 18, DO: 28, EE: 20, ES: 24,
    FI: 18, FO: 18, FR: 27, GB: 22, GI: 23, GL: 18, GR: 27, GT: 28, HR: 21,
    HU: 28, IE: 22, IL: 23, IS: 26, IT: 27, JO: 30, KW: 30, KZ: 20, LB: 28,
    LI: 21, LT: 20, LU: 20, LV: 21, MC: 27, MD: 24, ME: 22, MK: 19, MR: 27,
    MT: 31, MU: 30, NL: 18, NO: 15, PK: 24, PL: 28, PS: 29, PT: 25, QA: 29,
    RO: 24, RS: 22, SA: 24, SE: 24, SI: 19, SK: 24, SM: 27, TN: 24, TR: 26
  };

  // piece-wise mod97 using 9 digit "chunks", as per Wikipedia's example:
  // http://en.wikipedia.org/wiki/International_Bank_Account_Number#Modulo_operation_on_IBAN
  function mod97(string) {
    var checksum = string.slice(0, 2),
        fragment;

    for(var offset = 2 ; offset < string.length ; offset += 7) {
      fragment = String(checksum) + string.substring(offset, offset + 7);
      checksum = parseInt(fragment, 10) % 97;
    }

    return checksum;
  }

  // return a function that does the actual work
  return function (input) {
    var iban = String(input).toUpperCase().replace(/[^A-Z0-9]/g, ''), // keep only alphanumeric characters
        code = iban.match(/^([A-Z]{2})(\d{2})([A-Z\d]+)$/),           // match and capture (1) the country code, (2) the check digits, and (3) the rest
        digits;

    // check syntax and length
    if(!code || iban.length !== CODE_LENGTHS[code[1]]) {
      return false;
    }

    // rearrange country code and check digits, and convert chars to ints
    digits = (code[3] + code[1] + code[2]).replace(/[A-Z]/g, function (letter) {
      return letter.charCodeAt(0) - 55;
    });

    // final check
    return mod97(digits) === 1;
  };
}());


The error should be caught where it occurs, namely in the controller. If possible try to implement something like this

TimelineEventCollection personTimelineEvents; // Change to the appropriate collection type.
if (Controllers.FollowUp.TryGetAll(personID, out personTimelineEvents)) {
    timelineEvents.AddRange(personTimelineEvents);
}

The advantage of this approach is that the error does not get swallowed up silently by some try-catch-statement. You get a Boolean return value from TryGetAll telling you if all went right. At the same time the basic error handling happens in a low level method and not in your list filling routine.

If you cannot alter the Controllers.FollowUp class, you can still write an extension method giving you the same functionality.


Python editing lists and converting to a dictionary

I have a few complaints:

You're using a for loop to iterate over the indexes of a list instead of directly iterating over the list, but you're not actually using the indexes for anything. I'd suggest

for element in errors:

instead, then using element instead of errors[elements]
The line errors[elements][1] doesn't actually appear to do anything, except throw an IndexError if the list is length 1 or shorter. If this is the intended behaviour, it could be made clearer using a check such as if len(errors[elements]) < 2: ..., and perhaps avoid using exceptions entirely.
An except which catches every type of error there is is rarely a good idea - it's unclear and risks swallowing exceptions you actually want to be warned about in the future. If I understand your code correctly, except IndexError would do the same thing, but be slightly clearer.

All in all, however, it appears you're using exceptions for a case where they aren't needed, which tends to make code harder to grok overall. I'd probably rewrite the loop to something along the lines of

for element in errors:
    if len(element) >= 2:
        error.append(element[1])

though a list comprehension such as error = [element[1] for element in errors if len(element) >= 2] could work too.


Search object literal and return first key/value pair that matches regex

To be fair, the entire thing in Ruby would be a few more method calls:

{:a => 1, :b => 2}.detect { |i| i != :b }.each_slice(2).to_h

Can we do this in a similar number of lines in JavaScript?

First, we can shorten the 8 line original down to 5 lines if we use ES2015 syntax:

function test(data) {
  for(let key of data) {
    if(/_is$/.test(key)) return {[key]: data[key]};
  }
}

Adding in ES2015 methods we can use reduce and an arrow function to get rid of the return at the cost of making this always loop over all the keys in the object (now down to 3 lines):

const test = data => Object.keys(data).reduce((obj, key) =>
  obj || /_is$/.test(key) ? {[key]: data[key]} : undefined, undefined
);

If we're willing to use ES2017, we can use Object.entries and a helper function to get the line count down to 2 at the expense of a little legibility:

const toObj = ([key, value] = []) => key ? {[key]: value} : undefined;
const test = data => toObj(Object.entries(data).find(([key, value]) => /_is$/.test(key)));


Prime Sieve in Rust (Sieve of Eratosthenes)

Learn to love rustfmt.

Spaces go around operators

- count+=1;
+ count += 1;

- i=2*p;
+ i = 2 * p;

- while i<n {
+ while i < n {

Spaces go between function arguments

- let np = prime_sieve(n,ofile);
+ let np = prime_sieve(n, ofile);

Spaces go after the ; in array and Vec declarations.

- vec![true;n];
+ vec![true; n];

Do not take a &String, take a &str instead.
There's no need to specify the type of prime_mask at all, inference can handle it.
Instead of comments, make your code tell the story. Introduce constants with names and rename existing variables.
"N" usually infers a count of something. For prime numbers, I'd expect N to mean "return me the first N primes". In this case, it's "check the first N numbers to see if they are prime". A better name would help communicate that.
Do not declare variables with a wider scope than you need. i can be declared where it is initialized.
Loops where you add one each iteration can be replaced with range-based for loops. Note that this removes mutability from your code.
Use write! instead of allocating a String and writing that.
Use writeln! instead of specifying the newline yourself,
There's no need to specify the inner type of the args vector. Use _ to let the compiler infer it.
Instead of hard-coding the concept of "files" into your prime_sieve function, accept any type that implements Write. Makes it easier to test.

use std::env;
use std::fs::File;
use std::io::{Write, BufWriter};

fn prime_sieve<W>(max_number_to_check: usize, mut output: W) -> u32
    where W: Write
{
    let mut prime_mask = vec![true; max_number_to_check];
    prime_mask[0] = false;
    prime_mask[1] = false;

    let mut total_primes_found = 0;

    const FIRST_PRIME_NUMBER: usize = 2;
    for p in FIRST_PRIME_NUMBER..max_number_to_check {
        if prime_mask[p] {
            writeln!(output, "{}", p).expect("Unable to write to file");
            total_primes_found += 1;
            let mut i = 2 * p;
            while i < max_number_to_check {
                prime_mask[i] = false;
                i += p;
            }
        }
    }

    total_primes_found
}

fn main() {
    let args: Vec<_> = env::args().collect();
    let n: usize = args[1].trim().parse().expect("Wanted a number");

    let ofile = &args[2];
    let f = File::create(ofile).expect("Unable to create file");
    let f = BufWriter::new(f);

    let np = prime_sieve(n, f);

    println!("Found {} primes less than {}. Wrote to {}", np, n, ofile);
}

For your usage, a Vec<bool> wastes space. Each bool is one byte, of which you are using a single bit. Instead, there are efficient bit vector crates which pack the data much tighter.

  isn't there an advantage to explicitly putting in the types as it adds self documentation to the program? I come from Haskell which also has inferred typing but explicit type signatures are encouraged.

Explicit type signatures are required in Rust; you cannot infer the argument or return types of a function. Rust learned from Haskell here and avoided the problem of spooky action at a distance that can occur if you don't provide signatures.

Inference inside a function is quite idiomatic. There are times where you need to be explicit (such as the collection type to collect into), but beyond that, I shy away from listing any types.

I've a feeling this is something that changes as you grow accustomed to Rust. Beginners are more likely to sprinkle types about, then you learn to trust and rely on inference.

If there's ambiguity, it may be something that improving the variable name can help. As an example, to me a "mask" is a integral number that is applied using bitwise operations to another integer. I wouldn't expect for it to be a Vec.

I also use highly dynamic languages like Ruby where there are no static types, so the lack of types inside a function is not outrageous.

  For Vec<bool> types, are they always a waste of space to use? Is there a case where they should be used instead of bit-vec types?

Every data structure has tradeoffs. The primary one I'm aware of is that a bit vector does not allow you to get a reference to the specific boolean value because a boolean doesn't really exist.


Complex scientific formula for nuclear magnetic resonance

I would consider the practice ok in this case.

Your variable try appear to be roughly the "ASCII" equivalent of the ones used in the equation.
You cite the paper where you got the equations from. (This is probably the most important thing to do) This allows the programmer to understand the context.

Remember readability is subjective, look at something like APL for example and you will see that APL strives for code most closely aligned to math. The creator of this language purposely designed the language to be effective at representing math operations (in particular, matrix manipulation) and it takes a vastly different approach from Python.

One interesting thought experimenet: If we grew up and learned that the word "print" was simply "p", "print" would likely be considered not readable and we would replace each case with "p". However, in our world, we consider the opposite to be true in most cases.

For me it is much easier to read dx instead of something like change_in_x because I have learned to appreciate the former.

The only thing I would consider changing is getting rid of pi_squared and just writting it out explicitly (unless there is some worthwhile performance cost in doing so).


JavaScript metaballs optimization

I read that as "JavaScript meatballs optimization" :D

First optimization I would do is... code organization. Slow-looking code will be slow code, since it takes you an extraordinary amount of time working with it. So keep your code tidy. Use proper indentation, name variables properly, organize code in a coherent fashion.

Nested loops become a problem, fast. Avoid nested loops as much as possible. In the case of looping through canvas pixels, instead of using a nested loop to traverse horizontally and vertically, you can simply use one loop and skip by fours. That will give you the same pixel-traversing effect.

But isn't it the same amount of iterations? Yes, but here's the thing. Loops are a dead end in terms of optimization. If you get your x and y that way, that's it. However, if you do the 1d loop and do math to get your x and y, you still have a chance at optimization since math can be optimized (bitwise operations) and values can be cached easily.

Another perf killer is property access. It's negligible alone, but if you're operating at 3M pixels per frame, it becomes very visible. Cache values as much as possible, and avoid property accesses.

One optimization you could do is heuristics. I you know a pixel is far enough from any ball, you can just color it black without calculation. Same goes for pixels within a ball. If it's within a ball, it will be white regardless of overlapping balls. Also, if a pixel is already white, you can just skip calculation of the other balls since there's no way it could darken.

Another trick you could do is just use a smaller canvas and upscale it with CSS scale transform. To the script, the number of pixels on the canvas is lesser which means lesser iterations. But from the viewing perspective, the animation is about the same as the full-scale version.

Here's my take on it. Slightly faster due to skipping and upscaling.

const c = document.getElementById("canvas");
const width = c.width = 640;
const height = c.height = 360;
const ctx = c.getContext("2d");
const imageData = ctx.createImageData(width, height);
const data = imageData.data;
const dataLength = data.length;
const num = 20;
const balls = Array(num).fill().map(_ => new Ball());

function random(min, max) {
  var num = Math.floor(Math.random() * (max - min + 1) + min);
  return num;
}

function Ball() {
  this.posX = random(0, width);
  this.posY = random(0, height);
  this.dx = random(-4, 4);
  this.dy = random(-4, 4);
  this.radius = random(2, 25);
}

Ball.prototype.move = function() {
  if (this.posX > width || this.posX < 0) this.dx = -(this.dx);
  if (this.posY > height || this.posY < 0) this.dy = -(this.dy);
  this.posX += this.dx;
  this.posY += this.dy;
}

function updateBalls() {
  for (var i = balls.length; i--;) balls[i].move();
}

function renderBalls() {

  for (var sp = 0; sp < dataLength; sp += 4) {
    const index = sp / 4;
    const y = index / width | 0;
    const x = index % width | 0;
    var color = 0;

    for (var i = balls.length; i--;) {
      const ball = balls[i];
      const radius = ball.radius;
      const posX = ball.posX;
      const posY = ball.posY;

      color += radius * 2500 / (Math.pow((x - posX), 2) + Math.pow((y - posY), 2));

      if(color >= 255) break;
    }

    data[sp + 0] = color * 1.05;
    data[sp + 1] = color;
    data[sp + 2] = color * 1.4;
    data[sp + 3] = 255;
  }

  ctx.putImageData(imageData, 0, 0);
}

;(function loop() {
  requestAnimationFrame(loop);
  updateBalls();
  renderBalls();
})();
body {
  padding: 0px;
  margin: 0px;
}

canvas{
  transform: scale(4);
}
<canvas id="canvas"></canvas>


Who needs clean configuration? Swapping server.xml

Method

I'd suggest, instead of rm-ing and cp-ing, keeping each configuration set as named and symlinking to them as needed.

This gives you a couple of benefits:

You can tell which the current one is without opening the file, just using ls -l:

lrwxrwxrwx 1 user group 4 Jul 29 07:12 server.xml -> config-for-blah.xml

Changes are (sort-of) atomic: rm and cp take time, while over-writing a symlink with a symlink is as close to instant as you can reasonably make it.
You can move the actual files anywhere later and just update the symlinks: version-control it in a repo directory, put configuration sets into separate directories, whatever.

Replacing the rm and cp in your current script, that'd be:

ln -sf "$TOMCAT_HOME/conf/server_$1.xml" "$TOMCAT_HOME/conf/server.xml"

(You need -f, or else ln will complain that the link you're trying to create already exists.)

You should also detect whether the main commands have completed successfully, probably using something like:

if [ $? -ne 0 ];
    then
    echo "Oops." >&2
    exit 1
fi

Scripting

Quote your filenames. This helps avoid accidents where variables are mis-set.
Check your test types. In [ $# != 1 ], $# is being referenced as a number, but != is for strings. Use -ne for numbers. (This is just a good habit to get into.)
You don't need the semicolons after the fi.
Error messages should usually go to stderr: echo "Error" >&2
When detecting an error and exiting, exit with an status other than 0: this lets you easily detect problems when using the script. (c.f. the check in the method section above.)
Maybe do something to avoid command aliases. Sometimes aliases for commands like rm, cp, and ln can get into scripts by accident and make scripts break. You can avoid this by making sure your use of them doesn't trigger alias expansion for the commands, either by quoting, escaping, or using the full path.


Without really knowing a great deal about how your code is structured and basing it purely on your ajax function you could so somethhing like this;

function loadView(url, beforeSend, callback) {
    $.ajax({
        type: 'GET',
        url: url,
        cache: false,
        beforeSend: function(){
            beforeSend();
        },
        success: function(response){
            callback(response);
        }
    });
}

You could then use it like this

var showPreLoaderModal = function() {
    preloader.modal('show');
}

loadView("view/settings.php", showPreLoaderModal, function(response){
    $('#display-view').html(response)
});

But this is dirty the modern approach would involve promises!


typedef enum
{
    EQUAL = 0,
    LHS_NEWER,
    RHS_NEWER
} ECOMPARISON;

A common convention for three-way comparisons is that of strcmp() - return any negative value if the first argument is less than the second, zero if equal, and positive if greater.

If we take that approach, and if we can ensure that the version values are small enough to avoid integer overflow, we can simplify the comparison to just:

int CompareVersions(VERSIONCODE a, VERSIONCODE b)
{
    int diff = a.nMajor - b.nMajor;
    if (diff) return diff;
    diff = a.nMinor - b.nMinor;
    if (diff) return diff;
    return a.nRev - b.nRev;
}

If we can't ensure overflow won't happen, or if we absolutely must return fixed values, we'll need to convert those subtractions into calls to a custom comparison function - perhaps like this:

int compare_int(int a, int b)
{
    /* standard idiom to return -1, 0 or +1 */
    return (a > b) - (b > a);
}

The naming can be improved.  Most C conventions use ALL_UPPERCASE only for macros, to call attention to their difference from C code.  And most authorities discourage prefixes like the n and v used at the start of variable and member names - I encourage you to research "Hungarian notation" and understand the arguments.


Your code seems fairly robust, but it is inefficient. Here are a few ways you could speed it up.

Reuse request objects. There is a good bit of overhead creating these, so you definitely want to be reusing these if you are making more than a few requests per page. But be careful - some older browsers have strange quirks about reused request objects.
Don't make a new function for every onreadystatechange. The function is executed with xmlhttp as the context, so, within that function, this === xmlhttp.
Whenever possible, cache. You can cache whether the browser supports XMLHTTPRequest or ActiveX so you don't check every time the function is called.
synchronous requests are usually a bad idea. Are you sure you should be using them? If not, don't write code that is more general than it needs to be. It will just make the function less efficient.

Also, you're missing a semicolon.

As an example, here's a loader function I wrote a while ago. The feature set is a little different than yours - it doesn't support synchronous requests, but it does support error handlers, data encoding, and timeouts - and behind the scenes it implements all the optimizations above. Like your code, it results in a single function; the simplest use case would be load('log.php');.

/***
* load.js
*   Simplifies use of ajax.
* parameters
*   url     : String : address of requested content
*   options : Object : (optional) additional parameters. All keys are optional.
*     onload  : Function : passed request.responseText on success
*     onfail  : Function : passed status on status!=200 or 'timeout' on timeout
*     post    : Object   : POST key-value pairs. GET is used when post==false
*     timeout : Number   : seconds to wait before aborting request
***/

var load=(function() {
    var pool=[],
        getReq=window.XMLHttpRequest?
            function() {return new XMLHttpRequest();}:
            function() {return new ActiveXObject('Microsoft.XMLHTTP');};
    function statechange() {
        if(this.readyState==4) {
            clearTimeout(this.t);
            this.onreadystatechange=null;
            pool[pool.length]=this;
            var fn=this.o[this.status==200?'onload':'onfail'];
            delete this.o;
            fn&&fn(this.status==200?this.responseText:this.status);
        }
    }
    return function(url,options) {
        var req,t,data='';
        req=pool.length?pool.pop():getReq();
        req.o=options=options||{};
        if(options.post) {
            for(t in options.post)
                data+='&'+encodeURIComponent(t)+'='+encodeURIComponent(options.post[t]);
            data=data.substring(1);
            req.open('POST',url,true);
            req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        } else {
            req.open('GET',url,true);
        }
        req.onreadystatechange=statechange;
        req.send(data||undefined);
        if(options.timeout) {
            req.t=setTimeout(function() {
                req.onreadystatechange=null;
                req.abort();
                pool[pool.length]=req;
                if(req.o.onfail)
                    req.o.onfail('timeout');
            },options.timeout*1000);
        }
    };
})();


Securely deleting files, while attempting to protect the user against obviously dangerous inputs

Some notes:

def self.run cmd: Omiting parentheses on signatures is less and less idiomatic as time goes by, people have realized they are harder to read. I'd put them.
Open3.capture3 cmd: It's also less idiomatic than it was years ago to omit parentheses on calls (except for very specific DSL code).
stdout,stderr,status: Always a space after a comma.
def self.validate_path path, required_regex=nil. Positional optional arguments tend to get messy when you need to add new ones. I'd use always an options = {} hash. Ruby 2.0 has keyword arguments so this problem is fortunately gone.
raise if required_regex && !required_regex.is_a?(Regexp). I wouldn't check the type of the variable, it's the caller's responsability to get it right.
File.expand_path(path).tap. This kind of tap usages are IMO cryptic and unnecessary.
Lots of raise ... if condition: Inline conditionals save some lines at the cost of making the branching logic harder to follow. I prefer writing full-fledged indentend conditionals (indentation is a powerful conveyor of information).
Open3.capture3 cmd. Running command from strings is dangerous (files with spaces anyone?), you should use some mechanism to escape them.
find #{path} -type f. It's ok to call external commands when the the language is unable to do the task, but here you can easily perform a recursive find with, well, module find.

I'd write something like this:

require 'find'
require 'open3'
require 'fileutils'
require 'shellwords'

class SafeRemover
  def self.run(command_array)
    command_string = Shellwords.join(command_array)
    stdout, stderr, status = Open3.capture3(command_string)
    if !status || status == 0
      stdout
    else
      fail("Failed executing #{cmd}: stdout: #{stdout}, stderr: #{stderr}, status #{status}")
    end
  end

  def self.validate_path(path, options = {})
    required_regexp = options[:required_regexp]
    path2 = File.expand_path(path)
    if !Dir.exist?(path2)
      fail("Directory does not exist: #{path2}")
    elsif path2 == "/"
      fail("You cannot delete /")
    elsif required_regexp && !path2.match(required_regexp)
      fail("Path and required_regexp do not match")
    end
  end

  def self.dir!(root_directory, options = {})
    validate_path(root_directory, :required_regexp => options[:path_must_match])
    paths = Find.find(root_directory).select { |p| FileTest.file?(p) }
    output = paths.each_slice(100).map { |paths| run(["shred", *paths]) }.join
    FileUtils.rm_rf(root_directory)
    output
  end
end


Finding indices of numbers that sum to a target

Not quite right

First off, you're checking every cross pair of indices against each other. But that means that findTwoSum({1, 3, 4}, 6) will succeed, even though there is no pair of elements that sum to 6 - because you count the 3 twice. You need: "any two distinct elements".

Iterating over vectors

list is a confusing name for a vector. increment is a poor variable name for this - since it's not incrementing anything, it's just another index, so you really should use i and j instead. Also you don't need at() - that member function does range checking. But your indices will all definitely be in range, so you could simply write:

for (size_t i = 0; i < v.size(); ++i) {
    for (size_t j = i+1; j < v.size(); ++j) { // correcting initial bug
        if (v[i] + v[j] == target) {
            return std::make_pair(i, j);
        }
    }
}
return std::make_pair(-1, -1);

Failure case

Rather than using sentinel values, I prefer to use something like Boost.Optional to indicate failure, so that:

boost::optional<std::pair<int, int>> findTwoSum(const std::vector<int>&, int target);

Classes

Why is findTwoSum a static member function? Just make it a free function. There's no reason for a class. You could instead make TwoSum a namespace but I don't see the point of that either.

The Algorithm

You are checking every pair of indices - that's \$O(n^2)\$. We can do way better. Consider that once we have our first index - there is one unique element that we need to find to see if we have a success case: target - v[i].

We could simply throw all of our indices into a map:

std::unordered_map<int, size_t> indices;
for (size_t i = 0; i < v.size(); ++i) {
    indices.insert(std::make_pair(v[i], i));
}

And then simply search if target - v[i] is in indices for each such i:

for (size_t i = 0; i < v.size(); ++i) {
    auto j = indices.find(target - v[i]);
    if (j != indices.end()) {
        return std::make_pair(i, j->second);
    }
}

This will be \$O(n)\$ to create the hashtable, and then another \$O(n)\$ to do all the searching... for a grand total of \$O(n)\$.


Running 2 sets of tasks at the same time

When I have to manage multiple threads, I make sure all processing is complete, typically by using WaitAll.

List<Task> tasks = new List<Task>();
tasks.Add(Task.Run(() => { TriggerAccess(); }));
tasks.Add(Task.Run(() => { TriggerSQL(); }));
Task.WaitAll(tasks.ToArray());

This also allows me to use methods in a non-threaded capacity for testing and to easily add additional threads when the need arises. I can then also return actual data from a method, if I need to, instead of just a thread.

The difference between running the method in a thread and having the method be an async thread is that an async method waits until the first await statement to return to the main thread for processing whereas threading the method immediately continues to the next statement in the main method.

http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx and http://msdn.microsoft.com/en-us/library/hh156513.aspx are very helpful for me.


Validate if the user is associated with the organization then it must have any valid timezone

In case if you wanna improve only the validate_time_zone method:

Performance wise I don't see anything sinister in your implementation.

I assume the states table has a direct time_zone field. If so, then we can use the pluck method to avoid instantiation ActiveRecord objects.

Array.uniq returns a new array by removing duplicate values. The idea is nobel but it means it will use more memory and will loop over the time zones array which will happen anyway in case of include?

On the other hand nowadays in software development the real cost is more in maintenance rather than in CPU cycles.

With this in mind, how about the following refactor?

class User
  validates_presence_of :time_zone

  validate :validate_time_zone

  def validate_time_zone
    # using guard clause and let the built in validation do the presence validation
    return unless org.present? && time_zone.present?

    # A temp variable is a code smell, but here we have an underlying concept
    # that is better to be named
    allowed_time_zones = org.country.states.pluck(:time_zone)

    # tip: you can use the .exclude? API if you don't want to a use guard clause
    return if allowed_time_zones.include?(time_zone)

    errors.add(:time_zone, :invalid)
  end
end


You don't need to reverse a doubly linked list, which is an O(n) operation.
Just define a structure that will hold the head and tail of the list.
struct List
{
  Node* head;
  Node* tail;
  unsigned int count; // you can also keep track of number of nodes to access the count in O(1)
}

Functions manipulating the list shall now accept List* list rather then Node** head. They will also have to contain logic that checks and assigns the tail, but none of the operations should get any more complex in terms of its big-O time complexity.
Now traversing the list in reversed order is just matter of traversing the list from tail to head, rather then head to tail direction.
Doubly linked list without a tail is basically a singly linked list with capability to traverse back from where you already traversed forward, but never directly from the tail towards the head (without additional effort).


Better practice to find the max/min element in a loop

Enumerable has many useful methods that solve problems like this. In this case you want map and min or min_by:

closest_trigger_utc_time = following_triggers.map{|test| test.utc_time}.min

2**(0.size * 8 -2) -1 is a bad way to write infinity. If you must have an infinity value, use Float::INFINITY instead, but it's better to avoid this. min returns nil for empty input, so it's convenient to use that as the default value, or replace it with something else by closest_trigger_utc_time || some_meaningful_default.


Displaying a table using DataTables and AngularJS

I think your question is architectural in its nature, and it's rather hard to tell whether you want to prerender as much as you can on server side (meaning via PHP) or do most of the work on the client (i.e. via Angular.js). Each approach has its pros and cons.

Here are a few sources that may help you form your opinion about whether to go

client-heavy (would be my default pick)
server-heavy
spread complexity across layers (I'm really not a fan of having bits and pieces of scattered business logic).

To get a more definitive answer about which way to go, you would really need to provide the list of both functional and non-functional requirements to your system.


Custom sorting algo / optimized bubble sort

The design makes no sense in terms of Object-Oriented principles:

The inheritance relation between the two classes makes no logical sense.  It seems to serve the sole purpose of sharing the scanner instance.  Inheritance is more than mechanism for sharing variables.  It has application (aka business) meaning.  It defines "is kind of" relationship: a Dog is a kind of Animal.
The class names say absolutely nothing about what the code does. Well, one could argue that Main serves as the program's entry point.  I've seen this "naming convention" in actual java projects so that's passable.  I would call it something like ArraySorter.  It is also acceptable to add the main() method to the other methods instead of putting in a separate class.  Methods class is another matter: There has to be better name that describes what the collection of methods do.  In conclusion, it is up to you whether PushMaxSorter has its own main() method or keep it separate.
So, if we look at Methods as PushMaxSorter that is a class that implements your improved bubble sort algorithm, then getArray() can be regarded as a constructor.  and it should take a Scanner instance as argument.
So, from the above constructor, we deduce that PushMaxSorter holds the int array as internal data structure.  So the sort method should accept no arg and return void and if you wish you can add getArray() that is a "classic" getter method: allows access to the instance variable.
regarding printArr(): so we now can deduce that this method also accept no arg.  It is considered "best parctice" that a class with a data structure (or just a bunch of variables) will have a string representation of its internal state by overriding Object's toString() method.  This allows the caller to conrtol to which output the String is written.

Regarding complexity, I admit this is not my expertise. However, I do not see any  signs of exponential iteration on the data structure.  Your algorithm may improve upon the performance of classic bubble sort, but complexity is about scaling: comparing the performance of the same algorithm on input that is increasing in size. I'd say complexity here is the same as classic bubble sort, which is O(n^2)

Note: a more robust and extensible design will say that you need to decouple the data structure from the sorting algorithm (much like the Java Collections framework) so that you can apply your improved algorithm not only to array of integers.  But I think that is an "advanced" topic that requires deeper study of advanced OO principles.


Last three values sfdc trigger functionalty

You should try to keep the logic out of the trigger itself and try to put it into a handler class. This goes along with the one trigger per object pattern. What would happen if you needed to add another trigger on the same object that performed logic after update or before insert?
It looks like you might be replicating standard functionality with your split function. Make sure the standard split method not will meet your needs.


Small Code duplication

var existUserGroups = db.Users.Where(u => u.ID == user.ID).Single().UserGroups;
var existUserGroupsIds = db.Users.Where(u => u.ID == user.ID).Single().UserGroups.Select(ug => ug.ID).ToArray<int>();

can be reduced to

var existUserGroups = db.Users.Where(u => u.ID == user.ID).Single().UserGroups;
var existUserGroupsIds = existUserGroups.Select(ug => ug.ID).ToArray<int>();

The //Add part

Should be simplified using a foreach loop and made more readable by using the Contains() method

foreach (int newId in newUserGroupsIds)
{
    if (!existUserGroupsIds.Contains(newId))
    {
        existUserGroups.Add(db.UserGroups.Where(ug => ug.ID == newId).Single());
    }
}

The //Remove part

var diff = existUserGroupsIds.Except(newUserGroupsIds);

diff will never be null => the null check can be skipped
using a for..each instead of a for loop => the check for diff.Count() > 0 can be skipped

var diff = existUserGroupsIds.Except(newUserGroupsIds);
foreach (int id in diff)
{
    existUserGroups.Remove(db.UserGroups.Where(ug => ug.ID == id).Single());
}


Euler Project 14 - Longest Collatz Sequence in PHP

Redoing tons of work

Consider a number like 100. By the time $n gets to 100, we will have already done the work for $n == 50 (which has a length of 25). So rather than simply seeing that the result for $n was 25, and adding 1 (since we're one step away from that) -- we have to recalculate all 26 steps from scratch.

For that matter, we'd've already done $n as 33, so just by having gotten to 100, we should already know that it's at 26 without doing any work.

Save your state as you go along - this is known as memoization. Given that the resulting longest chain is of length 525, that's a lot of work that we'll end up saving. Just that one chain will end up with 525 operations instead of 138,075...


Rectangularize a list-of-lists structure

You can find a maximum without sorting. Instead of

len(sorted(x,key=len, reverse=True)[0])

you can use either of these:

len(max(x, key=len))
max(len(s) for s in x)

For a more generic solution I propose this:

import itertools

def rectangularize(nested_list, dimensions, fill_value=None):
    flat = nested_list
    for dim in range(dimensions-2, -1, -1):
        size = max(len(s) for s in flat)
        for s in flat:
            s.extend([] if dim else fill_value for _ in range(size - len(s)))
        flat = list(itertools.chain.from_iterable(flat))

x=[[[[4,3,4,5],[1],[2,2]],[[3,6,7],[2,3],[1]]],[[[1]]]]
rectangularize(x, 4)
print(x)

To explain:

The flat list is a flattened view of one dimension of nested_list. It contains references to sublists of nested_list; extending the sublists through flat mutates nested_list.
flat = list(itertools.chain.from_iterable(flat)) advances flat to the next dimension by concatenating the sublists.
The main loop runs dimensions-1 times because the outermost list never needs to be extended.
I'm using range(dimensions-2, -1, -1) to make dim == 0 in the final iteration where a different fill value is needed, so I can use a clean if dim else to deal with that.


Something to keep in mind is that this statement is truncating data:
        arr[j]=av;

because it is assigning a double to an int.
As was mentioned in a comment there are c++ container types that would be better than a old C style array, two of these are std::array<type, arraySize> and std::vector<type>. std::array is a fixed size and std::vector is a variable size. Both would allow the use of iterators that might simplify the code.
Avoid using namespace std;
If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.
std::endl
It is better for performance if "\n" is used rather than std::endl in output, std::endl flushes the output buffer as well as putting out a new line, and this can slow down loops.
Complexity
The function replaverage should really be 2 functions, one to input the data and a second to process the data. Perhaps a third to print the data.
Horizontal Spacing
It would be better if there were spaces around operators that separate operands.
#include <iostream>
#include <vector>

std::vector<int> getData()
{
    int n;
    std::vector<int> intputData;
    std::cout << "Enter array length\n";
    std::cin >> n;
    std::cout << "Enter the numbers\n";
    for(int i = 0; i < n; i++){
        int tmpIn;
        std::cin >> tmpIn;
        intputData.push_back(tmpIn);
    }

    return intputData;
}

void modifyData(std::vector<int> &data)
{
    int f=data[0];
    int l=data[data.size() - 1];
    double av = (f + l)/2;
    for (auto j: data)
    {
        if(j < av){
            j = av;
        }
    }
}

void printData(std::vector<int> &data)
{
    for (auto i: data)
    {
        std::cout << i << " ";
    }
}

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

    std::vector<int> data = getData();
    modifyData(data);
    printData(data);

    return 0;
}


API Get Request to pull data from an online database

My approach to your code:

# If this data isn't going to change, using constants would be good enough
HEADERS = { 'x-rapidapi-host' => ENV['HOST'],
            'x-rapidapi-key' => ENV['API_KEY'] }.freeze

def self.get_game_details(game_selection)
  # If Game is an ActiveRecord class, probably you should modify this to look
  # for the specific record instead of loading everything with .all
  # If is just a PORO, forget what I said.
  game = Game.all[game_selection.to_i - 1]
  return if game.description.present?

  response = RestClient.get("#{DETAIL_URL}#{slug}", HEADERS)
  data = JSON.parse(response.body)
  game.details = data
end

class Game
  ALLOWED_RATINGS = %w[recommended exceptional meh skip].freeze

  # Moved most of the assigning logic into the Game class. This is debatible as
  # I could use a Service class or another pattern for this, but as I don't
  # know your code's nature, to me looks like the quickest way.
  def details=(data)
    self.description = data['description']
    self.released = data['released']
    # .presence will return nil for blank strings, empty arrays, etc, then with
    # || you will default the value to 0, as:
    #
    #   nil || 0 # => 0
    self.metacritic_rating = data['metacritic'].presence || 0

    data['ratings'].each { |rating| self.rating = rating }
  end

  def rating=(rating)
    # .send method can run any method of this class, so better to check if the
    # value is valid first
    return unless ALLOWED_RATINGS.include? rating['title']

    send("#{rating['title']}_rating=", rating['percent'].presence || 0.0)
  end
end


Algorithm for dividing a number into largest "power of two" buckets?

CertainPerformance's solution using .toString(2) is clever, but for a fast solution to such an elementary problem, simple bit manipulation and a while loop is the way to go:

function split(number, bits = 5) {
  let unit = 1 << bits;
  const result = new Array(number >> bits).fill(unit);
  while (unit >= 1) {
    unit >>= 1;
    if (number & unit) result.push(unit);
  }
  return result;
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];
numbers.forEach(n => console.log(n, '=', split(n).join(' + ')));

In particular, you can indeed avoid division and Math.floor() by using the bitwise right shift operator >> instead: n >> k is a fast and compact way of calculating Math.trunc(n / 2**k) for any integer n and any non-negative integer k.  Also, the bitwise AND operator & makes it easy to check whether an integer has a particular bit set: n & k evaluates to a non-zero value if and only if n and k have any set bits in common.

Ps. To make this code even faster, at the cost of some extra complexity, we can precalculate the length of the result array so that we don't need to use .push():

function split(number, bits = 5) {
  // precalculate the length of the result array
  const maxUnit = 1 << bits, prefixLength = number >> bits;
  let length = prefixLength, unit = maxUnit;
  while (unit >= 1) {
    unit >>= 1;
    if (number & unit) length++;
  }

  // allocate and fill the array
  const result = new Array(length).fill(maxUnit);
  let i = prefixLength; unit = maxUnit;
  while (unit >= 1) {
    unit >>= 1;
    if (number & unit) result[i++] = unit;
  }
  return result;
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201];
numbers.forEach(n => console.log(n, '=', split(n).join(' + ')));

According to a quick benchmark, the preallocating version is about 40% faster than the one using .push() (and both are several times faster than the other solutions posted so far).

Pps. It turns out that, maybe a bit counter-intuitively, just building the entire output array one element at a time using .push() may be the simplest and fastest solution, at least for inputs that aren't too huge.  The credit for this solution goes to superb rain, so I'll just link to their answer for it, but I've added it to my benchmark above.  It seems to perform about as well in the benchmark (for all numbers from 0 to 999) as my fastest solution on Firefox, and outperforms all my solutions on Chrome.


I found about 5 things that can be improved, or maybe it's more accurate to say that I did 5 passes over the code in my efforts to improve it. Here's the changes I would recommend, in the order that I encountered them.

Better Names

The first change was mostly cosmetic, but it was very helpful laying the groundwork for more changes later.

def repeatedSpan[T](iterable: Iterable[T], pred: T => Boolean): List[Iterable[T]] = {
  if (iterable.isEmpty) Nil
  else {
    val (matches, rest) = iterable.span(pred)
    if (matches.isEmpty) rest.take(1) :: repeatedSpan(rest.tail, pred)
    else matches :: repeatedSpan(rest, pred)
  }
}

Naming is hard, particularly as rest is really the element that failed the predicate, and everything past that point.

Multiple Parameter Lists

This change was partially a help for the compiler, and partially to enable a bit of syntax that I'm partial to.

def repeatedSpan[T](col: Iterable[T])(pred: T => Boolean): List[Iterable[T]] = {
  if (col.isEmpty) Nil
  else {
    val (a, b) = col.span(pred)
    if (a.isEmpty) b.take(1) :: repeatedSpan(b.tail)(pred)
    else a :: repeatedSpan(b)(pred)
  }
}

By switching to a signature with multiple parameters, the compiler can infer types more easily, and as an additional bonus users can now use the shortened function literal syntax.

repeatedSpan(basicList, (a:Int) => a != 1) # Not bad to type
repeatedSpan(basicList)(_ != 1)            # Much nicer!

Pattern Matching

The next change moved from if () else to pattern matching. I did this for two reasons. The first is that it allowed better naming that rest and generally made the logic a bit more clear. The second was that it paves the way for one of the other changes that I had my eye on.

def repeatedSpan[T](iterable: Iterable[T])(pred: T => Boolean): List[Iterable[T]] =
  iterable.span(pred) match {
    case (Nil, doesNotMatch :: unTested) =>
      List(doesNotMatch) :: repeatedSpan(unTested)(pred)
    case (matchingPrefix, doesNotMatch :: unTested) =>
      matchingPrefix :: List(doesNotMatch) :: repeatedSpan(unTested)(pred)
    case (matchingPrefix, Nil) => List(matchingPrefix)
  }

This had the added bonus of eliminating a level of nesting, but the big gain was being able to easily decompose the results into matchingPrefix, doesNotMatch, and unTested.

Tail Recursion

One of the big remaining issues is that this will blow the stack on large lists. So the next step, facilitated by the simplification we gained by switching to pattern matching, was to rework it into a tail recursive version.

def repeatedSpan[T](iterable: Iterable[T])(pred: T => Boolean): List[Iterable[T]] = {
  @tailrec
  def loop(accum: List[Iterable[T]], rest: Iterable[T]): List[Iterable[T]] =
    rest.span(pred) match {
      case (Nil, doesNotMatch :: unTested) =>
        loop(List(doesNotMatch) :: accum, unTested)
      case (matchingPrefix, doesNotMatch :: unTested) =>
        loop(List(doesNotMatch) :: matchingPrefix :: accum, unTested)
      case (matchingPrefix, Nil) => List(matchingPrefix)
        matchingPrefix :: accum
    }
  loop(Nil, iterable).reverse
}

This has a major weakness. Tail recursion lets us work with large Iterables, but a List is a singly linked list, and they do not append well. To fix this, I created the list in reverse, then at the end reversed the result. I was not particularly happy with adding this complexity, but it was necessary to gain access to tail-call optimization and avoid blowing the stack with larger lists.

Program to the Interface

The best way to remove the unnecessary complexity introduced in the last step was to switch data structures. This would be more difficult if this had a bunch of code that called it, but it was simple to modify the signature and use a Vector instead, which has excellent append performance.

def repeatedSpan[T](iterable: Iterable[T])(pred: T => Boolean): Iterable[Iterable[T]] = {
  @tailrec
  def loop(accum: Vector[Iterable[T]], rest: Iterable[T]): Iterable[Iterable[T]] =
    rest.span(pred) match {
      case (Nil, doesNotMatch :: unTested) => loop(accum :+ List(doesNotMatch), unTested)
      case (matches, doesNotMatch :: unTested) => loop(accum :+ matches :+ List(doesNotMatch), unTested)
      case (matches, Nil) => accum :+ matches
    }
  loop(Vector(), iterable)
}

Now that we are using a more appropriate data structure, we have regained the simplicity we had before, and don't run out of stack space.


(de)serializing c++ object almost automagically

Avoid creating namespace aliases in header files
I assume that at least the declaration of class properties would be put in a header file. In that case, consider that users of that header file might not expect namespace nlm to be declared, so I recommend just writing out nlohmann fully.
Spelling
A minor issue: it is serializer, not serializor.
Function names
Avoid overloading state() to mean either setting the state or getting the state. While related, these are different operations, and it is much better to make that explicit by giving them different function names. An obvious modification is to name them get_state() and set_state(), but that sounds quite generic. I would also make it explicit that you are converting to or from JSON, so consider naming them to_json() and from_json().
Overhead
Your serialization method introduces a huge overhead. Every instance of a serializable struct now has to contain a std::unordered_map, which is filled in in the constructor. So this costs time and memory. It would be much nicer if you could build this only once per type that derives from properties. Perhaps it can be done using static variables and CRTP, something like:
template<typename T>
struct properties
{
    struct registry
    {
        // keeps the actual mapping
        ...
    };

    template <typename U>
    void set(str::string_view const& k, U&& v) {
        // forward it to the registry object, along with a pointer to the object
        auto self = static_cast<T *>(this);
        self->registry.set(self, k, v);
    }

    ...
};

struct S: properties<S>
{
    bool b{};
    int i{};

    static properties::registry reg_;

public:
    ...
};

S::properties::registry S::reg_ = {{"b", &S::b}, {"i", &S::i}};

But I struggle myself with how to create a constructor for properties::registry that would allow the above code (especially the last line) to work.
Make get() const
You should make the get() member function const, as it should not modify the state, and this will allow that functions to be used on const instances of classes that inherit from properties.
Use range-for where possible
You can simplify the code in some places by using range-for. For example, in properties::state(), where you can also combine it with structured binding:
for (auto &[name, variable]: reg_)
{
    r.emplace(name, variable.serializer());
}

It is unfortunate that the iterator of nlm::json doesn't work the same way; you can only access the value in a range-for, not the key.
Crash at runtime when accessing a non-existing property
If in main(), you call s.get("x"), the program crashes with a segmentation fault. Even if you never expect this function to be called with a user-supplied name, it still makes it hard to debug programming errors. Check the return value of calls to find() before trying to dereference the result. You could throw a std::runtime_error if find() return nulltpr, or if you don't want to use exceptions or pay for the performance cost in production builds, at least use assert() to help with debug builds.


Which is cleaner: a constructor with many parameters or many setters after construction?

Where do you want to validate the parameters?

If the parameters are passed inside the constructor (either as multiple parameters or as a structure), the constructor can check all of them and throw an exception if something is missing/off. That way, the other methods of the class can assume they are valid.
If the parameters are passed using setters, then every method needs to check if all the required values are present and valid. If the code runs in a multithreaded context, then there's additional protections needed as a value can change unexpectedly inside a method call if a setter is called from a different thread.


1. Bug

I tried a different test case:

graph = [[1, 0, 0, 0, 1], [1, 1, 0, 1, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 0, 0, 0, 0]]
rows = 5
cols = 5
length = 8

and then findFinalPath returned the following path:

[(0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0), (3, 2), (4, 2)]

This is not a legal path, since (2, 0) is not adjacent to (3, 2).

I give an explanation for this bug in 2.18 below, but it would be a good exercise to for you to try to figure out for yourself what's going wrong here. How does your search manage to step from (2, 0) to (3, 2)?

2. Comments on your code

No docstrings! What do your functions do, and how do you call them?
This kind of program is an excellent candidate for doctests.
The use of global variables makes your code difficult to re-use. For example, the global variable graph means that it would be awkward if you ever wanted to find paths in two different graphs.

When you have persistent state (like your graph) with associated operations (like your function positionInGraph) it's often a good idea to organize your code into classes and methods respectively. See section 3 below for how I would do this in your case.
You don't guard the execution of the test program with if __name__ == __main__:. This means that when I import your program into an interactive Python interpreter, it immediately starts running, which makes it harder for me to test. Put your test code into test functions or doctests.
Returning the string "impossible" when no path is found isn't the best way to design the interface. Returning an exceptional value to indicate failure tends to be error-prone: it's too easy for the caller to forget to check. It's usually better to raise an exception when exceptional circumstances are encountered.
You represent your coordinates as a pair (y, x). It would be slightly easier to understand the output of your program if you represented coordinates in the usual way (x, y). This would of course require a corresponding change, either looking up cells with graph[pos[1]][pos[0]] (preferred) or transposing your matrix so that it is in column-major order.
You set the number of rows and columns by hand but these numbers are easy to determine: they are len(graph) and len(graph[0]) respectively. (I prefer to call these numbers height and width myself.)
Your functions positionInGraph, positionNotVisited and positionIsEmpty all take a pos as their argument, but getAdjacent takes two arguments posx and posy (which are wrongly named: posx is the y-coordinate and vice versa). You should generally strive to be consistent in little details like this: it makes it easier to remember how to call functions.
The Python style guide (PEP8) says that "Function names should be lowercase, with words separated by underscores as necessary to improve readability" and the same for variable names. So you should consider changing positionIsEmpty to position_is_empty and so on. (You're not obliged to follow PEP8 but it makes it easier for other Python programmers to read your code.)
You can use itertools.product to avoid nested loops.
The loop

for i in adjQueue:
    processQueue.append(i)

can be written

processQueue.extend(adjQueue)

You have a variable called processQueue but it is not a queue. A queue is a data structure where you add elements to one end of a list and remove them from the other end (in Python you would use collections.deque). A data structure where you add and remove elements at the same end is called a stack.
You have a variable counter that you increment and decrement in parallel with adding and removing positions to pathList, so that counter is always the length of pathList. It would be better to drop counter and call len(pathList) instead: one less thing to go wrong. (If you were worried that len(pathList) might be an O(n) operation as it is in some languages, you can look at the TimeComplexity page on the Python wiki for reassurance.)
If you have an algorithm that uses a stack, it's often easiest and clearest to implement it as a recursive function (you can implicitly use the function call stack instead of having to explicitly push and pop your own stack). See section 3 below for how to do this.
You give the maze once in a comment:

# oxoo
# xoxo
# ooxo
# xooo
# oxox

and then again in code:

graph = [[0,1,0,0],[1,0,1,0],[0,0,1,0],[1,0,0,0],[0,1,0,1]]

This violates the DRY principle (Don't Repeat Yourself): it would be easy for you to make a mistake when encoding your maze as a matrix of 1s and 0s. Why not get the computer to do it for you?
Similarly, it's hard for you to check the results of your program, because the path comes out as a list of coordinates, which is tedious and error-prone to check by eye. Even in the buggy example I gave in section 1 above, it would be easy to give it a quick look and miss the error. It would be better to present the results in a form that's easy for you to check. (See section 3 below for how I did this.)
Your code has much unnecessary use of parentheses. The lines

return ((pos[0] >= 0) and (pos[1] >= 0)) and ((pos[0] < rows) and (pos[1] < cols))
return not(pos in visited)
return (graph[pos[0]][pos[1]]==0)
if (not(positionIsEmpty(pos)) or (pos in visited)):
while (processQueue and (counter < length)):
return (pathList, counter)

can be written

return 0 <= pos[0] < rows and 0 <= pos[1] < cols
return pos not in visited
return graph[pos[0]][pos[1]] == 0
if not positionIsEmpty(pos) or pos in visited:
while processQueue and counter < length:
return pathList, counter

respectively. "Program as if you know the language"!
Explanation for the bug in section 1: your back-tracking implementation doesn't backtrack all your search state, so that the search state becomes inconsistent. When your search reaches a dead end, it pops the last position from pathList and decrements counter, but does not update the rest of the search state. This means that the next currentPos that gets popped from processQueue will not (in general) be adjacent to the end of the path. When you backtrack in a search, you need to backtrack all your state: in your case pathList, counter, processQueue, and visited all need to be backtracked, but you only update the first two of these, and so it goes wrong.

See the revised code for how I keep the search state consistent. Every addition to the state as the search goes forward:

path.append(p)
visited.add(p)

is matched by a corresponding deletion as the search backtracks:

visited.remove(p)
path.pop()

(There's more to say about this issue, but I've moved this to section 4 below.)

3. Revised code

from itertools import product

class Found(Exception): pass
class NotFoundError(Exception): pass

class Maze(object):
    """A rectangular matrix of cells representing a maze.

    Describe the maze to the constructor in the form of a string
    containing dots for empty cells and any other character for walls.

        >>> m = Maze('''.#..
        ...             #.#.
        ...             ..#.
        ...             #...
        ...             .#.#''')
        >>> print(m.format(m.path(8)))
        .#.o
        #.#o
        oo#o
        #ooo
        .#.#
        >>> print(m.format(m.path(10)))
        ... # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
          ...
        NotFoundError: no path of length 10

    """
    def __init__(self, maze):
        self.matrix = [[c != '.' for c in line] for line in maze.split()]
        self.height = len(self.matrix)
        self.width = len(self.matrix[0])
        assert all(len(row) == self.width for row in self.matrix)

    def in_bounds(self, p):
        """Return True if `p` is a legal position in the matrix."""
        return 0 <= p[0] < self.width and 0 <= p[1] < self.height

    def empty(self, p):
        """Return True if `p` is an empty position in the matrix."""
        return not self.matrix[p[1]][p[0]]

    def neighbours(self, p):
        """Generate legal positions adjacent to `p`."""
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            q = p[0] + dx, p[1] + dy
            if self.in_bounds(q):
                yield q

    def path(self, n):
        """Find a path of length `n` in the maze, or raise NotFoundError if
        there is no such path.

        """
        path = []
        visited = set()
        def search(p):
            path.append(p)
            visited.add(p)
            if len(path) == n:
                raise Found()
            for q in self.neighbours(p):
                if self.empty(q) and q not in visited:
                    search(q)
            visited.remove(p)
            path.pop()
        try:
            for p in product(range(self.width), range(self.height)):
                if self.empty(p):
                    search(p)
        except Found:
            return path
        else:
            raise NotFoundError('no path of length {}'.format(n))

    def format(self, path=()):
        """Format the maze as a string. If optional argument path (an
        iterable) is given, highlight cells in the path.

        """
        path = set(path)
        def row(y):
            for x in range(self.width):
                p = x, y
                if not self.empty(p): yield '#'
                elif p in path: yield 'o'
                else: yield '.'
        return '\n'.join(''.join(row(y)) for y in range(self.height))

4. Extra credit: encapsulation of search state

In 2.18 above I discussed the need to update your search state properly when implementing a back-tracking search. As with any kind of data consistency problem, it's good practice to encapsulate operations that must be performed together.

An easy way to do this in Python is via a context manager. A "context manager" is just an object with __enter__ and __exit__ methods: when the context manager is the subject of a with statement, the __enter__ method is called on entry to the with statement, and the __exit__ method on exit. By putting your forward operations in the  __enter__ method and the back-tracking operations in the __exit__ method you can be sure that these pair up properly.

But an even easier way to do this is to use contextlib.contextmanager to build the context manager for you, like this:

from contextlib import contextmanager

def path(self, n):
    """Find a path of length `n` in the maze, or raise NotFoundError if
    there is no such path.

    """
    path = []
    visited = set()

    @contextmanager
    def visit(p):
        path.append(p)       # Forward: add p to path.
        visited.add(p)       # Forward: mark p as visited.
        yield                # Rest of search happens here.
        visited.remove(p)    # Backtrack: mark p not visited.
        path.pop()           # Backtrack: remove p from path.

    def search(p):
        with visit(p):
            if len(path) == n:
                raise Found()
            for q in self.neighbours(p):
                if self.empty(q) and q not in visited:
                    search(q)
    try:
        for p in product(range(self.width), range(self.height)):
            if self.empty(p):
                search(p)
    except Found:
        return path
    else:
        raise NotFoundError('no path of length {}'.format(n))


Specifying that one set of HTML elements controls a corresponding set

The only part of the code that changes are the index values. What if you don't specific the index yourself, but use the indexof() to let it determ the index itself:

var index;
$('#main-nav li').on({
    mouseenter: function () {
        //alert($(this).index());
        index = $(this).index();
        $('body section:eq(' + index +')').find('.secondState').stop().fadeIn(600);
    },
    mouseleave: function () {
        if ($('body section:eq(' + index +') .toggle').hasClass('current')) {
            return false;
        } else {
            $('body section:eq(' + index +')').find('.secondState').stop().fadeOut(600);
        }
    }
});

I place the index into a variabe so the code doesnt have to determ the index over and over. Now i only fill the index when the mouseenters, because you will have the index of the element were  you entered with.

jsFiddle

I hope this helps.


Packet

private static int packetCount; // Determined at the time of the objects creation [incremental]

I would remove this field. Personally I feel it's odd for a Packet to need to know the number of packets. Apart from that you would need to synchronize access to this field, should your class ever be used in a multi-threading environment.

Node

make data final. A node should never change it's data once created. Remove the setter as well.
Remove the default constructor public Node(). It is unused and does not initialize the (now final) field data.
rename the field data to packet. A clear naming will help other developers and your future self remember what is stored here.

Router

size should be private too

public void enqueue(Packet packet) {
    Node node = new Node(packet);

    if (head == null) {
        head = node;
        tail = node;
    }
    tail.setNext(node);
    node.setPrev(tail);
    tail = node;

    size++;
}

if head == nullyou set head = tail = node. You now have three references to the same Packet object. After that you set next and prev on this object to itself.

public Packet dequeue() {
    Node ptr = head;
    head = ptr.getNext();

    if (head == null) {
        tail = null;
    }

    size--;

    return ptr.getData();
}

If now dequeue is called, head is assigned to ptr (which is the Packet pointing forward and backward to itself. head is assigned ptr.next which means, it is still the same object. head == null will never be true. For every subsequent call to dequeue you will get that Packet.

If another Packet ist enqueued the next call to dequeue will return the first Packet once more and then return the new Packet, removing it from your list.

To fix that, change enqueue to

public void enqueue(Packet packet) {
    Node node = new Node(packet);

    if (head == null) {
        head = node;
        tail = node;
    } else {
        tail.setNext(node);
        node.setPrev(tail);
        tail = node;
    }

    size++;
}

Are you sure, that the output created by recToString is what you want/need?

Calling

router.enqueue(new Packet(11, 11, 11, 11));
router.enqueue(new Packet(22, 22, 22, 22));
router.enqueue(new Packet(33, 33, 33, 33));
System.out.println(router.toString());

yields the output:

Packet #33 => arrive at simulation unit: 33 => packet size: 33
Packet #22 => arrive at simulation unit: 22 => packet size: 22
Packet #11 => arrive at simulation unit: 11 => packet size: 11Packet #22 => arrive at simulation unit: 22 => packet size: 22Packet #33 => arrive at simulation unit: 33 => packet size: 33

Since you implement FIFO I think, the first (head) element should be printed first.

Remove recToString and replace toString:

@Override
public String toString() {
    StringBuilder result = new StringBuilder();

    Node current = head;
    while (current != null) {
        result.append(current.getData().toString()).append("\n");

        current = current.getNext();
    }

    return result.toString();
}

It now starts at head and walks forward through the list till it hits the end.

With recToString removed the only call to Node#getPrev() got removed, too. A FIFO-structure does not need to be double linked. Let's remove it.

Node:

public class Node {
    private Packet data;
    private Node next;

    public Node(Packet data) {
        this.data = data;
        next = null;
    }

    public Packet getData() {
        return data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

Router#enqueue()

public void enqueue(Packet packet) {
    Node node = new Node(packet);

    if (head == null) {
        head = node;
        tail = node;
    } else {
        tail.setNext(node);
        tail = node;
    }

    size++;
}

Edit:
Forgot my own comment.

Exception handling

Create your own Exception:

public class QueueEmptyException extends RuntimeException {
    public QueueEmptyException() {
    }

    public QueueEmptyException(final String message) {
        super(message);
    }

    public QueueEmptyException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public QueueEmptyException(final Throwable cause) {
        super(cause);
    }

    public QueueEmptyException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

Create a method that throws the Exception, if the queue is empty:

private void assertNotEmpty() {
    if (isEmpty()) {
        throw new QueueEmptyException("Queue is emtpy");
    }
}

Change peek

public Packet peek() {
    assertNotEmpty();

    return head.getData();
}

and dequeue

public Packet dequeue() {
    assertNotEmpty();

    [...]
}


Counting terms in Collatz sequences until 1 is reached or a limit is exceeded

Overflow Bug

The reason your program is timing out is because your variable val is defined as an int instead of a long long.  Because of this, val can become negative during the line val=(val*3) + 1, which leads to an infinite loop.  You should change the type of val to long long.  If you want to test the infinite loop yourself, try this test case and see what happens:

113383 2147483647

Output Bug

Your program has two output related errors:

You should initialize n=1 instead of n=0.
Your code is missing the line n++.

The above two problems mean that your program is outputting something like:

Case 0: A = 100, limit = 100000, number of terms = 25
Case 0: A = 101, limit = 100000, number of terms = 25

instead of the correct format of:

Case 1: A = 100, limit = 100000, number of terms = 25
Case 2: A = 101, limit = 100000, number of terms = 25


The lambda expression you pass to Where() is where you define the condition, so this is where it makes the most sense to put all the logic for this.
.Where(u => strict ? u.Nickname.Equals(login) : u.Nickname.Contains(login))

Or for higher performance you can conditionally pass a different lambda expression:
Func<User,bool> checker = strict
  ? (Func<User,bool>)((User u) => u.Nickname.Equals(login))
  : (Func<User,bool>)((User u) => u.Nickname.Contains(login));

...

.Where(checker)


If you want to write production-ready code using node, then you should use node modules to divide your code into independent, maintainable modules. Even better, use a framework (Express). It provides "development" and "productions" options for the application and it also solves the trivial common issues for you, like setting up a router. You can also use an scaffolding tool, to generate a standard folder structure for your app.

For reading values from a config file, create a new module and store all the application wide configuration in it, instead of reading directly from a .json file.

Coming to onListening() function, it's not a good practice to hardcode url's. It's better to store them in a config module and require it when needed.


More succinct / ideal solution to Project Euler #22

Yes. I think you still miss a very useful part of clojure - using its various collection types to model your solution. In your problem, you could use the fact that a string is a seq and a map acts as a function to calculate the cost of a word:

;; this map will act as a function from a name to its ordinal
(def name->position (zipmap names (map inc (range))))

;; and this map will act as a function from letter to its ordinal
(def ab-map (zipmap alphabet (map inc (range))))

Now that we have these two functions, we could easily calculate a name's value in this way:

(defn score [word]
  (* (reduce + (map ab-map word))
     (name->position word 0)))

You can now calculate COLIN:
(score "COLIN")

Explicit recursion can many times be avoided by using functions like map and reduce, mainly because often the sequences themselves are defined in terms of recursion

From here, you could solve this question by using map and reduce with the new function score


Determining whether a string can be rearranged into a palindrome

int

All the counters are inherently non-negative. I recommend to make them unsigned, just to clarify your intentions.
What to return

Computing return value

    if (condition) {
        return false;
    }
    return true;

is a long way to say

    return !condition;

Actual condition

    oddCount != 0 && oddCount != 1

is a long way to say

        oddCount > 1

So I recommend to simply

    return oddCount < 2;

Efficiency

I wouldn't bother about performance at all. However, you may shave few cycles:

    ....
    charCount[(int)input.charAt(i)] ^= 1;
    ....
    oddCount += charCount[i];

thus avoiding taking modulo and making decisions inside the loop. I don't think it will make any difference however.
Assumptions and restrictions

Traditionally A man, a plan, a canal, Panama! is considered a palindrome. You really need to say what is a palindrome in your setting.


Shopping cart login and coupon code validation

You need to learn how to use prepared statements, aka queries. That way, user input is never part of the SQL command.

https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

http://prash.me/php-pdo-and-prepared-statements/


Assigning values to array elements based on a lookup table

if (lookup.ContainsKey(transmitter))
        {
          var receiverLookup = lookup[transmitter];

This searches for the KeyValuePair twice. There's a more efficient approach:

        if (lookup.TryGetValue(transmitter, out var receiverLookup))

      var ungrouped = receivers.Except(blocksTracker).ToArray();

      foreach (var receiver in ungrouped)
      {
        blocks.Add(new Block(){Id = receiver, status = "red"});
        blocksTracker.Add(receiver);
      }

The ToArray() there is unnecessary: the enumerable can be left as a lazy enumerable because the only use is to iterate over it once.

          var intersection = receivers.Intersect(receiverLookup).ToArray();
          if (intersection.Length > 0)
          {
             blocks.Add(new Block() { Id = transmitter, status = "yellow"});
             blocksTracker.Add(transmitter);
            foreach (var receiver in intersection)
            {
              blocks.Add(new Block(){Id = receiver, status = "yellow"});
              blocksTracker.Add(receiver);
            }
          } else
          {
            blocks.Add(new Block(){Id = transmitter, status = "red"});
            blocksTracker.Add(transmitter);
          }

This seems rather complicated. I think the whole thing could be simplified:

var transmittersPaired = new HashSet<string>();
var receiversPaired = new HashSet<string>();

foreach (var transmitter in transmitters)
{
    if (lookup.TryGetValue(transmitter, out var receiverLookup) && receiverLookup.Any())
    {
        transmittersPaired.Add(transmitter);
        foreach (var receiver in receiverLookup)
        {
            receiversSeen.Add(receiver);
        }
    }
}

var blocks = new List<Block>();
foreach (var transmitter in transmitters)
{
    blocks.Add(new Block { Id = transmitter, status = transmittersPaired.Contains(transmitter) ? "yellow" : "red" });
}
foreach (var receiver in receivers)
{
    blocks.Add(new Block { Id = receiver, status = receiversPaired.Contains(receiver) ? "yellow" : "red" });
}

There's still some repeated code, which might be simplified in one of two ways. If there's a guarantee that the transmitters and receivers will never share IDs then transmittersPaired and receiversPaired could be merged into one set, and the foreach loops at the end could be merged into one loop over transmitters.Concat(receivers). Alternatively, a method could be factored out.