Two similar MongoDB-querying functions to find distinct and non-distinct documents

You could return early on errors. This way, you don't nest as much.

I'm not sure if getConnection, find and distinctDocuments are custom functions or library functions based on the example. But if you are able to update their implementation or swap it out for another library, use Promises. That way you avoid callback hell.

Also, I really hate functions that do too much. Some developers tend to just put multiple similar functionalities in one function and distinguish them via an argument. But when more functionality is added or when the functionalities diverge, the implementation becomes monolithic and hard to refactor. So I suggest that until a third or fourth function with the same flow comes in, I would keep it as is.

If the implementation used promises, it would be as easy as:

collectionFind: function collectionFind(collectionName, query, fields, options) {
  const url = getUrl();

  if (!url) return logger.error('No mongodb connection set');

  return getConnection(url)
    .then(db => find(db, collectionName, query, fields, options))
    .catch(err => {
      logger.error(err);
      clearConnection();
      throw err; // rethrow
    });
}
collectionDistinct: function collectionDistinct(collectionName, field, filter) {
  const url = getUrl();

  if(!url) return logger.error('No mongodb connection set');

  return getConnection(url)
    .then(db => distinctDocuments(db, collectionName, field, filter))
    .catch(err => {
      logger.error(err);
      clearConnection();
      throw err; // rethrow
    });
}

// Usage
ns.collectionFind(...).then(result => {

}, err => {

});

ns.collectionDistinct(...).then(result => {

}, err => {

});


Out of order bug
It appears that there could be a case where the items inserted into the channel can be read out of order.  From reading your test code,  it seems that you want to maintain a FIFO ordering, so I am guessing this is unwanted behavior.  Here's the sequence of events that can trigger the behavior:

Initially, sendIdx recvIdx are -1, and slen rlen are 0.
Thread 1 calls Send, and atomically increments sendIdx to 0.
Thread 1 is context switched out before filling in q[0].
Thread 2 calls Send, and atomically increments sendIdx to 1.
Thread 2 fills in ch.q[1] and atomically increments slen to 1.
Thread 3 calls Recv, and sees that there is 1 element in the queue because slen - rlen = 1.
Thread 3 atomically increments recvIdx to 0.
Thread 3 tries to do a read from q[0] but finds that it was empty.
Thread 3 atomically increments recvIdx to 1.
Thread 3 reads from q[1] and find the value placed there by Thread 2.
Thread 1 wakes up an inserts its element into q[0].

So at this point, the item added by Thread 2 in q[1] was read before the item added by Thread 1 in q[0], but it could be argued that Thread 2 inserted its element timewise before Thread 1 so that behavior might be OK.  However:

Thread 1 calls Send again, and inserts an element into q[2].
Thread 3 calls Recv and reads the element from q[2].
Thread 3 calls Recv and reads the element from q[0] (after wrapping around the queue once).

Now, it is clear that Thread 1 sent q[0] before q[2], but Thread 3 received q[2] before q[0], which is out of order.


LINQ has two syntaxes to offer. You've used the method syntax, which I find very neat and useful, but for simpler queries I find the query syntax looks much less bulky in VB.NET:

Dim result = (From p In GetType(TObject).GetProperties()
              Where p.Name = PropertyName _
                  AndAlso p.CanRead() _
                  AndAlso p.PropertyType Is GetType(TProperty)
              Select p) _
             .FirstOrDefault()

It removes the inline Function(p) anonymous function declaration, and leaves it up to the compiler to generate it, which in turns frees your code from some of the boilerplate.


Yes. You can simplify this code. I made two main changes.

First, I forget that \$x_{50}\$ is known and write an equation for it just like all the other variables, then I replace that equation by the equation \$x_{50}=1\$.

Second, this is a system of linear equations. Notice that on both sides of the equation we have \$a_{ij}b_{kij}\$ with \$\{i,j,k\}=\{s,t,r\}\$ on the left and \$\{i,j,k\}=\{r,t,s\}\$ on the right, and both are summed over \$t\$ which corresponds to \$j\$. So first I find the matrix \$C_{ik}=\sum_ja_{ij}b_{kij}\$, which requires quite some tweaking due to the messed up dimensions/slices. Now the equation reads

\$\displaystyle x_{s}\sum_{r=1}^R C_{sr} = \sum_{r=1}^R C_{rs}x_r \$

for each \$s\in1,2,\ldots,S\$. The sum of the left is just sum(C,2) in Matlab, and the sum on the right is the matrix multiplication of \$C^t\$ with the vector of unknowns \$\vec x\$. We can write the equation in matrix form as

\$\displaystyle \vec c\vec x-C\vec x=0 \$

where \$[\vec c]_s=\sum_r C_{sr}\$. Written another way, we have

\$\displaystyle \left(\mathrm{diag}(\vec c)-C\right)\vec x=0. \$

Now since we know \$x_{50}=1\$ just replace the last row of the matrix with \$[0,0,\ldots,0,1]\$. Then if \$M=\mathrm{diag}(\vec c)-C\$ our equation is \$M\vec x=\vec v\$ where \$\vec v=[0,0,\ldots,0,1]^t\$. We can solve this system directly using \.

%% Define parameters
T = 3; % Number of types (T)
S = 3; % Number of senders (S)
R = S; % Number of receivers (R), equals the number of senders
A = [.1 .1 .1   % Columns are senders (S), rows are types (T)
     .3 .3 .6
     .6 .6 .3];
B1 = [.9 .0 .1
      .5 .1 .2
      .8 .2 .1];
B2 = [.0 .7 .2
      .2 .9 .0
      .1 .8 .1];
B3 = [.1 .3 .7
      .3 .0 .8
      .1 .0 .8];

C = squeeze(sum(A.*cat(3,B1,B2,B3),1)).';

M = diag(sum(C,1))-C; % matrix equations
M(end,:) = [zeros(1,S-1) 1]; % replace the last equation

v = [zeros(S-1,1);1]; % modify final RHS entry

F = M\v;

An additional benefit is that solving linear systems is much faster than solving nonlinear systems, so this code is much faster. I couldn't test with different R, S, or T so something might have to change, I'm not sure if it will just work, but I think it should.

With the new method for generating the equations, we can make a few more simplifications to avoid having to concatenate the Bi's explicitly, using a cell array:

T = 3; % Number of types (T)
S = 3; % Number of senders (S)
R = S; % Number of receivers (R), equals the number of senders
A = [.1 .1 .1   % Columns are senders (S), rows are types (T)
     .3 .3 .6
     .6 .6 .3];
B{1} = [.9 .0 .1
      .5 .1 .2
      .8 .2 .1];
B{2} = [.0 .7 .2
      .2 .9 .0
      .1 .8 .1];
B{3} = [.1 .3 .7
      .3 .0 .8
      .1 .0 .8];

C = squeeze(sum(A.*cat(3,B{:}),1)).';

M = diag(sum(C,1))-C;
M(end,:) = [zeros(1,S-1) 1];

v = [zeros(S-1,1);1];

F = M\v;


Let's get a closer look at the sum you're trying to calculate:

$$start + (start+step) + (start+2 \times{}step) + \ldots + (start + (len-1)\times{} step)$$

Which can be reordered as:

$$start + \ldots + start + step + 2\times{}step + \ldots + (len-1)\times{}step$$

Which gives you a nice formula regardless of the sign of start or step or even the value of stop:

$$start \times{} len + step \times\frac{len(len-1)}{2}$$

All the complexity being hidden in the len(range_obj) call. So you can just write:

def sum_of_range(range_obj):
    """Calculates the sum of a range object (Python 3) in O(1).

    This function always returns a python integer representing the sum
    without loss of precision (as would happen if it uses intermediate
    floating point values).
    """

    length = len(range_obj)
    step_counts = length * (length - 1) // 2
    return range_obj.start * length + range_obj.step * step_counts


I apologize for updating my answer multiple times. I shouldn't upload my answer when I'm tired.
I'm going to ignore the running time complexity to avoid confusing you.
If you want to know, this will run in O(n^2) time. This can be simplified to O(n log n) time using a tree, but using and explaining a tree might confuse a beginner.
The simplest way to do and undertand this is as follows:
    # you don't need "import os" in this case.
    new_dict = {}

    # This is to open the file to get the count of all words:
    filename = 'abc.txt'
    with open(filename, "r") as fp:
        for line in fp:
            # For this to work, make sure the words don't end with any punctuation.
            # If any words end with a punctuation, take a look into re.sub()
            words = line.split()

            for word in words:
                word = word.lower()

                if word not in new_dict:
                    new_dict[word] = 1
                else:
                    new_dict[word] += 1

    # This is to calculate the count of all words:
    total_words = sum(new_dict.values())

    # This is used to get the probability of each word.
    output_file = 'x.txt'
    with open(output_file, "w") as fs:
        # The dictionary is set as: {dictionary_name[key] : value}
        for key, value in sorted(new_dict.items()):
            probability = value / total_words
            fs.write(key + ": " + str(probability) + "\n")

Using for x_variable in collection_variable

When you are using for x_variable in collection_variable, you need to make sure any code using the x_variable resides inside of the for each loop. In this case, I pushed anything that uses word to make sure the word variable is accessible because you are calling it from inside the for word in words iterator.

When to call file.close()

When opening files with the with open(...) function, you don't need to explicitly close it. You can just leave the with open code block and the garbage collector will know you are done with that file. However, if you do open(...) without the with operator, then yeah, you need to call fs.close()

How sorted(variable) works

With simple data types like string, int, float, tuple, list, dictionary, they already include comparison functions, so you can use sorted(variable) to sort them. However, if you have your own data type or object, you need to define the comparison functions for the sorted() to work. Read more about sorted(variable) on Python docs
Hope this helps :)


Function to delete oldest items out of HTML5 localStorage. Can I make it more efficient?

Object.size

First off, if it's ok with you to use ES5 APIs (you use localStorage, it should be okay), then here's a quicker way to get the number of keys in an object using Object.keys.

return Object.keys(obj).length

Delete by N

Also, from what I understand in your code, you're deleting keys by 3's. If so, then you should not hardcode the 3. Instead, have it configurable in your object.

Verbose Variable Naming

Here's one I get often. Name variables according to use. tmpExp will not help anyone understand its purpose. Name them verbosely. I should understand code like I read the back of a milk box or something.

Compress the algorithm

I suggest you compress the algorithm, make it simple.

Nested loops are just bad for performance. Also, getItem is a synchronous operation, which means that if it freezes, it freezes the UI as well. Nesting that along with a JSON.parse makes it even more slow.

If you can, do operations with the least loop runs and function calls as much as possible. If you can cram several loops into one big loop (like batched operations), then do so.

Here's a proposed fix for makeRoom. Keeping it simple, it just removes the oldest among the stored data.

// Just grab the expiry and store the expiry-key into an object
var expiries = Object.keys(localStorage).reduce(function(collection,key){
  var currentExpirationTime = JSON.parse(localStorage.getItem(key)).expirationTime;
  collection[currentExpirationTime] = key;
  return collection;
},{});

// Get the expiry dates into an array
var expiryDates = Object.keys(expiries);

// For N times, find the oldest (smallest timestamp) and destroy
for(var i = 0; i < N; i++){
  var oldestDate = Math.min.apply(null,expiryDates);
  this.destroyItem(expiries[oldestDate]);
}

getTime now()!

Instead of new Date().getTime(), there's the new Date.now(). Same effect, but saves you memory from creating a new Date instance just to get the current timestamp.


I noticed that you are calculating to 314 decimal places instead of 314 digits, so drop 6 instead of 5.

You really don't need the extra functions. You can remove

fun arccot(x:Int) = arccot(x.toBigInteger())

if you convert Int to BigInteger inside your arctan method.
You can remove

operator fun Int.times(x: BigInteger) = this.toBigInteger() * x

if you shl(2) instead of * 4.
You can remove

operator fun BigInteger.plus(x: Int) = this + x.toBigInteger()

if you change

divisor += 2

to

divisor += BigInteger("2")

You can shorten

println("314 digits of Pi ${r[0]}.${r.substring(1).dropLast(5)}")

to

println("314 digits of Pi ${r[0]}.${r.substring(1,314)}")

Now, you can change the imports to

import java.math.*

You don't have to declare the type for val r.

The final code I came up with by doing that is:

import java.math.*
fun main(args: Array<String>) {
  val r = (acot(5).shl(2)-acot(239)).shl(2).toString()
  println("314 digits of Pi ${r[0]}.${r.substring(1,314)}")
}
fun acot(x:Int):BigInteger {
  var precision = BigInteger.TEN.pow(319)/x.toBigInteger()
  var total = precision
  var divisor = BigInteger.ONE;
  while(precision.abs() >= divisor) {
    precision = -precision/(x.toBigInteger().pow(2))
    divisor += BigInteger("2")
    total += precision / divisor
  }
  return total
}

I also came up with shorter code, with decreased width, by calculating a different way:

import java.math.*
fun main(args:Array<String>) {
  val b4 = BigDecimal(4)
  val r = ((atan(5)*b4-atan(239))*b4).toString()
  println("314 digits of Pi ${r.substring(0,315)}")
}
fun atan(xInv:Int):BigDecimal {
  var x = BigDecimal(1).divide(BigDecimal(xInv),330,3)
  var (numer, total) = arrayOf(x, x)
  for (i in 3..450 step 2) {
    numer = -numer * x * x
    total += numer / BigDecimal(i)
  }
  return total
}


Filter array elements using variable number of filters

What didn't work, is using arr = arr.filter... to iterate over the array passed into the function

It works. But you would then need to return arr instead of newArr. Also, it is less readable as you re-assign the function's return value to the input parameter, which is confusing.

Further suggested improvements:

Naming:

Rename newArr to e.g. result as this makes its role more clear.

Style:

Array.from(arguments).slice(1) creates an unnecessary internal copy. Use e.g. Array.prototype.slice.call(arguments, 1). Some people prefer [].slice.call(arguments, 1)
Don't make an unnecessary local copy of the arguments if performance
is key.
Since you already make a local copy, replace the for-loop with the functional style Array.includes for consistency's sake, since you already use Array.filter.
Having a function call within a loop body is slow as the function call overhead is not marginal in JavaScript.
Declare the loop iterator i as a local variable for (var i = ...

Applying those suggestions to your code gives us:

function destroyer(array) {
  var filter = Array.prototype.slice.call(arguments, 1);
  return array.filter(function(el) {
    return !filter.includes(el);
  });
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // [1, 1]
console.log(destroyer(["tree", "hamburger", 53], "tree", 53)) // ["hamburger"]

However, this function is inefficient for larger inputs as it iterates the filter array for each array element. It's time complexity is in O(mn) where m and n are the lengths of array and filter. You can improve on that by using a Set and come up with a linear time solution. Using rest parameters allows us to get rid of the argument slicing:

function destroyer(array, ...filter) {
  filter = new Set(filter);
  return array.filter(element => !filter.has(element));
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); // [1, 1]
console.log(destroyer(["tree", "hamburger", 53], "tree", 53)) // ["hamburger"]


Calculator that can add/subtract/divide/multiply two inputs

Immutable sequences
operators should be a tuple (i.e. ('+', ...)), since you don't change it.
Nested functions
instructions should be moved to the global level - you shouldn't need a closure, and should be passing information between instructions and run_calculator with parameters and return values, not closure variables.
Index-based selection
It's a little awkward to ask that the user select an operator based on numerical index. Make operators a dictionary instead, and have the user input the operator character. Of course, this is only possible if the parameters of your homework assignment permit.
Never except:
Seriously. except ValueError: instead. Otherwise, you'll catch exceptions you don't want to, including user-break Ctrl+C.
Parens
Python doesn't need parens here:
while (True):

so delete them.
Logic inversion
    if restart.lower() == 'y':
        continue
    else:
        print("Results:")
        for x in range(len(answers)):
            print(f"{answers[x]}")
        break

is more easily expressed as
    if restart.lower() != 'y':
        print("Results:")
        for x in range(len(answers)):
            print(f"{answers[x]}")
        break


Convert your test values where you need them

Your initial for loop only sets each "right / left" value to -1 if it is 0. This can be done in the reduce function itself. Also, your conditional p[c[1]] != undefined is unnecessary, as undefined evaluates to false, and there is no concern here about other "falsy" values such as zero.

Use Javascript's array methods

.some() can eliminate unnecessary for loops with conditionals in Javascript.
.values() lets you concisely iterate through values of an object.

Combined with the arrow operator =>, these can result in concise code that reads a little more like a natural sentence.

Applying both of the above points to your code:

shoes = [[0, 21],
         [1, 23],
         [1, 21],
         [0, 23]];

function pairOfShoes(shoes) {
    var p = shoes.reduce(function(p, c) {
        p[c[1]] = (p[c[1]] || 0) + (c[0]==1 ? 1 : -1);
        return p;
    }, {});
    if (Object.values(p).some(x => x != 0)) { return false }
    else { return true };
}

console.log(pairOfShoes(shoes));

[Edit: It might also be clearer to replace your reduce function with a `for' loop.]


Algorithm

This algorithm is already provided by the standard library.
std::random_shuffle()
If you want to implement it yourself then this is not very optimal (as @rolfl mentioned this is \$O(N^2)\$ at best). @rolfl suggests using Fisher-Yates I call it the Knuth shuffle but basically it is the same thing (and Knuth is a cooler name to throw around :-)

The Knuth shuffle is basically:

Pick a random value in your container. Swap it with the last element.
Reduce the size of the elements you consider for swapping by 1.
if size > 0 goto 1

Rand

The rand algorithm is known to be bad so consider using the new random number generators provided by the standard. If you want to stick to rand() then at least try and use it in a way that does not have bias (or worse bias).

index = rand()%size;

Does not give an even distribution (unless RAND_MAX % size == 0). If the modulus is not zero then a couple options have a slightly higher probability. The correct way to do it is:

// To make sure you have an even distribution you
// must discard all values that contribute to it being uneven.
// So first calculate the max value where we can evenly distribute
// input values [0..max)
//
// If rand() generates a value greater or equal to max then discard it
// as this is part of the unevenness. Otherwise do your modules and return.
int randEven(int max)
{
     maxRange = RAND_MAX / max * max; // Note division is integral
                                      // So result is not necessarily RAND_MAX
     for(;;)
     {
         int r = rand();
         if (r < maxRange)
         {    return r % max;
         }
     }
}

Interface

void shuffle(int array[], const int size);

This is a very C like interface. It also limits you to using C-Arrays (In C++ there are lots of container types). So I would change this to use iterators.

template<typename T>
void shuffle(T begin, T end);

You can still use the same function with your C array (as pointers implement the iterator interface).

shuffle(a, 7);

// becomes

shuffle(&a[0], &a[7]);

Code Review

Try to always use braces.

    for ( int i(0); i < size; ++i)
        temp[i] = array[i];

Its a good habit to get into as there are a few corner cases where it matters and if you just do it by habit you will not hit them.

    for ( int i(0); i < size; ++i) {
        temp[i] = array[i];
    }

Prefer to never use C cast style.

Use a C++ cast. They are easy to spot and the compiler can check most of them for correctness. The dangerous ones are then easy to find during code review.

    srand((unsigned int)time(NULL));

    // The C++ way.
    srand(static_cast<unsigned>(time(nullptr)));

    // Alternatively you can use the constructor syntax (not official name)
    // Personally don't like this.
    srand(unsigned(time(nullptr)));

If you are initializing arrays like this then don't specify a size:

    int a[7] = {1,2,3,4,5,6,7};

    //  Don't say seven
    int a[] = {1,2,3,4,5,6,7};

In this version the compiler calculates the correct size. If you had accidentally used an incorrect size then the compiler can generate incorrect code. If you had used 8 then the compiler fills the array with zeros. If the you had used 6 then you overrun the size of the array. So prefer to let the compiler work it out.

Prefer to use "\n" rather than std::endl. This is because std::endl adds '\n' and then flushes the stream. Unless you really want to flush the stream use "\n". You rarely want to do this as the streams will do it automatically when they fill up.

    std::cout << std::endl;


Well, here's some tips:

Never use for-in for arrays. for-in runs through the array properties.

var a = [1,2,3]
a.foo = 'bar'; // arrays are still objects
for(var i in a){console.log(i)} // will run over foo

forEach though native, but AFAIK is still slow compared to while and for. Some say it suffers the same overhead of calling a function (activation records, stack, scope lookup etc.)
Consider async instead. By the looks of it, you want to loop through an array as fast as possible to avoid freezing the browser. You can go with WebWorkers, or Timers. Here's an example using setInterval. It's not as fast as loops, but you won't be seeing those "Unresponsive script" and "He's dead Jim!" warnings:

var i = 1000000;
var looper = setInterval(function(){
  /* do something */

  if(!--i) clearInterval(looper);
},0);


Count the different positions reached in a cycle of permutations

Naming
The question starts off talking about N and K.  Your code begins with reading in z and d.  The question text is ready-made documentation for your code; use the same names for the variables!
n, k = map(int, input().split())
Guilty, I said N and K but used n and k.  PEP 8, the Style Guide for Python Code recommends using snake_case for variables.  So we should also change S and Flag to s and flag.
But ...  what is flag?  Obviously, it is a flag, but a flag for what?  Perhaps changed would be a better name; you are looping while a change was made in the previous iteration.
Similarly, S is your list of swaps.  Why not call it swaps?
Don't relookup values
Python is an interpreted language.  It doesn't do any data-flow analysis to determine if the value of an expression will be used again.  It can't, since the meaning of operations can be changed on the fly.
In the for i in S loop, how many times is i[0] and i[1] used?  Six times each.  Each time, the interpreter looks up the object stored in i, and calls the __getitem__ method to fetch the value.  Let's fix this by looking up the value only once, and storing the values in (say) p and q:
    for p, q is swaps:
        if p not in pos[permute[q - 1]]:
            changed = True
            pos[permute[q - 1]].append(p)
        ...

That is immediately clearer.  No extra [0] and [1] to confuse the issue.
Use O(1) lookups instead of O(K) searches
You're using if thing not in container: container.append(thing).  This is a lot like a set.  A set can only contain one instance of an item.  But unlike a list, if thing not in container is O(1) on a set, where as the with a list, the entire list has to be searched to ensure the thing is not inside the list.
Two simple changes.  First, instead of pos[i] = [i,] (the comma is actually unnecessary), initialize it with pos[i] = {i}.  Second, instead of .append(), use .add() to add the value to the set.
Note: sets are more complex than lists.  This may actually slow things down and use more memory, if the number of things in the containers is small.  The sets gain their speed advantage when they contain many elements.  So profile this change, especially using larger problem sets.
Explicit is better than implicit
swaps = []
for i in range(k):
  swaps.append(list(map(int, input().split())))

What happens if an input line has more than two numbers?  The input will be split into whole bunch of terms, each term will be mapped (converted) to an integer, and stored as a list inside the swaps list!
Oops.
If the program crashes, it will happen well after this point in the code.
It is better to crash early.  You expect exactly two values.  Be explicit.
swaps = []
for i in range(k):
  swaps.append(list(map(int, input().split(maxsplit=1))))

If given more than two numbers, say 12 23 34, then split will return "12" and "23 34", and int("23 34") will raise a ValueError.  The bug will be caught earlier.
Map the problem to Python, if possible
Python uses 0-based indexing.  The problem uses 1-based indexing.  You can get rid of the +1 in range statements, and -1 in the solution code by mapping the problem into a more Pythonic version.
For example, instead of swapping numbers at positions 1 and 3, we'll swap them at positions 0 and 2.  This just requires adjusting the swap positions as we read them in:
swaps = []
for i in range(k):
  p, q = map(int, input().split())
  swaps.append([p - 1, q - 1])

Note.  The explicit maxsplit=1 went away because we are assigned the result of map to a tuple of two variables, which requires exactly two values.  Explicit is better than implicit ... especially when the it can be expressed implicitly!
Reworked Code
n, k = map(int, input().split())

pos = {}
for i in range(n):
  pos[i] = {i}

permute = list(range(n))

swaps = []
for i in range(k):
  p, q = map(int, input().split())
  swaps.append([p - 1, q - 1])

changed = True

while changed:
  changed = False
  for p, q in swaps:
    if p not in pos[permute[q]]:
      changed = True
      pos[permute[q]].add(p)
    if q not in pos[permute[p]:
      changed = True
      pos[permute[p]].add(q)
    permute[p], permute[q] = permute[q], permute[p]

for i in pos:  # Note: relies on ordered dictionary
  print(len(pos[i]))

Algorithmic improvement
1 2 3 4 5
After one iteration of swaps, you end up with this:
2 4 3 1 5
We can see we have moved

1 -> 2, 2 -> 4, 4 -> 1.  (length 3)
3 -> 3
5 -> 5

The 1 visited locations 1, 3, 2 and 4.  The 2 visited locations 2, and 1.  The 4 visited locations 4 and 2.  On subsequent iterations, the 2 will have moved into the 1's starting position and will visit 1, 3, 2 and 4, and so on.  So we have 1, 2, and 4 all visiting locations 1, 2, and 3 and 4 ... for a total of 4 locations
3 will visit 3, 1, and 2 and return to 3.
5 stays at 5.
All that is required is one pass through the swaps array to determine which positions each starting point visits, and what ending position it will have.  From that, the "rings" can be determined.  All starting positions in each ring will visit all the locations visited by every position in the ring.
With only one pass through the swaps array required, we don't need to save the swaps into a swaps list; it can be processed on the fly.  This helps the solution stay within the memory constraint.
n, k = map(int, input().split())

pos = [{i} for i in range(n)]
permute = list(range(n))

# Perform swaps, recording which values appear in which positions
for _ in range(k):
    p, q = map(int, input().split())
    p -= 1
    q -= 1

    pos[permute[q]].add(p)
    pos[permute[p]].add(q)
    permute[p], permute[q] = permute[q], permute[p]

# Implementation of final steps left to student


Is it possible to DRY these 2 methods of a tailrec Node Tree?

I defined a Higher-Order function:

@tailrec
def foldAsc(op: Node => Node): Node = {
  op(this)       // <= still this statemnt when x=>x is useless..
  parent match {
    case None => this
    case Some(x) => x.foldAsc(op)
  }
}

def asc(): Node = foldAsc(x => x)

def ascVisited(deltaInc: Inc): Node = foldAsc { x =>
  visited += deltaInc
  x
}

It is not still optimal but DRYed out a little.


Binary operators should always be surrounded by whitespaces(it is inconsistent in your code: sometimes you do surround them, sometimes you don't). For example,

for (int j=0; j<a.length; j++)

should be

for (int j = 0; j < a.length; j++)

There should be one whitespace before an opening bracket. Again, there is an inconsistency in your code: a whitspace is present most of the time, but it is not present, for instance, here:  if(hi <= lo){. Not following established style guidelines is not good, having inconsistencies is definitely bad.
A little bit about blank lines: they should be present between different methods and it is fine to have them inside one method if it is really big and you need to separate logical blocks from each other(however, too long methods should be avoided). But having a blank line after each statement is pointless and it makes your code less readable.

private static void sort(Object[] a, int lo, int hi) {
    if(hi <= lo) {
        return;
    }
    int mid = lo + (hi - lo) / 2;
    sort(a, lo, mid); // sort left part
    sort(a, mid + 1, hi); // sort right part
    merge(a, lo, mid, hi);
}

looks better than:

private static void sort(Object[] a, int lo, int hi) {

    if(hi <= lo){

        return;

    }

    int mid = lo + (hi - lo)/2;

    sort(a, lo, mid);// sort left part

    sort(a, mid+1, hi); // sort right part

    merge(a, lo, mid, hi);

}

Variable naming. There is no need to shorten words: you code will become more readable if you use names like low and high instead of lo and hi.
It is conventional to declare one variable at a time. I would use

int i = lo;
int j = mid + 1;

instead of int i = lo, j = mid+1;. And again, i and j are not the best names for variables because they are not descriptive(but it can be ok if their scope is very narrow, so it is not a very big issue in this case).
It is a good practice to write comments for each public method to describe what it does, what do its parameters stand for, what pre- and post-conditions are guaranteed, what exceptions can be thrown, is it thread-safe or not and so in. You should write comments for all public classes, too.


JavaScript code for countdown function is maxing CPU usage

First, I'll get to the fix for your problem.  The problem is more in the CSS than in your JavaScript.  Because you are updating the graph every second, that area of the page has to be repainted each time.  Due to the way browsers handles these things by default, it has to also check the surrounding area to see if it now needs to be changed as well.  So the idea is to minimize this.  And the simplest way to do this is to add the following lines into your CSS:
.chart {
  transform: translateZ(0);
  z-index:1;
  /* future proofing */
  will-change: transform;
}

What this code does is move the charts onto there own rendering layer. This prevents the browser from having to check the surrounding areas because each chart is now separated from the rest of the content.  In Chrome, you can see the performance difference this makes by watching the Timeline in the Dev tools.  In the original, it spends ~180 ms repainting the screen and ~100 ms performing calculations.  In the updated version, it spends ~20 ms for each.  Add this over four graphs and you can see why the cpu is pegged.  The will-change is a new CSS property that will basically do the same thing as the two lines above in the somewhat-near-future.  I have updated the fiddle with just this change and you can see the difference.
Now, the code review:
As always, the first thing I recommend is to remove your code from the global scope.  The easiest way to do this is to use an IIFE.  This will basically create a private scope for all your code which reduces the amount of code you place in the global scope, which in turn, reduces the chance of collisions with other peoples code.  Since you are using jQuery, this also provides a way to make sure $ always points to it.
(function( $, window, document, undefined ) {
  //your code here
})( jQuery, window, document );

So in the above statement, we are passing jQuery as $, as well as the window and document objects (for a slight performance boost) and, to deal with older browsers, making sure undefined is actually undefined.
The next thing you could do is cache your jQuery selectors.  This will improve the overall performance because selecting an element in the DOM is one of jQuery's slowest performing functions.  Your are using ID's which help but caching them is even quicker.  We want to do this as soon as the DOM is ready.  I usually create a single function for everything that has to happen there and then call the single function.  Also, since we will be referring to these selectors we will declare them immediately inside of our IIFE. I have also included the reference to create the piecharts:
(function( $, window, document, undefined ) {

  var $days, $daysText, $hours, $hoursText,
      $minutes, $minutesText, $seconds, $secondsText;

  function init() {

    var options = {
      scaleColor: false,
      trackColor: 'rgba(255,255,255,0.3)',
      barColor: '#E7F7F5',
      lineWidth: 6,
      lineCap: 'butt',
      size: 95
    };

    getSelections();

    $days.easyPieChart( options );
    $hours.easyPieChart( options );
    $minutes.easyPieChart( options );
    $seconds.easyPieChart( options );

  }

  function getSelections() {

    $days = $('#days'),
    $daysText = $days.find('span'),
    $hours = $('#hours'),
    $hoursText = $hours.find('span'),
    $minutes = $('#minutes'),
    $minutesText = $minutes.find('span'),
    $seconds= $('#seconds'),
    $secondsText = $seconds.find('span');

  }

  $(function() {   //shortcut for document.ready event
    init();
  });

})( jQuery, window, document );

One other big change you need to make is to not update all four pie charts every second.  There is only one chart that needs updating that often (seconds obviously).  You should only update the minutes chart every minute, the hour every hour and the days every day.  That way, on almost every interaction you are only updating the one chart.
Another way you could improve this code is to DRY it out a bit.  One place that would greatly benefit from this is the display function.  We need to make changes here anyway to help out with the problem mentioned above.
Let's take this code:
days_rem = ("00"+days).slice(-sl);
hrs_rem = ("0"+hours).slice(-2);
min_rem = ("0"+minutes).slice(-2);
sec_rem = ("0"+sec).slice(-2);
$("#days span").text(days_rem);
$("#hours span").text(hrs_rem);
$("#minutes span").text(min_rem);
$("#seconds span").text(sec_rem);

Notice how that is pretty much the same thing repeated over and over?  That means it needs to be it's own function:
updateText( $daysText, days );
updateText( $hoursText, hours );
updateText( $minutesText, minutes );
updateText( $secondsText, seconds );

function updateText( $el, val) {
  var len = val.length;
  val = ( len === 1 ) ? '0'+val : val;
  $el.text( val );
}

With this function, val will always be at least 2 characters long.
Now before updating the charts, check to see what are current value is.  If it's the same as the new value (which will be typical for minutes, hours, days), then there is no reason to update them (or there text for that matter). Adding a data element with jQuery is a great way to keep track of this.
if ( $days.data('remaining') !== days_rem) {
  // update it
  updateText( $daysText, days );
  $days.data('remaining', days_rem);
  $days.data('easyPieChart').update( ( 100 / tot_days) * days_rem );
}

The first time through, the remaining data element is not set so it will update the chart.  Each other time through, it will check that existing value and only update the chart when the value actually changes.  Once the code is added for each chart, it becomes obvious that this can be DRY-ed out as well. Maybe with something like this:
updateChart( $days, $daysText, days_rem, ( 100 / tot_days ) * days_rem );
function updateChart( $chart, $chartText, newValue, formula ) {
  //code here
}

I will leave that code up to you.
At this point, you should see a noticeable increase in the performance of the page.
Some other things to consider:
In your calculate function you have a bunch of Magic Numbers such as 86400. Although this is fairly straight forward when you know what you are looking at, it might be easier to set up some variables to hold those that provide some explanation for them:
var SECONDS_IN_A_DAY = 86400;
days = parseInt( remaining / SECONDS_IN_A_DAY , 10 );

Also notice, the radix parameter for the parseInt function.  It isn't required but it's one of those things you should use anyway.  That way the parser doesn't take the extra time to figure this out on it's own.
I hope that helps! Feel free to post any comments or questions.
Updates based on comments/fiddle
I have created a fiddle with all of the updated code, including some of the things you were trying to do on your own fiddle.  To show you the performance improvements, I created a couple of screen captures.  Note these are both showing when the seconds chart goes from 1 to 59.
This first one is your original fiddle linked in your post.
Performance Before
This is the updated fiddle I linked to above.
Performance After
By reducing the number of times each of the charts have to update and using the CSS above, you can see the execution time has improved significantly.  These samples were taken with Chrome dev tools.  If you are seeing significant CPU thrashing, try running in an incognito window to see if it is something else (tab or extention) interfering with your performance.


Fun crypto problem: Exploiting a vulnerable encryption scheme with Python

The conversions to bit-strings, then ints and back to strings are unnecessary.  m and k are bytes, so the elements (e.g., m[0] or k[i]) are already integers in the range 0-255;  bitwise operators can be applied to the elements directly.

I think routines in the Crypto library return strings, so the encrypt() return value might need to be encoded before using it.

from Crypto.Cipher import DES

m = b'secret!!'
k = b'qwerty!!'
E = DES.new(k, DES.MODE_ECB)
C = E.encrypt(m)

C = C.encode()  # <- needed if encrypt() returns a string (i.e., not bytes)

C_alpha = bytes(x^y for x,y in zip(C, m))

C_beta  = bytes(x^0xff for x in C)

C_omega = C_alpha + C_beta


Print total number of vowel and consonant in an entered sentence

Some thoughts:

choose good names

counter is IMO a bit "generic". Perhaps something more expressive like count_vowels_consonants?

Moreover, the inner function's parameter is named count, but it's actually not some count (number) but a text string.

Furthermore you're using the term "sentence", but you're not actually requiring sentences, but rather character sequences / strings.

don't call the function twice

find_total(count_sentence)
vowel_total = find_total(count_sentence)

Here you call find_total, discard its result (return value) and then call it again, this time assigning the result to the local variable.

separate calculation and output

Instead of

print("Vowel: {0}, Consonant: {1}".format(vowel_total, consonant_total))
return

leave out the print and return the values in a tuple

return (vowel_total, consonant_total)

On the caller side, you can then either use the returned tuple as it is

t = count ("foo bar")

or for example use tuple unpacking to obtain the individual counts

vowels, consonants = count ("foo bar")

only iterate once over the characters

Instead of first going one time over the characters to filter out non alphabetic characters and adjust the case of the alphabetic ones and then a second time to count, do it in one loop:

def count_vowels_consonants(text):
  vowels_list = ['A', 'E', 'I', 'O', 'U']
  consonants = 0
  vowels = 0
  for character in text:
    if character.isalpha():
      if character.upper() in vowels_list:
        vowels += 1
      else:
        consonants += 1
  return (vowels, consonants)

test corner cases

Does your function work well with an empty string? A string with only vowels or consonants? A string with only punctuation?


Repository Pattern universal application

What we are looking at is a long tutorial on Inversion of Control and dependency injection. Basically at the most simpilest form you will be looking to abstract your data layer from you application layer and provide interfaces for your IoC container to deliver to the application.

This can get quite confusing however all we have to do is remeber our application will be using the interfaces to work with the data layer and not the actual implementation.

So for your Unit of work you would resolve IUnityOfWork interface instead. Now here is a quick example I put together. It is by no means a finished or tested product (and the xml side is very fragile) but shows how this can work.

First off I am using the interface IRepository<T> to access the data layer. This can be connected database through EntityFramework or Xml through serialization. This repository is simple.

public partial interface IRepository<T>
    where T : BaseEntity
{
    T GetById(int id);

    T Insert(T item);

    T Update(T item);

    void Delete(T item);

    IQueryable<T> Entities { get; }
}

As simple interface the has the standard insert\update\delete and queryable methods. It is worth noting that I am referencing BaseEntity which is a simple entity with an public int Id { get; set; } property.

Now for Database connections I have created an implementation called EfRepository<T>

public class EfRepository<T> : IRepository<T>
    where T : BaseEntity
{

    public EfRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        _dbContext = dbContext;
    }

    readonly DbContext _dbContext;
    DbSet<T> _entities;

    /// <summary>
    /// Gets the entities as a querably
    /// </summary>
    public IQueryable<T> Entities { get { return DbEntities; } }

    protected virtual DbSet<T> DbEntities { get { return _entities ?? (_entities = _dbContext.Set<T>()); } }

    public void Delete(T item)
    {
        DbEntities.Remove(item);

        _dbContext.SaveChanges();
    }

    public T GetById(int id)
    {
        return DbEntities.Find(id);
    }

    public T Insert(T item)
    {
        DbEntities.Add(item);
        _dbContext.SaveChanges();
        return item;
    }

    public T Update(T item)
    {
        _dbContext.SaveChanges();
        return item;
    }
}

Now this is a very simple class that connects to my Data layer via entity framework. (We will talk about the constructor shortly).

Next I have an Xml Repository named XmlRepository<T>

public class XmlRepository<T> : IRepository<T>
    where T : BaseEntity
{
    public XmlRepository(XmlContext xmlContext)
    {
        _xmlContext = xmlContext;
    }

    readonly XmlContext _xmlContext;
    IList<T> _entities;

    public IQueryable<T> Entities
    {
        get
        {
            return XmlEntities.AsQueryable();
        }
    }

    protected IList<T> XmlEntities
    {
        get
        {
            return _entities ?? (_entities = _xmlContext.Set<T>());
        }
    }

    public void Delete(T item)
    {
        if (XmlEntities.Any(i => i.Id == item.Id))
        {
            XmlEntities.Remove(item);
            _xmlContext.SaveChanges(XmlEntities);
        }
    }

    public T GetById(int id)
    {
        return Entities.FirstOrDefault(x => x.Id == id);
    }

    public T Insert(T item)
    {
        if (item.Id == default(int)) //only add if id = default(int)
        {
            var lastEntity = Entities.LastOrDefault();
            if (lastEntity != null)
                item.Id = lastEntity.Id + 1;
            else
                item.Id = 1;

            XmlEntities.Add(item);
            _xmlContext.SaveChanges(XmlEntities);
        }
        return item;
    }

    public T Update(T item)
    {
        _xmlContext.SaveChanges((IList<T>)Entities);
        return item;
    }
}

Again really simple implementation and also has another constructor reference (XmlContext).

We will get to resolution and setup of Unity shortly but given this we now have a two generic data access repositories. One for EntityFramework and one for Xml File Store.

Now back to the EfRepository it has a constructor parameter DbContext dbContext this is required as we need access to the underlying data context and connections. Now this is actually an injected class of type EfDataContext which has an initializer and a few overloads (plus dependency injection).

public class EfDataContext : DbContext
{
    public static void Initialize()
    {
        var connectionFactory = new SqlConnectionFactory();
#pragma warning disable CS0618
        Database.DefaultConnectionFactory = connectionFactory;
#pragma warning restore CS0618
    }

    public EfDataContext(ApplicationSettings applicationSettings)
        : base(applicationSettings.DataConnectionString)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new TestEntityMap());
        base.OnModelCreating(modelBuilder);
    }
}

The class above is really used to override the OnModelCreating method to add my Fluent configurations for entity mapping (out of scope here) and to Initialize my connection Factory. You will also note the ApplicationSettings constructor parameter.

Now for the XmlRepository has its own context that is used to load the xml files and save the entities to xml files. This is a very basic (not thread safe) example.

public partial class XmlContext
{
    public XmlContext(ApplicationSettings appSettings)
    {
        _xmlFileLocation = appSettings.DataConnectionString;
    }

    readonly string _xmlFileLocation;

    public void SaveChanges<T>(IList<T> entities)
        where T : BaseEntity
    {
        if (entities == null)
            return;

        string filePath = Path.Combine(_xmlFileLocation, $"{typeof(T).Name}.xml");
        using (var writer = new StreamWriter(filePath))
        {
            var serializer = new XmlSerializer(typeof(List<T>));
            serializer.Serialize(writer, entities);
            writer.Flush();
        }
    }

    public IList<T> Set<T>()
        where T : BaseEntity
    {
        string filePath = Path.Combine(_xmlFileLocation, $"{typeof(T).Name}.xml");
        IList<T> entities = new List<T>();
        if (File.Exists(filePath))
        {
            //XDocument doc = XDocument.Load(filePath);
            using (var stream = File.OpenRead(filePath))
            {
                var serializer = new XmlSerializer(typeof(List<T>));
                entities = serializer.Deserialize(stream) as List<T>;
            }
        }
        return entities.OrderBy(e => e.Id).ToList();
    }
}

This simple class uses the built in XmlSerializer to read\save files to disk by naming the files {Type.Name}.xml. You will also notice it has the ApplicationSettings constructor parameter.

So far we have setup our Contexts and Repositories for access both connected databases (via EntityFramework) and Xml file storage. The next step is to put it together and register everything in our Unity container. This is where the application settings come in handy.

public class ApplicationSettings
{
    [JsonProperty("dataProvider")]
    public DataProviderType DataProvider { get; set; }

    [JsonProperty("dataConnectionString")]
    public string DataConnectionString { get; set; }
}

public enum DataProviderType
{
    SqlServer,
    XmlFileStore
}

This is a simple Json text file that we can parse and load our settings (however I just did it manually in the example). Your implementation can be done any way. The important thing to note for the DataProvider.SqlServer the DataConnectionString is the database connection string and DataProvider.XmlFileStore is the root location to store the xml files.

static void Main(string[] args)
{
    var appSettings = new ApplicationSettings
    {
        DataConnectionString = @"D:\xmltest\",
        DataProvider = DataProviderType.XmlFileStore
    };

    RegisterContainer(appSettings);

    var repo = _container.Resolve<IRepository<TestEntity>>();
    var entity = new TestEntity
    {
        EntityName = "Hello Stack Oveflow"
    };

    repo.Insert(entity);
}

static UnityContainer _container;

public static void RegisterContainer(ApplicationSettings settings)
{
    _container = new UnityContainer();

    _container.RegisterInstance(settings);

    switch (settings.DataProvider)
    {
        case DataProviderType.SqlServer:
            EfDataContext.Initialize();
            _container.RegisterType<DbContext, EfDataContext>();
            _container.RegisterType(typeof(IRepository<>), typeof(EfRepository<>));

            break;

        case DataProviderType.XmlFileStore:
            _container.RegisterType<XmlContext>();
            _container.RegisterType(typeof(IRepository<>), typeof(XmlRepository<>));
            break;

        default:
            throw new Exception($"The DataProvider Type {settings.DataProvider} is unknown");
    }
}

Now the fun begins. Basically at this point we know our data access will be through the use of the generic interface IRepository<T>. We will use our ApplicationSettings class to dicate the provider and the connection string. From here we adapt our Unity Registration methods to register one instance of the other.

To walk through the RegisterContainer method we simply pass in the instance of the ApplicationSettings. We then register the instance of the ApplicationSettings (essentially a singleton). Next we then determine which type of provider we are going to load.

If the type is DataProvider.SqlServer we simply setup the EfDataContext with the Initialize() method and then register the DbContext dependency as EfDataContext (which requires the ApplicationSettings dependency already registered. Next we register the IRepository<T> dependency as EfRepository<T>. Where EfRepository<T> has the dependency DbContext which has been registered as EfDataContext.

Alternativly for the DataProvider.XmlFileStore type we register the dependency type XmlContext and then register the IRepository<T> dependency as XmlRepository<T>. Where XmlRepository<T> has the XmlContext dependency registered earlier.

Now that we have gotten this far we can answer the question. Finally moving back up to the Main method we can now call _container.Resolve<IRepository<TestEntity>>() which regardless of our data storage type gives us the same common interface.

Back to the original question

  Currently this model is communicating with the database, but if I
  wanted (for whatever reason) to change this model to save data in the
  XML file, I would have to completely rewrite all my Repository
  classes? Or am I missing something here?

Following the strategy above and leveraging your IoC container all you need to rewrite is your IRepository<T> implementation to your different storage type. For example you could easily write a JSON serializer similar to the XmlRepository<T> and XmlContext. You could change your EfRepository<T> to directly call sql queries.


Interesting question,

You have a ton of repeating code, so don't hesitate to write more helper functions so that this:

genericLogger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: './log/error.log' })
    ]
});

dbLogger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: './log/db.log' })
    ]
});

viewLogger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: './log/view.log' })
    ]
});

networkLogger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: './log/network.log' })
    ]
});

could be:

function createLogger( filename ){
  return new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: filename })
    ]
  });
}
genericLogger  = createLogger( './log/error.log' );
dbLogger       = createLogger( './log/db.log' );
viewLogger     = createLogger( './log/view.log' );
networkLogger  = createLogger( './log/network.log' );

I did not test this code, but you get the gist.

Furthermore, in this code, I have no idea what t and n are:

Logger.db = function(t, n) {
    if(n) {
        dbLogger.log(t, n);
    } else {
        dbLogger.info(t);
    }
};

Logger.view = function(t, n) {
    if(n) {
        viewLogger.log(t, n);
    } else {
        viewLogger.info(t);
    }
};

Here as well, you could use a helper function:

Logger.loggerHelper = function( o , t , n ){
  if(n){
    o.log(t,n)
  } else {
    o.log(t)
  }
}

Logger.db = function(t, n) {
  loggerHelper( dbLogger , t , n );
};

Logger.view = function(t, n) {
  loggerHelper( viewLogger , t , n );
};

After a while I would get irritated by the above as well, and write something like this:

var winston = require('winston');

var Logger = {};
var loggers = {
  generic : './log/error.log',
  db : './log/db.log',
  view : './log/view.log',
  network : './log/network.log'
};

for( logger in loggers){

  Logger['_' + logger] =  new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: loggers[logger] })
    ]
  });

  Logger[logger] = function(t,n ){
    if(n) {
        Logger['_' + logger].log(t, n);
    } else {
        Logger['_' + logger].info(t);
    }
  }

}

Logger.error = function(n) {
  Logger['_generic'].log('error', n);
};

Logger.info = function(n) {
  Logger['_generic'].log('info', n);
};

module.exports = Logger;

loggers contains the link between the method and the file name, so it becomes now very easy to add/remove/change loggers. This approach does expose a lot more (all) the functionality in Logger, but I think that would work out.


I found out that using Data.ByteString.Lazy.Char8 could significantly improve the running time (about one third of the one I posted initially).

Here is the code, taking into account some suggestions by Gurkenglas:

import qualified Data.ByteString.Lazy.Char8 as C

-- Define type synonyms for fields in a fastq record.
type Name = C.ByteString
type Nucleotides = C.ByteString
type Qualities = C.ByteString

data Fastq = Fastq Name Nucleotides Qualities

formatFastq :: Fastq -> C.ByteString
formatFastq (Fastq n s q) = C.unlines [n, s, C.pack "+", q]

-- Parse lines four by four, ignore the third of each batch.
getFastqs :: [C.ByteString] -> [Fastq]
getFastqs [] = []
getFastqs (l1 : l2 : _ : l4 : ls) = Fastq l1 l2 l4 : getFastqs ls

{-
We assume that the records come in sorted by sequence.
Successive records having the same sequence are fused,
arbitrarilly keeping the first name, and taking the
highest quality at each position.
-}
fuseFastqs :: [Fastq] -> [Fastq]
fuseFastqs [] = []
fuseFastqs [r] = [r]
fuseFastqs (r1@(Fastq n s1 q1) : r2@(Fastq _ s2 q2) : rs)
    | s1 == s2 = fuseFastqs (Fastq n s1 (bestquals q1 q2) : rs)
    | otherwise = r1 : fuseFastqs (r2 : rs)

{-
For each position, we want to keep the highest quality
among the records that had the same sequence.
In fastq format, qualities are integers represented as ascii characters
Using max on Char does what we want, and seems to work on Bytestring elements.
-}
bestquals :: Qualities -> Qualities -> Qualities
bestquals q1 q2 = C.pack (C.zipWith max q1 q2)

processLines :: [C.ByteString] -> [C.ByteString]
processLines ls = map formatFastq (fuseFastqs (getFastqs ls))

main :: IO ()
main = C.interact (C.concat . processLines . C.lines)

It would be nice to be able to avoid the ugly C.pack in bestquals.


First of all,you declare them without anything,so it's probably declared globally,this is not good,with this amount of variables in global.

Second of all,ES6 Destructuring assignment

var arr=[1,2,3,4,5];
var [a,b,c,d,e]=arr;
console.log(a,b,c,d,e); // 1,2,3,4,5

Using the same way,

for (grid in obj.Grid) {
    var i=obj.Grid[grid][0];
    var [unused,labels[i], utterances[i], links[i], icons[i], colours[i], slide_number[i]]
    =obj.Grid[grid]
    //....
}


Unit testing async functions in node/express

Is it a bad practice to insist functions return a value, which isn't required, simply to make testing easier? Are there any side effects of this?

I wouldn't say it's bad practise, having to provide anchors for test purposes isn't uncommon. Side affects would really boil down to how & where it's being used, in this case it looks very much like Express middleware and nowhere in the docs does it mention any rules about not returning values. Furthermore, if you dig into the source you'll find that middleware return values are ignored.

I think in your case returning a Promise from the middleware is the ideal solution.


Do not use using namespace std in global scope.
Never use global variables.  Right away, this will introduce all sorts of problems, including maintainability and bugs.  There are different alternatives to this, one being a struct:

Such a structure just needs the month, day, and year:

struct Date
{
    int month;
    int day;
    int year;
};

Initialize the two Date instances:

// same order as appears in struct
Date date1 = {1, 2, 2000};
Date date2 = {4, 5, 2001};

Access the structures and set the data members (with your code):

std::cout << "Enter first date: ";
std::cin >> date1.year >> date1.month >> date1.day;
std::cout << "Enter second date: ";
std::cin >> date2.year >> date2.month >> date2.day;

If you want to get into encapsulation/information-hiding, I'd recommend a class instead.  If you want to keep this simpler than a struct, just move the globals into main() (but use the variables from my example).  You could also create more specialized functions, thereby not just working in main().  Modularity will help keep your code more organized and maintainable.
I don't like int for these values (dates cannot be negative).  I'd go with std::size_t instead (include <cstddef> to use it).
month_days[] should be a const while in global scope.  As a constant, it can remain there because it cannot be changed by anything else.  However, this will prevent you from accounting for leap-years.  Speaking of which...
To account for leap-years, I'd either:

leave out February's value from the array (it's the only value that could change)
not make the array a constant (the program will handle the values during runtime)

With that, you can allow the program to adjust February's value if a leap-year.


Your array set could be written as *(array + index) = value; and your array get could be written as return *(array + index);.

array[index] could also be written as *(array + index). Those two functions don't do anything you can't already do with [].


int diff = guessNum - randomNum;
    if (guessNum >= randomNum) {
      System.out.println(diff);
    } else { System.out.println(randomNum - guessNum); }

You mix styles here.  Consider

    if (guessNum >= randomNum) { System.out.println(guessNum - randomNum); }
    else { System.out.println(randomNum - guessNum); }

That's a distinct style.  It puts the {} on the same line as the contained statement and it does every calculation just when it is needed.  Most importantly it's consistent.

I don't like that style.  It's especially uncommon.  I'd prefer

    int difference = guess - solution;
    if (difference >= 0) {
        System.out.println(difference + " high.");
    } else {
        System.out.println(-difference + " low.");
    }

We only calculate the difference once.  Then we use it three times.

This uses a four-column indent, which is standard in Java.

This puts {} on the same lines as their control structures when possible.  And it puts the enclosed statements on lines of their own.  Also standard in Java.

I changed the names of the variables to concentrate on their role in the program.  Not characteristics of how they are defined, e.g. randomly or numeric.  This leaves us with more flexibility to change in the future.  For example, this version could be easily modified to guess letters.

If you don't like the high/low, you could just say

    System.out.println(Math.abs(guessNum - randomNum));

No intermediate variables or if/else that way.


All this nesting obfuscates your code pretty badly, so let's start by reducing it so it's easier to read. If you need to test something in your for loop, you should flip the test and use continue, like this:

    for line in in_file:
        if not string in line:
            continue
        En = line.split().pop(4)

This saves you one block of nesting at least. You could also combine your two range calls with itertools.product. product performs a nested loop based on the two iterables it's passed. It essentially creates the exact nested loop you have with just one line:

for i, j in itertools.product(range(-index,index+1), range(-index,index+1)):
    for line in in_file:
        if not string in line:
            continue
        En = line.split().pop(4)
        for line in in_file:
            current_line += 1
            if current_line == 2*(n+1)+2:
                x = line.split().pop(10)
            elif current_line == 3*(n+1)+2:
                y = line.split().pop(10)
            elif current_line == 4*(n+1)+2:
                z = line.split().pop(10)
                current_line = 0
                break
        print i, j, En, x, y, z
        data = "%d %d %s %s %s %s\n" % (i,j,En,x,y,z)
        out_file.write(data)
        break

It's certainly more readable now. Though still confusing, why are you looping over in_file within the in_file nested group? It seems redundant but also I think you have misunderstood how file reading works. When you have read the first ten lines of a file object and then start a new loop over that same object you wont re-read the first ten lines. This means there's no reason to nest your inner for loop like this. This will iterate over the same values:

for i, j in itertools.product(range(-index,index+1), range(-index,index+1)):
    for line in in_file:
        if not string in line:
            continue
        En = line.split().pop(4)
    for line in in_file:
        current_line += 1

Now about that current_line, you actually don't need to use that, you could use enumerate instead to automatically count the iteration you're on. enumerate takes an iterable and returns both the value, ie. line but also a number which you can use to replace current_line. enumerate usually starts counting from 0, but you can pass an optional starting parameter:

    for current_line, line in enumerate(in_file, 1):

I think current_line is a confusing name especially now that it's next to line. index or i are what I'd use, personally.

Also you're creating the same string twice, once to print and once to write. Just create data upfront so you can print the same value, this will avoid confusion with typo discrepancies between the two. You can manually add the newline in the write call instead. You should also use the new way of formatting, str.format, as it's type agnostic:

        data = "{} {} {} {} {}".format(i, j, En, x, y, z)
        print (data)
        out_file.write(data + '\n')

Now let's see how this looks with these changes:

for i, j in itertools.product(range(-index,index+1), range(-index,index+1)):
    for line in in_file:
        if not string in line:
            continue
        En = line.split().pop(4)
        break
    for idx, line in enumerate(in_file, 1):
        if idx == 2*(n+1)+2:
            x = line.split().pop(10)
        elif idx == 3*(n+1)+2:
            y = line.split().pop(10)
        elif idx == 4*(n+1)+2:
            z = line.split().pop(10)
            break

    data = "{} {} {} {} {}".format(i, j, En, x, y, z)
    print (data)
    out_file.write(data + '\n')

Now, a note about using open for your files. It's actually better to use with because it will always ensure your files are closed no matter what, even if error's occur during your script. It will unfortunately reintroduce nesting, but it it is worth it.

with open("file.txt") as in_file, open("out.txt", "w") as out_file:
    for i, j in itertools.product(range(-index,index+1), range(-index,index+1)):

Your names could definitely use work too. x, y and z don't mean anything to me. What is n? Is it a constant? Does it change? string is likewise vague, something like key would make more sense. index is confusing too, as it's only for specificying the range you loop over. Would boundary work perhaps? The problem is, your names are so vague I can't even suggest better ones because I don't know what these things do.

Also you should match Python naming conventions. You use snake_case for current_line which is good, but En looks like a class due to the capital. It should just be en, or better yet a descriptive name. Even i and j would benefit from descriptive names if it was possible.


In your ListNode::toString() the use of StringBuilder is useless overhead as you just append one single string. You could strip it down method to just this:

public String toString() {
    if (this.value == null) { // beware of null!
        return "null";
    }
    return this.value.toString();
}

In your List::add(T) method you should throw an Exception (maybe an ArrayIndexOutOfBoundsException with a proper message) if the list is full (if(listSize == initialCapacity) {) instead of writing a note to System.out. Otherwise the calling code of your implementation wouldn't notice the problem. See Fail Fast Principle.
In your add(T) method, why are there two different paths for the first and the other items, when the do exactly the same?
Is it by intention, that you reduce the intial/maximum size of your internal array in the remove(ListNode<T> toBeRemoved, int index) method?

node = new ListNode[--initialCapacity];  // << newSize = initialCapacity -1

It seems a bit strange to me.

In your remove methods you use initialCapacity where you rather should use listSize (except from the line mentioned in 4a).
Within the remove you could reuse the add method. I would refactor it to something like this:

public boolean remove(T value) {
    boolean result = false;
    for(int i = 0; i < listSize; ++i) { // note: only check elements added
        if(node[i].getValue() == value) {
            result =  remove(node[i], i);
            if(result) {
                listSize--;
            }
            // break; // note: exit loop if you only want to remove first occurence.
        }
    }
    return result;
}

private boolean remove(ListNode<T> toBeRemoved, int deleteIdx) {
    if(deleteIdx < 0 || deleteIdx >= listSize) { // note: if no element -> exit
        return false;
    }

    if(listSize > 1) { // note: listSize relevant here
        ListNode<T>[] oldNode = node;

        node = new ListNode[initialCapacity]; // note: same size here
        int sourceIdx = 0;
        for(int targetIdx = 0; targetIdx < listSize; targetIdx++) {
            if (targetIdx == deleteIdx) {
                sourceIdx++; // skip deleted element
            }
            node[targetIdx] = oldNode[sourceIdx++];
        }
    }
    else {
        this.clear();
    }
    return true;
}


Retrieving album artist info from third party API

Some pointers:

Move $http.get out of the controller to a service. Stuff that is not presentation logic should not be in your controller.
getAlbums should probably be a method of the controller and not the $scope , see this video on egghead.io on how to use controller as syntax.
I don't really see the point in your ng-if="albums.length > 0". Why is it there?
It's common practice to postfix your controllers - so AlbumController or AlbumCtrl are more common names. I usually try to stick to conventions like this to convey intent more clearly.
If you're considering minification - consider using the minification syntax - start by reading this.


Currently you do not search sub nodes it a matching parent is found. This code fixes that problem and also simplifies the code by removing the unnecessary SearchChildNodes function. If you only care about the first match use var node = FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text).FirstOrDefault();

private IEnumerable<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{
    foreach (TreeNode node in nodes)
    {
        if (node.Value.IndexOf(searchstring,
              StringComparison.CurrentCultureIgnoreCase) >= 0)
            yield return node;
        else
        {
            foreach (var subNode in FindNodeByValue(node.ChildNodes, searchstring))
                yield return subNode;
        }
    }
}


Zero-initializing large dynamically allocated arrays of double

So my first hunch when I read your question is:

Okay this guy is making a complicated solution to a simple problem based on a hunch that the trivial solution is "grossly inefficient" without any measurements to back up said claim. I suspect OPs solution is slower than the trivial solution.

So I set out test this, I pit your fancy implementation against my trivial implementation:
double * calloc_d2(size_t nmemb){
    double* ret = malloc(sizeof(double)*nmemb);
    double* end = ret + nmemb;

    if(ret){
        double* i = ret;
        while(i != end){
            *i = 0.0;
            ++i;
        }
    }
    return ret;
}

I tested this here on ideone.com (I think it is using clang) which shows that this simple bit of code is consistently around 3-5% faster than your fancy code.
So I have two pieces of advice

Express your intent as clearly as possible, and let the compiler worry about generating high performance code. Compilers are pretty smart...
Always, always, always measure.

Addendum/Edit
Seeing as this answer has gotten quite some attention I've gone ahead and dug deeper.
Using godbolt compiler explorer I compiled (-O3) and disassembled my trivial loop implementation.
Here is the disassembly on GCC 6.2:
calloc_d2(unsigned long):
        push    rbp
        push    rbx
        lea     rbx, [0+rdi*8]
        sub     rsp, 8
        mov     rdi, rbx
        call    malloc
        test    rax, rax
        mov     rbp, rax
        je      .L1
        lea     rax, [rax+rbx]
        cmp     rbp, rax
        je      .L1
        mov     rdx, rbx
        xor     esi, esi
        mov     rdi, rbp
        call    memset
.L1:
        add     rsp, 8
        mov     rax, rbp
        pop     rbx
        pop     rbp
        ret

Notice how the compiler has just gone "Oh, you want to zero that? Cool, I'll just replace your code with a memset". This goes to show that an optimising compiler is quite smart and is able to transform your code in astounding ways.
I also tried different versions of GCC and clang on ARM and MIPS and PowerPC, they all generate similar instructions which essentially boil down to call malloc then memset.
With the sole exception of ICC 17 (-O3 -march=native) which goes above and beyond:
calloc_d2(unsigned long):
        push      rbp                                           #5.1
        mov       rbp, rsp                                      #5.1
        and       rsp, -32                                      #5.1
        push      r15                                           #5.1
        push      rbx                                           #5.1
        sub       rsp, 16                                       #5.1
        mov       rbx, rdi                                      #5.1
        lea       rdi, QWORD PTR [rbx*8]                        #6.50
        call      malloc
        -- snip --
        call      __intel_avx_rep_memset                        #12.8
        -- snip --

Notice that it calls into __intel_avx_rep_memset instead, this is a 512 bit wide AVX optimized memset that will only function on modern CPUs (it did this because I passed -march=native asking it to throw backward compatibility out the window). There is some branching code at the end which deals with cases where nmemb isn't evenly divisible by 512/64=8.
But here is the key take away, we clearly expressed our intent with the trivial loop. The compiler could then replaced the trivial loop (after deducing it's functionality) with an (512 bit) AVX optimised memset written by Intel's engineers specifically for modern Intel CPUs.
There is this thing called the "as-if rule" in C/C++. Which pretty much says:

As long as the program does the same reads and writes to volatile memory in the same order as-if the program was executed according to the language specification, then the program may do ANY transformation of the code it pleases. Including reordering instructions, reordering stores and loads to non-volatile memory, or removing instructions all together.

Just to show you how awesome some compilers can be look at what clang does here:
auto stupid(){
   auto x = new int[30];
  for(int i = 0; i < 30; i++)
    x[i] = i;

  auto sum = 0;
  for(int i = 0; i < 30; i++)
    sum += x[i]*x[i];
  delete [] x;
  return sum;
}

gets compiled into:
stupid():                             # @stupid()
        mov     eax, 8555
        ret

It deduces that the function always returns the same value and it completely removes all code and just returns a constant! It also removes the calls to new and delete as it realises they are pointless and don't affect the output of the function. If that is not impressive, I don't know what is. :)
So I would like to take this opportunity to reiterate my first piece of advice again:
Clearly express what it is you want your code to do. Let the compiler worry about generating good machine code, the compiler is likely much better at it than you are.


Count unique IP address in a date range from Apache log

I assume there's a simply copy-paste error where you have | at the start of a line, instead of at the end of the preceding line?

If we're just going to count lines, there's no need for sort | uniq -c | sort -n - we can replace all that with sort -u.

These two Awk programs can be trivially combined:

awk '$0 !~ /127\.0\.0\.1|bot\.|bot\/|dotbot|crawler/' | awk '{print $2}'

That would become

awk '$0 !~ /127\.0\.0\.1|bot\.|bot\/|dotbot|crawler/ {print $2}'


A simple solution is a good solution:

public GetHeadingImage(string iconName, int heading){
    var directions = new string[] {
        "n", "ne", "e", "se", "s", "sw", "w", "nw", "n"
    };

    var index = (heading + 23) / 45;
    return iconName + directions[index] + ICON_FILE_EXTENSION;
}


For small primes - i.e. up to 2^32 and maybe up to 2^40..2^50ish regions - you can improve speed by several orders of magnitude if you use a Sieve of Eratosthenes.

In order to get decent speed the factor primes - i.e. those up to sqrt(limit), whatever your limit might be - should be sieved up front and stored in an array, alongside with the current working offset for each prime (initialised to the square of the prime). The sieving of the small factor primes can also be done with a - simpler - Sieve of Eratosthenes.

The size of the sieve should be equal to the L1 cache size of the expected target machine (usually 32 KByte), and for maximum efficiency you should use a packed odds-only bitmap. BitArray is slow as molasses, so either use bool[1<<15], or byte[1<<15] with manual bit indexing (i.e. sieve[i>>3] |= 1<<(i&7) to set bit i). Using wheels like mod30 can improve efficiency further, but only in connection with major unrolling of loops and lots of other complications.

Another performance boost is offered by presieving. Instead of clearing the sieve prior to sieving a new window's worth of primes, you simply blast over the sieve a pre-computed bit pattern that corresponds to sieving by a certain number of (odd) small primes. Presieving up to 13 hits a sweet spot in a situation like this, but going up to 17 or 19 can realise further (tiny) speed gains at the cost of much increased size of the precomputed pattern.

In order to illustrate what the code would look like and how the various techniques connect, here's the actual sieving function from my SPOJ PRIME1 submission:

internal static byte[] presieve_pattern;
internal static int presieve_modulus;
internal static int first_sieve_prime_index;
internal static byte[] sieve;
internal static int[] result;
internal static int result_size;

// ...

internal static void sieve_primes_between_ (int m, int n)
{
    if (m > n)
        return;

    Trace.Assert(first_sieve_prime_index == 0 || m > small_odd_primes[first_sieve_prime_index - 1]);
    Trace.Assert((m & 1) != 0 && (n & 1) != 0);
    Trace.Assert(m > 1);

    int sqrt_n = (int)Math.Sqrt(n);
    int max_bit = (n - m) >> 1;         // (the +1 is redundant here since both are odd)

    Trace.Assert(max_bit < sieve.Length * 8);

    if (first_sieve_prime_index == 0)  // without presieving
        Array.Clear(sieve, 0, (max_bit >> 3) + 1);
    else
    {
        int base_bit = (m >> 1) % presieve_modulus;
        while ((base_bit & 7) != 0)
            base_bit += presieve_modulus;
        Buffer.BlockCopy(presieve_pattern, base_bit >> 3, sieve, 0, (max_bit >> 3) + 1);
    }

    for (int i = first_sieve_prime_index, e = small_odd_primes.Length; i < e; ++i)
    {
        int prime = small_odd_primes[i];

        if (prime > sqrt_n)
            break;

        int start = prime * prime, stride = prime << 1;

        if (start < m)
        {
            start = (stride - 1) - (m - start - 1) % stride;
        }
        else
            start -= m;

        for (int j = start >> 1; j <= max_bit; j += prime)
            sieve[j >> 3] |= (byte)(1 << (j & 7));
    }

    Trace.Assert(m > 3 && m % 3 != 0);

    for (int i = 0, d = 3 - m % 3, e = (n - m) >> 1; i <= e; i += d, d ^= 3)
        if ((sieve[i >> 3] & (1 << (i & 7))) == 0)
            result[result_size++] = m + (i << 1);  // m is odd already
}

The code should answer quite a few questions that I simply glossed over in the text. This version is geared towards experimentation with various aspects (like number of presieve primes and so on), and thus it lacks a lot of - uglifying and code-bloating - optimisations.

The wrapper function needs to take care of things like non-sieve primes and normalising arguments, which is why I'm showing it here as well:

internal static void sieve_primes_between (int m, int n)
{
    result_size = 0;

    if (m < small_odd_primes[first_sieve_prime_index])
    {
        for (int i = -1; i < first_sieve_prime_index; ++i)
        {
            int prime = i < 0 ? 2 : small_odd_primes[i];

            if (m <= prime && prime <= n)
            {
                result[result_size++] = prime;
            }
        }

        m = small_odd_primes[first_sieve_prime_index];
    }

    n -= 1 - (n & 1);           // make it odd
    m |= 1;                     // make it odd
    m += m % 3 == 0 ? 2 : 0;    // skip if multiple of 3

    sieve_primes_between_(m, n);
}

This illustrates the kind of complications that you have to deal with when certain optimisations are applied, like special handling for the wheel primes (in this case only the number 2) and the presieve primes.

What is not shown here - because it does not fit the profile of the PRIME1 task - is the remembering of offsets. I don't have working C# code that uses the technique at the moment, because I just started learning the language. Remembering the working offsets shouldn't be too difficult to implement, despite the peculiarities of C# like lack of reference types.

The code takes 3..4 milliseconds to sieve 10 x 100,000 numbers just below the PRIME1 limit (10^9). A version using bool[] could be marginally faster for the low PRIME1 limit but certain further optimisations require the use of byte[] or int[], especially as C# has major performance problems with indexing.

This type of sieve performs decently in the 32-bit range. It can be modified to operate beyond 32 bits but in higher regions of the 64-bit range it gets bogged down by the sheer number of potential factor primes (hundreds of millions, at the end of the range) each of which needs to be considered for sieving each window unless a technique like bucketing is used.


As I wrote in a comment, changing the code here won't change zlib usage, as that's something that's happening at a lower level. Still, I wanted to review the code. However, as TastyLemons rightfully notes in a comment, if you can simply send less stuff all the time, it'll help. But with that much CPU usage for zlib, I'm guessing there's something wonky in the node/zlib/server configuration.

For the first loop (users loop):

That is a very long and complex if condition! And it's filled with magic numbers, as well as numbers that I assume you don't need to calculate over and over again.
The object you're building is mostly the same in both the inner branches, so it'd be easier to build the common part first, and then only add the parts that differ.
There are other small changes that would make things simpler, like setting the dying boolean in the object before pushing it to the array.
You can make good use of the map and filter array methods

For the condition, you're checking if the user is in the same room, and in view of the u user (Sidenote: u is not a terribly descriptive label, and it doesn't help that you sometimes use player and other times use user to refer to the same kind of entity).

I'd make that a method, for instance on the User prototype, if you have such a thing:

User.prototype.canSee = function (otherUser) {
  // initial check
  if(this.room !== otherUser.room) {
    return false;
  }

  // x and y distances between user and other's "radius"
  var dx = Math.abs(otherUser.x - this.x) - otherUser.radius,
      dy = Math.abs(otherUser.y - this.y) - otherUser.radius;

  return dx <= this.xViewDistance && dx <= this.yViewDistance;
};

(if you don't have a User prototype, you can change the function to be a plain function that takes two arguments.)

I'm assuming here, that the *ViewDistance values are already calculated, since I imagine they don't really change (or at least don't change all the time). So if the screenWidth doesn't change much, you could calculate a screenHalfWidth and keep it around, so you don't always have to divide by 2 to get the same result. And the 20 needs to be a needs constant (I know JS doesn't have constants; I mean a variable you treat as constant). Something like SCREEN_WIDTH_MARGIN and maybe a similar thing for height.

So xViewDistance might be defined as user.screenHalfWidth - SCREEN_WIDTH_MARGIN, which itself is a value that probably won't change all the time, and can thus be stored.

Point is, you end up with code, where:

your magic numbers are labelled so you know what they mean
your magic numbers are defined in exactly 1 place, so you only need to hunt down the same number in 23 different places if it needs to change
calculations are done once, and the results stored, rather than recalculated constantly despite not having changed.

For building the objects I'd again suggest a method on the User prototype (though again, it can also be a function that just takes an argument). Something like:

User.prototype.getInfo = function (isPlayer) {
  var info = {
    x: this.x,
    y: this.y,
    angle: this.angle,
    hue: this.hue,
    radius: this.radius,
    squeeze: this.squeeze,
    name: this.name,
    dead: this.dead,
    dying: this.dying
  };

  if(isPlayer) {
    info.isPlayer = true;
    info.kills = this.kills;
  }

  return info;
};

Putting it together, you might get:

var visibleUsers = users.filter(function (user) {
  return user.id === currentUser.id || currentUser.canSee(user);
}).map(function (user) {
  return user.getInfo(user.id === currentUser.id);
});

That's everyone's info, including the current user/the player, ready to be sent.

For the energies, the story's similar: Add some methods/functions to do the heavy lifting, and use filter/map to iterate the array. Only trick is that if firstSend is true, we could really skip the filter function, but I've left it pretty much as-is:

var visibleEnergies = energies.filter(function (energy) {
  return currentUser.firstSend || (energy.updated && energy.room === currentUser.room);
}).map(function (energy) {
  var info = energy.getInfo();
  info.anim = info.anim || currentUser.firstSend; // override anim if necessary
  return info;
});