Factorising and Finding Prime numbers with list comprehension

I have to state right at the start, I don't know what your code does.  That's ok.  I'm going to stream-of-conciousness review the code, so you'll get all my thoughts and improvements as it goes on.  Maybe that's a good thing.

Global Variables

Global variables are frowned upon.  They make code harder to test and harder to reason about.  The function user_in modifies all_primes.  What value(s) can all_primes have before the function runs?  If the function is run more than once, does more stuff get added to all_primes?  Does stuff get replaced?  Is the result corrupted?

In this case, the global variable is easy to get rid of.  Instead of modifying a global all_primes variable, how about returning it?

def user_in(num):
    all_primes = []
    while True:
        ...
        all_primes.append(primes)
        ...
    return all_primes

...
all_primes = user_in(x)
...

Now you can run user_in() several times with different input values, and actually test that the right value is returned in your test cases.

Method Naming

What does user_in() do?  It sounds like it might ask the user for some input, but it isn't clear what that input might be.

But reading the user_in() method, it doesn't ask for any input at all!  Rather, the mainline code ask the user to enter a number, and this number is given as an input to the user_in() method.  A better name would be process_and_output(), but that is still a horrible name; it doesn't say what kind of processing is being done, nor what kind of output is produced.  Moreover, the method is producing output and it is (now) returning a value.  Functions should do one logical thing, and be named after what it does.

Ranges, Lists, and Iterables

The statement numbers = [i for i in range(1, num + 1)] constructs a range object with the numbers from 1 to num inclusive, takes successive numbers in that range, and extracts them into a list.  The remainder of the code iterates over the values stored in numbers.

Why?

First of all, numbers = list(range(1, num + 1)) would be a shorter way of expressing the construction of numbers.

Second, why realize a physical list of numbers when you are just going to iterator over it, and a range() object itself is iterable?  Just use the range object.

numbers = range(1, num + 1)

Factorization

factors = [i for i in numbers if num % i == 0]

This is fine, but it is inefficient.  Factors come in pairs.  If num % i == 0, then i is a factor and num // i is also a factor.  If you recorded both, then instead of looping over all numbers, you could loop up to math.isqrt(num) + 1.  If num is one million, this would save you nine hundred and ninety nine thousand trial divisions!  Note, you would have to watch for the special cases of num being a perfect square: you would want to generate that factor exactly once.

Move Constant Expressions Out of Loops

What does this statement do?

    primes = [i for i in factors if len(factors) <= 2 and i != 1]

First, look at the len(factors) <= 2 condition.  Can it change during the loop, or will it always be either True or False?  The list of factors doesn't change, so clearly the length is constant.  So we could write this as a two statements:

    if len(factors) <= 2:
        primes = [i for i in factors if True and i != 1]
    else:
        primes = [i for i in factors if False and i != 1]

Simplifying if True and anything to if anything, as well as if False and anything to "never", we get:

    if len(factors) <= 2:
        primes = [i for i in factors if i != 1]
    else:
        primes = []

Moreover, if there are 2 or less factors, those factors are 1 and num.  Since you are filtering out the i == 1 factor, you will always be left with the second factor, if it exists, which will always be num:

    if len(factors) == 2:
        primes = [num]
    else:
        primes = []

Then, you are adding this list to all_primes, and later flattening the list, to remove the empty lists which you added.

How about, just adding the prime you found to all_primes, and not generating a list of lists?

    if len(factors) == 2:
        all_primes.append(num)

Printing

That is a rather long print statement.  Any reason for making it that long?  Maybe split it up into the equivalent 7 print statements?  We've gotten rid of primes, which contained 0 or 1 value, so computing the "sum of primes" needed to be adjusted.  It begs the question as to what the "sum of primes" was supposed to be?  Why does it produce 0 if the number wasn't prime?

    print('Number: {}'.format(num))
    print('Factors: {}'.format(factors))
    print('Factor count: {}'.format(len(factors)))
    print('Sum of factor: {}'.format(sum(factors)))
    print('Sum of numbers: {}'.format(sum(numbers)))
    print('Sum of Primes: {}'.format(num if len(factors) == 2 else 0))
    print(''.format(primes))

Wait a second ... what is that last print statement printing?  ''.format(primes)?  Did you have an argument to the format statement that didn't have a corresponding {} code???

Python 3.6+ now has something called an f-string, which allows you to interpolate values and expressions directly into the string, so you will never mismatch .format(*args) again!

    print(f'Number: {num}')
    print(f'Factors: {factors}')
    print(f'Factor count: {len(factors)}')
    print(f'Sum of factor: {sum(factors)}')
    print(f'Sum of numbers: {sum(numbers)}')
    print(f'Sum of Primes: {num if len(factors) == 2 else 0}')
    print()

Looping a Fixed Number of Times

def user_in(num):
    while True:
        if num <= 2:
            break
        num -= 1
        ...

This code wants to loop starting from num - 1, and go down and stop at 2.  This is what for variable in range(): statements were meant for.  Don't recreate for loops by using while True loops and modifying the loop index yourself:

def user_in(start):
    for num in range(start - 1, 2, -1):
        ...

Sum of all primes

print('... Sum of all primes: {} ...'.format(..., sum(flat_list) + x, ...))

What is that + x doing there?  If I give as input the number 4, it computes the primes less than 4 to be [2, 3], and the sum to be 9!  I'm pretty sure this is wrong.

Reworked Code

I've reworked the code a little bit, trying to reason out what you were actually trying to do.  For example "Sum of primes" I implemented a running total of the prime numbers being generated.  I also implemented the faster factorization method, I mentioned above, as a separate function.  For good measure, I added a sum_up_to function for computing \$\sum_{i=1}^{n} i\$.  Finally, the main function has been renamed to find_primes_up_to(), since that seems to be what it is doing, and the mainline code has been moved into a if __name__ == '__main__': guard, so the file can be imported into other files, and allows unit tests to be added.

import math

def factorize(num):
    if num == 1:
        return [1]

    limit = math.isqrt(num) + 1

    small = [1]
    large = [num]
    for i in range(2, limit):
        if num % i == 0:
            small.append(i)
            large.append(num // i)

    if small[-1] == large[-1]:
        large.pop()

    return small + large[::-1]

def sum_up_to(num):
    return sum(range(1, num + 1))

def find_primes_up_to(limit):
    sum_of_primes = 0
    primes = []

    for num in range(1, limit + 1):
        factors = factorize(num)

        print(f'Number: {num}')
        print(f'Factors: {factors}')
        print(f'Factor count: {len(factors)}')
        print(f'Sum 1 to {num}: {sum_up_to(num)}')

        if len(factors) == 2:
            primes.append(num)
            sum_of_primes += num
            print(f'Sum of primes: {sum_of_primes}')

        print()

    return primes

if __name__ == '__main__':
    limit = int(input("Enter upper limit: "))
    primes = find_primes_up_to(limit)
    print(f'Primes: {primes}')
    print(f'Sum of all primes: {sum(primes)}')


Comparing random number of bits (followup)

The code looks fine, I can only mention a few things more related to code style, but before we get to that, this one line caught my attention:

if(Utils::isValidBinString(bin_string) || len < check_n_bits) return false;

Nothing really wrong with it, but it reads weird. It returns false if the binary string "is a valid bin string". Hum? Why would we want to fail if the string isValidBinString? This statement is either missing a ! at the beginning, or the function does the exact opposite of what its name advertises, unless you are actually wanting to check "invalid strings", which would also be weird...

As said before, I don't see anything particularly bad with the code, but one thing that I would refrain from doing is prefixing in-class member access with the this-> pointer. That has no practical purpose other than visual noise, but it can also hide variable names that shadow each other, which in turn is a thing you should really avoid.

You could make more thorough use of const on locals that are only assigned once, to ensure they are not changed later. That's a good habit to acquire. We can easily track the lifetime of a variable in a small scope, but sometimes scopes grow big, so it is nice to have a guarantee that a variable is not changed after its initialization. Languages like Rust make immutable the default, which is actually a neat idea, most of time you just want a single assignment.

Storing the return value here:

if(memcmp(tmp_bin_repr, &bin_string[i * 8], chars_to_compare) != 0) {
    match = false;
    break;
}

Is pointless since the function is over after the loop. Just return false directly.

A minor issue, but strict C++ mandates that C library functions and types be accessed from the std:: namespace, and imported from header files like <cstdio>, <cstdlib>, etc. To comply with that and ensure portability across different C++ compilers, you have to, for instance, use std::size_t, std::strlen(), etc.

I don't have problems with macros when they are well used, but you could have accomplished BYTETOBINARYPATTERN and BYTETOBINARY using a constant and inline function, respectively, gaining scoping and better error messages if misused.


Check if two strings are permutation of each other

For short strings, this algorithm and the implementation is good.

If your strings are longer than a few 100 characters and if they only contain ASCII characters, it may be more efficient to count how many times each character appears and then compare if all these counts are equal. This algorithm has complexity \$O(n)\$, but the (invisible) constant factor is larger.

If your strings contain arbitrary Unicode code points, using a simple array for the counts becomes impractical, since that array needs to have 0x11_0000 entries. Looping over these entries and comparing them is \$O(1)\$, but nevertheless it is slow.

Therefore, for practical purposes and the general case, your code looks perfect. There might be some improvements if you know more about the string's contents, but these are on the implementation level, not on the algorithm complexity level.


Just a quick review with changes I'd make if I were working with this controller in a rails project. I'll not changes I make in a list and paste your code with the alterations I've made at the end.

In the third line, you have if params[:search].nil? or params[:search].empty? && params[:where].empty?. I'm assuming you're aware of the operator precedence of or vs ||, but I personally prefer to avoid the or and and keywords as they can cause confusion (both to people new to ruby and myself when I inevitably derp something up)
I saw a lot of duplication in checking for the presence of params[:search] and params[:where]. Repetition of common logic is usually a good candidate for a new method. I created two new methods (search_params and where_params) which preformed these checks internally and returned nil whenever the respective parameter failed the presence checks you were already performing
A lot of what this controller was doing was figuring out what parameters were available in order to construct a list of arguments for Portfolio.search. I'm repeating what I did with the search_params and where_params methods I created and put together a new method for constructing the desired arguments for Portfolio.search
I considered making another method to DRY up the code in search_params and where_params, but I figured there wasn't enough duplication here to justify another method.

Results

class SearchController < ApplicationController
  def index
    if search_params.blank? && where_params.blank?
      @portfolios = Portfolio
        .includes([:user, :portrait])
        .where(published: true)
        .order('created_at DESC')

    else
      @portfolios = search_portfolio search_params, where_params
    end
  end

  private

  # Construct a search query using search arguments
  def search_portfolio(search: nil, coordinates: nil)
    search_args = [ { include: [:user, :portrait] } ]

    # Find portfolios near a given location if coordinates
    # have been provided
    if coordinates
      search_args.unshift({
        where: {
          location: {
            near: Geocoder.coordinates(coordinates),
            within: '300mi'
          }
        }
      })
    end

    # Filter results with a search query if a search
    # term was provided
    search_args.unshift(search) if search

    Portfolio.search(*search_args)
  end

  # Return `params[:search]` if it is present and non-empty,
  # otherwise return nil
  def search_params
    params.fetch(:search, nil).present? ? params[:search] : nil
  end

  # Return `params[:where]` if it is present and non-empty,
  # otherwise return nil
  def where_params
    params.fetch(:where, nil).present? ? params[:where] : nil
  end
end


Is this a good way to syncronize my Threads?

When I tried to measure the delay of AutoResetEvent, I usually got less than 0.1 ms. That doesn't sounds like something you should worry about. If you're seeing larger delay, maybe it's caused by something else. It could be processing the message queue, which is what RenderLoop does between calls to Run().
Calling Set() before you enqueue the item is wrong, because it has a race condition: the dequeuing thread could wake up and call TryDequeue() before you call Enqueue().
In fact, the whole way you're using AutoResetEvent is wrong. If two items are enqueued quickly, then only one of them will be dequeued. Actually, this could be what's causing the delay you see, because it means there could be an ever-growing number of items in the queue just waiting for no good reason.
A better way to write your code would be to use BlockingCollection<T> instead of ConcurrentQueue<T> (which I assume you're using now) and AutoResetEvent.
It might be more efficient to dequeue more than one item from the queue in each call to Run(), if they are available. But probably only a limited amount, to make sure the message queue is processed too.


Recursive branch and bound Knapsack solution

Here is a 'wanna-be functional' solution in java which might help you (it has gone through a set of test cases so I believe it works correctly)

private double bestBound;

public Knapsack.KnapsackResult solve() {
    Cons<Knapsack.Item> list = Cons.from(items);
    bestBound = 0.0;

    double bound = calcBound(list, capacity, 0.0);
    Solution res = dfs(list, 0, capacity, bound, null);

    return buildSolution(res);
}

public Solution dfs(Cons<Knapsack.Item> list, int value, int weight, double bound,
        Cons<Knapsack.Item> taken) {
    if (bound < bestBound) {
        return null;
    }
    if (list == null) {
        bestBound = bound;
        return new Solution(bound, taken);
    }
    Knapsack.Item item = list.head();
    if (item.weight > weight) {
        return notTaking(list, value, weight, taken);
    }

    // taking the item
    Solution left = dfs(list.tail(), value + item.value, weight - item.weight,
        bound, Cons.cons(item, taken));

    // not taking the item
    Solution right = notTaking(list, value, weight, taken);

    if (left == null) {
        return right;
    }
    if (right == null) {
        return left;
    }
    if (right.bound > left.bound) {
        return right;
    } else {
        return left;
    }
}

private Solution notTaking(Cons<Knapsack.Item> list, int value, int weight,
        Cons<Knapsack.Item> taken) {
    Cons<Knapsack.Item> tail = list.tail();
    Cons<Knapsack.Item> without;
    if (taken != null) {
        without = taken.reverse().append(tail);
    } else {
        without = tail;
    }
    double newBound = calcBound(without, capacity, 0.0);
    if (newBound <= bestBound) {
        return null;
    }
    return dfs(tail, value, weight, newBound, taken);
}

public static double calcBound(Cons<Knapsack.Item> list, int k, double acc) {
    if (list == null) {
        return acc;
    }

    Knapsack.Item head = list.head();
    if (head.weight <= k) {
        return calcBound(list.tail(), k - head.weight, acc + head.value);
    } else {
        return acc + head.relativeValue() * k;
    }
}

Here I used cons for lists - so it's the same as lists in Scala. There's only one "global" variable - bestBound - which, I know, not very functional, but it was just simpler than passing it around.


From an OOP design perspective, you've duplicated the sales items. Data is the products, and Products are the products too (hope that makes sense?).

Think back for a second regarding what entities are at work here, and their specific functions. We have:

a manager,
a cashier,
a terminal (which the cashier and manager can both use),
and all the products on the store shelves.

Now, both managers and cashiers are of type Person, however Manager can override the Person class with an Edit function (for the products), whereas Cashier would just inherit Person with the in-built View function, correct? (are you with me so far?)
Now, we can be cheeky and assume that the Terminal has Loading and Saving functions - in lieu of the mainframe in the manager's office (typically terminals are just dumb devices and the price editing is handled by the manager with a list of products sent by head office).
Given that the Manager and the Cashier both need to use the Terminal, you would need to have a Logon and Logoff function, correct? That implies a state pattern, which I'll leave you to research.

Now, your question listed the desired functionality:

read/write CSV
Cashiers have view functionality
Managers have view and edit functionality.
Authentication
Potentially having salaries on managers and cashiers

All these can be achieved in the OOP layout I wrote above. The Authentication component of course would be tied into the Type of which (inherited) Person is logged onto the Terminal (that implies you either need to do some reflection on the logged on user or have an attribute which gives the answer to the terminal).
You also ask:

  Will the code load many Data objects?

That's hard to say, but it sounds like if you stick with a simple approach, it should keep them to a minimum. Also you ask:

  Should I use a singleton for the Data object?

Given the Terminal is responsible for the product data, if the Terminal loads and saves the product data, I don't think you need to worry about that.

Hope this helps!


Naming

The name CompareCode does not express ll what this method is doing. Try to name it more meaningful.

General

You don't need a List(Of String) here. Add a private const string like

Private Const orderedCode As String = "ICMF"
Private Function CompareCode(ByVal code As String, ByVal otherCode As String) As Boolean
    Return orderedCode.IndexOf(code) < orderedCode.IndexOf(otherCode)
End Function


Handling files - the Python way

Without being able to test run your code at the momemt, there is one thing I can already recommend to you, which is to make use of Python's powerful with statement. Using with will make sure that files will be closed no matter what happens (e.g. unexpected exceptions). with also works with more than one file as described in this SO post.

Also consider adding the output filename as parameter to your function. You can even give your momentary value of "output" as default value.

Minor notes on style

I'm not sure if you're aware of the official Style Guide for Python, often just called PEP8. The official recommendation is to use snake_case for variable and function names. This would create a more unified code appearance when working with other Python libraries which often stick to that convention. As always, exceptions apply.

Below is your code including these changes.

def make_key(password, salt):
    ...

def encrypt(password, input_filename, output_filename="output"):
    #creates the needed variables for encryption
    salt = secrets.token_bytes(16)
    key = make_key(password, salt)
    nonce = secrets.token_bytes(AES.block_size)
    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    # put the file size, salt and nonce in outputfile
    filesize = os.path.getsize(input_filename)
    with open(output_filename, "wb") as output_file,\
         open(input_filename, "rb") as input_file:
        output_file.write(struct.pack('<Q', filesize))
        output_file.write(salt)
        output_file.write(nonce)
        #beginning of encryption itself
        chunkSize = 64 * 1024
        while True:
            chunk = input_file.read(chunkSize)
            if len(chunk) == 0:
                output_file.write(cipher.digest())
                break
            output_file.write(cipher.encrypt(chunk))
        print("File encrypted successfully!")


Calculating a factorial with parallel sub-computations using pmap, pvalues and pcalls

1) that is quite idomatic Clojure from what I have seen.

2) macros are "contagious" if the thing you are trying to call is a macro and you want to do anything requiring first-class-functions (map apply reduce etc...) then the thing doing the applying must it's self be a macro.

This is why the coding standards for clojure.contrib stable releases require that your library provide a non-macro way to access it's services in addition to the macro one. as your problem nicely demonstrates.
macros are incredibly useful, and they are not first class


String of numbers to Integers (without using .to_i)

So I think using hex isn't in the spirit of the challenge, but that part is easy anyway:

def to_i(digit)
  '0123456789'.index(digit)
end

Your hash idea would have worked fine here too, but the above is a bit terser.

The rest is a good fit for reduce:

def convert(str)
  str.split('').reduce(0) { |m,x| 10 * (m + to_i(x)) } / 10
end

Or you can forget splitting the solution into 2 functions and just do a 1 liner:

def convert(str)
  str.split('').reduce(0) { |m,x| 10 * (m + '0123456789'.index(x)) } / 10
end

Finally, another alternative which sacrifices some brevity to mirror the definition of what a number is even more closely:

def convert(str)
  str.split('').reverse().map.with_index { |x,i| to_i(x) * 10**i }.reduce(:+)
end


Improve this javascript code: It displays hidden text and highlights the selected page number

Here are some ideas:

Use either tab or, preferably, 4-spaces for indention consistently. Right now the indention is all screwy on JSBin.
Put all your variable declarations at the top, even if you don't define them yet. This'll prevent any confusion from variable hoisting.
Since null is a falsy value, you can change document.getElementById(...) !== null to document.getElementById(...) to check for the existence of an element in you if statements.
Space out your if statements (so if (...) instead of if(...).)
Maybe think about using jQuery? It'll make working with events and elements much easier than using the DOM directly. So for example, hiding all the pages could be written as easy as: $('div').hide().

That's all I have time for now!


Creating a grid in HTML from a database search

Use string.Empty instead of "" to indicate an empty string. It conveys your intent without ambiguity (i.e.: nobody will think you forgot to enter something in the string).

When concatenating in a loop, use a StringBuilder.

Use meaningful names. I don't know what concat and oDrc actually mean. Nor pkunica, but that might be a language-issue (I'd encourage you to stick to English-only).


First, I recommend avoiding the matrix type altogether. The problems it causes outweighs the minor syntactical convenience it provides, in my (and quite a few others') opinion.

Second, the idiomatic way to do this kind of thing in numpy is not to assert that the inputs are particular types, but to coerce them to an ndarray. np.asarray() does this efficiently; if the input is an ndarray, the input passes through untouched; if it is an ndarray subclass, then a new ndarray will be created but only as a view on the original data so no data will be copied.

import numpy as np

def sigmoid(x):
    # No need to use vectorize() for this. It's already vectorized.
    return 1.0 / (1.0 + np.exp(-x))

def prob_hOn_givenV(v, b, w):
    v = np.asarray(v)
    b = np.asarray(b)
    w = np.asarray(w)
    # Don't bother checking the shape. `np.dot()` will do that for us.
    # Strictly speaking, the `asarray(v)` and `asarray(w)` aren't necessary
    # since `np.dot(v, w)` already does that internally. But it does no harm.
    return sigmoid(b + np.dot(v, w))


Generate every unique combination using all elements from array

Your method chooses a word combination at random, then checks if that combination has been discovered previously. The first few combinations are discovered quickly, but last few take much longer. Once you have found 99.9% of the unique rows, it will take on average 1000 tries to find the next unique row. You also give up too soon, leaving some combinations undiscovered.

For n different words, there are n! (n factorial) unique combinations. So for your 8-word example:

    array("Quick", "Brown", "Fox", "Jumped", "Over", "The", "Lazy", "Dog")

there are 8! or exactly 40,320 combinations. When I ran your code, I got only 40,305 rows, in random order, with 15 combinations missing. (and it took 4 minutes!) My version (below) runs in 400ms and produces the rows in the order you desire, i.e. all the "Quick" rows first etc.

My algorithm doesn't make use of random guesses; it uses some loops and recursion to generate all the combinations deterministically.

    // For an array of n words, return an array of n! strings, each containing the words in a different order.
    function wordcombos ($words) {
        if ( count($words) <= 1 ) {
            $result = $words;
        } else {
            $result = array();
            for ( $i = 0; $i < count($words); ++$i ) {
                $firstword = $words[$i];
                $remainingwords = array();
                for ( $j = 0; $j < count($words); ++$j ) {
                    if ( $i <> $j ) $remainingwords[] = $words[$j];
                }
                $combos = wordcombos($remainingwords);
                for ( $j = 0; $j < count($combos); ++$j ) {
                    $result[] = $firstword . ' ' . $combos[$j];
                }
            }
        }
        return $result;
    }


Overall, the code is very good, but a few tiny improvements can be made:

In the decompose function x = x - m can be replaced with x -= m
Instead of return decompose(x) + [m] and such, use yield
Instead of for a in answer ..., use print(*answer, sep='\n')
In the decompose function, math.ceil(float(1 / x)) can be changed to math.ceil(1 / x). Python 3.x automatically interprets / as a float operator
As only math.ceil is used, you could just do from math import ceil

Here's the final code:

from math import ceil
from fractions import Fraction

def decompose(x):
    if x.numerator == 1:
        yield x
        return

    m = Fraction(1, ceil(1 / x))
    x -= m

    yield m
    yield from decompose(x)

def main():
    inp = input("Enter positive fraction in form 'a/b': ")

    try:
        x = Fraction(inp)

    except ValueError:
        print("Invalid input.")
        return

    if float(x) == 0:
        print("Enter non-zero value.")
        return

    if float(x) < 0:
        print("Converting to positive value.")
        x = -x

    if float(x) >= 1:
        print("Enter valid fraction")
        return

    print(*decompose(x), sep='\n')

if __name__ == "__main__":
    main()

Hope this helps!


Splitting Hashmap by converting to TreeMap

Interfaces over implementations

           TreepMap<String, Type> treeMap = new TreeMap<String, Type> (originalMap);

This could be

           SortedMap<String, Type> splittable = new TreeMap<>(original);

That gets rid of the typo TreepMap.

It saves specifying the types twice.  You don't need to do that unless you are building against an old version of Java.

Specifying the interface rather than the implementation makes it easier to change implementations in the future.  You could also use NavigableMap, but it's not necessary for these operations.

I prefer descriptive names like splittable and original to type names.  Of course, your coding standards could be different.

Exceptions

      } catch (Exception e) {
           throw e;
      }

If you're just going to throw the same exception, there's no reason to catch it.  If you want to catch it, then handle it.  If you want it to percolate up to the caller, then just let it go without catching it.  As is, the try/catch doesn't do anything.  You could simplify the code by taking it out.

Alternatives

I'm not convinced that this does enough to be worthwhile.  It's probably going to be less efficient than the more manual solution.  And it's not less code.  Consider

    Map<String, Type> current = new HashMap<>(MAXIMUM_CAPACITY);

    for (Map.Entry<String, Type> entry : original.entrySet()) {
        current.put(entry.getKey(), entry.getValue());

        if (current.size() >= MAXIMUM_SIZE) {
            splitMaps.add(current);
            current = new HashMap<>(MAXIMUM_CAPACITY);
        }
    }

    if (!current.isEmpty()) {
        splitMaps.add(current);
    }

This is about the same amount of code, but it saves turning the keySet into a List.

Both versions have to iterate over the original map.  This one does so manually while the original code did so implicitly by converting to a TreeMap.

I would find the code more compelling if the data was moved from the HashMap to a TreeMap as the base source.  I.e. if there never was a HashMap and the map came as a TreeMap.

This assumes the creation of two new constants.  You might be able to find better names with more context.  I don't like criticalNumber as a name because it doesn't tell me what makes the number critical.  MAXIMUM_SIZE is a bit better in my opinion, as it tells me that the number is a size and that we don't want to go beyond it.


Java hashcode without using the Object#hashCode method

Use meaningful names for your fields:

private int N;
private int M;

What do those fields hold? What is the purpose of them?
Ask yourself those questions and use names that represent the meaning of your field:

private int size;
private int capacity;

Don't cast where you don't need to:

keys = (Key[]) new Object[M];
vals = (Value[]) new Object[M];

This makes no sense; why do you cast a generic Object[] array to a Key[]/Value[] array?
Simply create them without casting:

keys = new Key[M];
vals = new Value[M];

Your hashing methods don't return hashes

Your code is entirely broken in that regard. They only work for Strings and you use them for getting your index. This is not how hashing works!
I don't know if this is a restriction of your assignment, but no matter how large the capacity of your table is, your hashing method should always return the same value in order to be comparable to other objects.


Express a number as a sum of powers of 2

List building performance aside, there is a way to get the powers of two out without touching the bits in between, by using the formulas:

isolateLowestSetBit(x) = x & -x
resetLowestSetBit(x) = x & (x - 1)

These have been explained elsewhere.

Using those definitions, you can extract the powers of two like this:

def two_powers(num):
    powers = []
    while num != 0:
        powers.append(num & -num)
        num = num & (num - 1)
    return powers

Since it potentially avoids testing many bits (depending on the size and sparseness of the input) it may be faster. It can also work out not so well, for very dense numbers.


Implement selection from array by 'random' or 'if/elif conditionals'

The array is clean and easy to read, and it takes up much less space than an army of if/elif/else statements. In my opinion, what you have is much better than the alternative.

That said, there are a couple of things that could be changed.

First, either move the random selection into the getAnswer() function, or change the function to accept an argument. What if you decide later on that you want to get multiple answers? Even if you only call getAnswer() once, making one of these changes will make the function's job clearer.

Second, remove the hard-coded array length in the random.randint() arguments. If you later add or remove answers, the arguments to randint() need to be changed, too. This can be avoided by either using random.choice() (ideal if getAnswer() doesn't take any arguments) or by using random.randint(0, len(answer) - 1) or random.randrange(len(answer)).

randrange() is typically preferred over randint(). Everything else in Python treats ranges as including the start index and excluding the end index, but randint() includes the end index. Not only does that make randint() inconsistent with everything else, but it also makes working with lists and sequences more error-prone (notice how clean and neat randrange(len(my_list)) is compared to randint(0, len(my_list) - 1)?).

Here is how these changes might look (along with one or two other changes, unrelated to how the random selection is made).

Option 1: Random selection inside of getAnswer():

import sys
import random
import time

ANSWERS = ['It is certain', 'It is so', 'Try later', 'Ask Again', 'Not good', 'Doubtful']

def getAnswer():
    print (random.choice(ANSWERS))

def Main():
    prompt_string = 'Try your luck. Yes or no.\n'
    while input(prompt_string).strip().lower() in ('yes', 'y')
        prompt_string = 'Try again (yes or no)?\n'
        getAnswer()

    print('May luck be on your side.')
    sys.exit()

if __name__ == '__main__':
    Main()

Option 2: getAnswer() takes an argument

import sys
import random
import time

ANSWERS = ['It is certain', 'It is so', 'Try later', 'Ask Again', 'Not good', 'Doubtful']

def getAnswer(chosen_index):
    print (ANSWERS[chosen_index])

def Main():
    prompt_string = 'Try your luck. Yes or no.\n'
    while input(prompt_string).strip().lower() in ('yes', 'y')
        prompt_string = 'Try again (yes or no)?\n'
        getAnswer(random.randrange(len(ANSWERS)))

    print('May luck be on your side.')
    sys.exit()

if __name__ == '__main__':
    Main()


Find the min and max elements of a collection, and check whether it is sorted

The quick exit seems a bit clunky.

// 0 or 1 elements
if (first == last) return result;
auto next = std::next(first);
if (next == last) return result;

I also don't like the return on the same line as the if (test) it makes it harder to read (subjective).

I think I would simplify like this:

auto next = first;
if ((next == last) || (++next == last)) {
    return {first, first, last};
}

This also removed the need to declare result so far before it is actually needed.

Thus this:

// The range is not sorted, use a regular minmax_element algorithm
result.min = first;
result.max = current;
result.sorted_until = next;

can now be replaced with:

result_type result = { first, current, next };

Lets also use the std library to convey meaning for the min and max. So this:

if (compare(*tmp.first, *result.min)) {
    result.min = tmp.first;
}
if (not compare(*tmp.second, *result.max)) {
    result.max = tmp.second;
}

Can be replaced by:

auto iterCompare = [&compare](ForwardIterator lhs, ForwardIterator rhs){return compare(*lhs, *rhs);};
result.min = std::min(tmp.first,  result.min, iterCompare);
result.max = std::max(tmp.second, result.max, iterCompare);


Calculator with four arithmetic operations

Do not insult users

"THAT WASN'T A CHOICE, YOU LITTLE SHIT!!!" is absolutely not acceptable.

You are repeating yourself a lot, in programming you should avoid as much as possible code repetition as it leads to bugs and is not easily reusable.

Instead do this:

template<typename Function>
int do_operation(int x, int y,Function operation,string message) {
    cout << message
    cin >> x;
    cin >> y;
    answer = operation(x,y);
    return answer;
}

You can then do:

int add(int x,int y) {
    return do_operation(x, y, std::plus<int>(), "Add two numbers:\n");
}

I see many many if and elif, it is better to use a switch statement. You may even use an array but perhaps then it would be overkill.
learning is quite puzzling as a name. A more standard running is more intuitive.
//doMath.getAn(); and

/*void getAn()
{
    cout << answer;
}*/

are really puzzling. Either uncomment them or delete them because commented out code confuses the readers.
Use constants for your strings and put them at the top. You can modify them in a simpler and faster way.

static const string Menu = "Menu:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\n5) Quit\n"
static const string ErrorMessage = "Invalid choice, enter a valid number."

and then

cout << Menu << endl;
cout << "Choose your option.\n";

and

else {
    cout << ErrorMessage << endl;
    running = 0;
}

Do not use while(learning==1) because it is redundant and weird, use the simpler while(learning) (or even better while(running))
Do not use using namespace std;, if you are curious to know why, look here
Put the first brace on the same line of the function title and indent the function body.

int add(int x, int y) {
    cout << "Add two numbers:\n";
    cin >> x;
    cin >> y;
    answer = x + y;
    return answer;
}


First, use generics properly.

Second, why do you track the cache size if when you need it, you get a hardcoded 99? I will assume that was some sort of mistake.

Third, if you really want to annoy most truely professional java developers and course instructors (i.e, not these that write Java code as if they were programming in C#, C++ or Pascal), prefix your class and variable names. If you don't want to do so, do not make this.

Fourth, I would personally prefer to handle synchronization myself. This way, if the class is expanded to include some method that makes two or more operations in the map, I will not break it. I added the atomicGetAndSet method to show this. If I relied in the synchronization provided by the Collections.synchronizedMap instead of my own, the atomicGetAndSet method would not be atomic and it would break if LRUCache instances are used concurrently.

With this in mind, your code became this:

public class LRUCache<K, V> {

    private final Map<K, V> cacheMap;

    public LRUCache(final int cacheSize) {

        // true = use access order instead of insertion order.
        this.cacheMap = new LinkedHashMap<K, V>(cacheSize, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                // When to remove the eldest entry.
                return size() > cacheSize; // Size exceeded the max allowed.
            }
        };
    }

    public synchronized void put(K key, V elem) {
        cacheMap.put(key, elem);
    }

    public synchronized V get(K key) {
        return cacheMap.get(key);
    }

    public synchronized V atomicGetAndSet(K key, V elem) {
        V result = get(key);
        put(key, elem);
        return result;
    }
}


Finding the Players with the highest score

This is a terrible approach. Sorting the list (an \$O(n \log(n)\$) step) and then iterating through it (an \$O(n)\$ operation) to collect the highest scoring players is simply inefficient.

Instead, just iterate through the list in this way:

List<Player> playersList = new ArrayList<>(players);
Set<Player> highestScoringPlayers = new HashSet<>();
int maxScore = Integer.MIN_VALUE;
for (Player player : playersList) {
    maxScore = Math.max(maxScore, player.score)
}
for (Player player : playersList) {
    if (player.score == maxScore) {
        highestScoringPlayers.add(player);
    }
}
return highestScoringPlayers;

This uses 2 loops and the minimal amount of space (just enough for the original list and the highest scorers) and so is \$O(n)\$, which is better than your \$O(n \log(n))\$ solution.

If you would like to only use 1 loop, at the cost of some additional overhead here is the code:

List<Player> playersList = new ArrayList<>(players);
Set<Player> highestScoringPlayers = new HashSet<>();
int maxScore = Integer.MIN_VALUE;
for (Player player : playersList) {
    if (player.score >= maxScore) {
        if (player.score > maxScore) {
            maxScore = player.score;
            highestScoringPlayer.clear();
        }
        highestScoringPlayer.add(player);
    }
}


While there are examples of how the code can be used, it would be helpful for anyone reading the code (including your future self) to have a comment block above each method to describe the purpose, parameters, return value and any possible error that could be thrown.

The question is tagged with performance- are you trying to optimize the code for speed? If so, it would be better to use a for loop instead of functional methods that use iterators - e.g. Array.prototype.forEach(), Array.prototype.indexOf().

Has the code been tested? Are there any unit tests for the module? If not, it would be wise to create tests to cover all aspects of the code.
Correct me if I am wrong but looking at how the off() method is implemented my presumption is that the call from once() will not actually remove any callback, given that a wrapped function is registered instead of the callback parameter.

There appears to be no validation that the callback is a function. This could lead to an error if some other type is passed in that parameter.

The shorthand property definition notation can be used to simplify the following lines:

 return {
    on: on,
    once: once,
    off: off,
    emit: emit,
    getListeners: getListeners
  }

To this:
return {
    on,
    once,
    off,
    emit,
    getListeners
  }

You may be interested in reading the responses I received on similar code I wrote- see Event emitter npm module


How do I simplify the following slice of a Makefile?

All of these rules

Audio/%.o: Audio/%.cpp
        $(C) $(CF) -c $< -o $@

# etc.

are redundant!  Your first pattern rule

%.o: %.cpp
        $(C) $(CF) -c $< -o $@

already covers them all.


Refactoring code duplication so the same textArea is not used in 4 different classes

Write your own class:

class MyTextArea extends JTextArea{

    private final List<Foo> list;

    MyTextArea(int row, int col, List<Foo> list) {
        super(row, col);
        this.list = list;
        setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics g) {
        for (int i = 0; i < list.size(); i++) {
            if(i == lineIndex)
                g.setColor(Color.black);
            g.drawRect(0, 20, 750, 20);
            //use list...
        }
        super.paintComponent(g);
    }
}


Combine a boolean condition with a Where clause in same query

Taking @VisualMelon's advice,

I converted it to this code, also replacing the compare with equal, maybe better.

List<KeyValuePair<int,string>> Groups =
model.Groups.Where(
  m => string.Equals(m.Value,
                     "properties",
                     StringComparison.OrdinalIgnoreCase) == isProperty)
  .ToList();


Yours is definitely an improvement, but there is still room for more improvement:

PEP8

The official Python style guide will tell you:

two newlines between every function (i.e. before detectCollision, etc.)
function and variable names in snake_case, i.e. detect_collision
avoid line continuation: this

    return cat.get_size()[0] + x >= window_size[0] or \
        cat.get_size()[1] + y  >= window_size[1] or \
            x <= 0 or y <= 0

should become

return (
    cat.get_size()[0] + x >= window_size[0]
    or cat.get_size()[1] + y  >= window_size[1]
    or x <= 0
    or y <= 0
)

spaces after the commas in ['right','down','left','up']
remove the spaces before the commas here:

        return x , y+5
    elif direction == 'left':
        return x - 5 , y
    elif direction == 'up':
        return x , y - 5

Main function

Move everything starting with i = 0 into a main function that is called with a name guard:

if __name__ == '__main__':
    main()

Constant arrangement

There's a big crazy mix of constants and variables in global scope. I consider these constants that should be grouped together:

FPS = 30  # frames per second setting
WINDOW_SIZE = (400,300)
WHITE = (255, 255, 255)

Nothing else in that region should be in global scope.

Enums

Represent direction as an enum.Enum with four entries, rather than a stringly-typed variable.

Hard exit

Don't exit from listen_to_quit - just break out of the loop.

Better yet - rearrange your code so that you don't need a forever loop:

while not should_quit():
    pygame.display.update()
    fps_clock.tick(FPS)

    DISPLAYSURF.fill(WHITE)

    x,y = getMovement(x_,y_,direction)
    while detectCollision(cat,x,y,window_size):  # if there would be a collision, change direction
        direction = getDirection(direction)
        x,y = getMovement(x_,y_,direction) # re-calculate movement, now avoiding collision

    x_,y_ = x,y

    DISPLAYSURF.blit(cat,(x,y))


Regarding the code itself I think functions should usually return an output and then this should be printed. It is also worth introducing some way of alerting the user if there input causes an error. I entered
5, -3, 0 and this raised an error because your code splits on spaces not commas. Additionally, you are mapping the list to int so entering a character by mistake breaks the code

Hence saying something like

def get_input():
    input_str = input("Enter elements to be sorted: ")
    try:
        lst = list(map(int, input_str.split()))
    except:
        raise TypeError ("Please enter a list of integers only, separated by a space")
    return lst

def selection_sort(thelist):
    for i in range(len(thelist)-1):
        min_idx = i

        for j in range(i+1, len(thelist)):
            if thelist[j] < thelist[min_idx]:
                 min_idx = j

        thelist[i], thelist[min_idx] = thelist[min_idx], thelist[i]
    return thelist

if __name__ == '__main__':
    input_list = get_input()
    output = selection_sort(input_list)
    print(*output, sep = ", ")


Cops and robbers program to find the most frequent character in a string

for(int i = 0; i < input.length(); i++)
{
    done.add(String.valueOf(input.charAt(i)));
    all.add(String.valueOf(input.charAt(i)));
}

Instead of iterating over the input string like that, converting every single character to a new String, actually doing all of this twice, and adding each to a collection, you can convert the string to a list of Strings (for each character) like this:

List<String> inputChars = Arrays.asList(input.split(""));

Note that previously to Java 8 this results in the first element being an empty string, which must be handled accordingly.

Then add all of the characters in the array to the collections:

done.addAll(inputChars);
all.addAll(inputChars);

int highest = 0;
int overallIndex = 0;
for(int i = 0; i < num.size(); i++)
{
    if(num.get(i) > highest)
    {
        highest = num.get(i);
        overallIndex = i;
    }
}

To better structure your code, move the loop to a method findIndexOfHighest(). Your overallIndex actually is the indexOfHighest. Then you get the index of the highest element and the highest element like this:

int indexOfHighest = findIndexOfHighest();
int highest = num.get(indexOfHighest);

Add blank lines between blocks of code, e. g. between for loops. That makes your code much more readible.

int amount = done.size();
for(int i = 0; i < amount; i++)
{
    String letter = done.first();
    int tempNum = 0;
    for(int j = 0; j < all.size(); j++)
    {
        if(all.get(j).equals(letter))
        {
            tempNum++;
        }
    }
    num.add(tempNum);
    some.add(letter);
    done.remove(letter);
}

Here the inner loop can be a for-each loop. Also it should be in a separate method, because what it does is countOccurences(String s, char c). The variable tempNum should be called count or occurences.


There is no space before : in types.
There is a space after the return type
There is a space between function arguments, after the comma.
str::to_lowercase allocates a new string. It's a potential optimization to iterate through each character and convert to lowercase. Profiling should be done if performance matters.
Could use itertools sorted to reduce some boilerplate. Does the same thing under the hood.

extern crate itertools;
use itertools::Itertools;

/// Returns the sorted alphabetic symbols of a string in lowercase.
fn normalize(s: &str) -> Vec<char> {
    s.chars()
        .flat_map(char::to_lowercase)
        .filter(|c| c.is_alphabetic())
        .sorted()
}

/// Returns true if the sets of alphabetic symbols coincide.
pub fn is_anagram(a: &str, b: &str) -> bool {
    normalize(a) == normalize(b)
}

#[test]
fn is_anagram_test() {
    assert!( is_anagram("Clint Eastwood", "Old West Action"));
    assert!( is_anagram("wisdom", "mid sow"));
    assert!(!is_anagram("Reddit", "Eat Dirt"));
    assert!( is_anagram("Schoolmaster", "The classroom"));
    assert!( is_anagram("Vacation Times", "I'm Not as Active"));
    assert!( is_anagram("12431b53c11a5324", "abc"));
}

Ultimately, you won't be able to achieve the same particular kind of elegance as the Haskell solution, but I'd hope that the performance would be better.


Is this implementation of binary search correct?

I believe it works correctly, but I'm not enthused about the style.

A few points in no particular order:

Array indices should be size_t rather than int.

I really dislike loops of the form:

while (true) {
    if (something) break;
    do_real_loop_body();
}

I'd rather see the condition for exiting the loop written into the loop condition itself.

In this case, I'd also rather see a for loop than a while loop. We need to do some initialization, a test on every iteration, and update some variables ever iteration. When we have all three elements of the for loop, we might as well use it as simulate it on our own.

Although I know some misguided people agree, it's also generally best to avoid using braces when (for example) each leg of your if statement is only controlling a single statement.

Incorporating all these, we end up with a function that looks more like this:

bool binarySearch(int* array, size_t endPos, int element) {
    if (endPos == 0)
        return false;

    size_t startPos = 0;
    for (size_t pivotPos = endPos/2;
        endPos-startPos != 1;
        pivotPos = startPos + (endPos - startPos) / 2)
    {
        if (element < array[pivotPos])
            endPos = pivotPos;
        else
            startPos = pivotPos;
    }
    return element == array[startPos];
}

The next step would be to make it generic, working with iterators so it can deal with different containers and different types in those containers. For that we could end up with something closer to this:

template <class Iter, class T>
bool bfind(Iter left, Iter right, T val) {
    Iter o = right;
    while (left < right) {
        Iter middle = left + (right - left) / 2;
        if (*middle < val)
            left = middle + 1;
        else
            right = middle;
    }
    return left != o && *left == val;
}

Interestingly, the generic version is not only more versatile, but also somewhat simpler.


Python - Do I need a class or are these functions okay?

Wow, this is kind of a mess.
I'll just review items in sequence as I read them.
My short answer, tl;dr: Yes!
Try executing python 2.7 code with a python 3 interpreter,
even if only during development on your laptop, or in unit tests.
It will give you the confidence to import six or otherwise drag
ancient code kicking and screaming into the modern era.
Small changes like print x → print(x) are easy and helpful.
The first three lines are nice.
We define currentdirectory, versionf, & verfile as top-level module constants.
PEP-8 prefers the name current_directory, but I quibble, it's fine as-is.
You conditionally def or print.
I recommend an early abort:
            if not os.path.isfile(verfile):
                raise FileNotFoundError(verfile)

You have unfortunate coupling in this code.
Python, like all O-O languages, offers you structuring tools to improve cohesion.
Please avoid the global keyword, it is a bad code smell.
And please avoid nested def, as its effect on namespaces is similar to using global variables.
For private helpers, choose _private names like def _get_app_name,
def _version_number, and def _app_name_version.
You wrote:

application = subprocess.check_output(['grep', 'application', verfile]) ...

In several places you reference verfile.
Just listen to your code.
Clearly it is telling you it wants an __init__ constructor
which assigns to self.verfile, so that it may be used here.
Also, fork'ing grep is a tool one might use,
but it's not the most appropriate one for the task at hand.
Let me introduce you to import configparser.

                global application
                ...
                return application

Ok, you used to have 3 module-level variables,
and now you've added a 4th one.
Sadly, you have scattered them all around the module,
and you will continue to define additional ones.
This is poorly structured.
There's no central place for a maintenance engineer
to discover "what are the important pieces of state I need to worry about?"
Also, not sure why, after side effecting the variable,
you bothered to return it, since caller ignores the return value.
Rather than no-arg invocations of get_app_name and version_number,
you might consider passing in the values they need as arguments.
But if you turn this into a class, then self can supply those values.

            except:
                print ...

Better for your catch to be except Exception,
lest you accidentally catch CTRL-C exceptions, as well.
Consider using a logger.
Then we continue to see a pattern of "more of the same",
I won't belabor it with repetition.
You are consistently abusing namespaces,
relying on implicit args,
and side effecting globals at module-level.
It's not quite clear from the generic code you posted,
but I'm going to go out on a limb and say that this module
seems to be about "app verification".

Please do this:
class AppVerifier:

and then define half a dozen object attributes as I suggested above.
Doing just that one thing will have a huge effect on making your
code more maintainable for the next engineer that has to interact with it.


I assume that you are familiar with std::queue and std::deque and wrote this class as a reinventing-the-wheel exercise.

There are a few mainly aesthetic points that you could improve:

int size() is better if returning a std::size_t, which is the underlaying type returned by vector::size().
Keep parameter names in function prototypes, it helps self-documenting the code.
T peek() doesn't change any internal state, so it should be const too.
operator[] should be provided with two overloads, const and non-const:

T& operator[](std::size_t index);
const T& operator[](std::size_t index) const;

Otherwise you won't be able to access data in a const Queue<T>. The same thing applies to begin()/end(). You will have to provide both const and non-const versions. This is purely boilerplate code, but C++ doesn't offer a better solution.
This excessively long name: typename std::vector <T>::iterator should be replaced by a typedef or using alias:

using iterator = std::vector<T>::iterator;

// Then you simply use `iterator` now:
iterator begin() { ... }

Shouldn't you provide a constructor that takes no arguments? It is very likely that you will want to declare an empty queue at some point. A default constructor should also do:

Queue() = default;


Ping and write the status of a timer on a GUI thread

As it is not really much code, let us just focus on the label part and a little naming.

TimesBufferClear++;

If this is a variable, we should use camelCase casing for the name. If it is a property it follows the naming convention.

currping

Can be renamed to currentPingStatus, which is more meaningful.

Now let us refactor the assignment to the Text property of this label:

String formatPattern = "Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}";

currentPingStatus.Text = String.Format(formatPattern,
         waveProvider.BufferedDuration.Milliseconds.ToString(),
         TimesBufferClear.ToString(),
         pingSender.Send(otherPartyIP.Address).RoundtripTime.ToString(),
         SendStream.BufferMilliseconds);


Manipulating URL/array to remove the last element

pop() mutates the underlying list: it removes the last item (and returns it).

It seems you're looking for slice:

"www.mycompany.com/sites/demo/t1".split('/').slice(0, -1).join('/')
// -> gives: "www.mycompany.com/sites/demo"

.slice(0, -1) gives the elements of the list from the start until the end minus one item.

However, this is a very poor solution to drop the last path element from a URL. In particular, splitting a string to an array, drop the last element and join the string again is inefficient. It would be better to use lastIndexOf to find the position of the last /, and then substr to extract the part of the string before the last /.

var s = "www.mycompany.com/sites/demo/t1";
s.substr(0, s.lastIndexOf('/'));


Polling AJAX client for P2P file sharing website

You are polling filecheckerhandler.ashx regularly at two-second intervals. The fact that such polling is implemented using recursion, with Filer() calling itself, is irrelevant to your performance problem.  You could improve the client code by using setInterval() instead of setTimeout(), but the overall system performance will be just as bad.

There are only three strategies to improve system performance:

Lengthen the polling interval.  Especially if no activity has occurred recently, activity is less likely in the near future, so the polling interval could be adaptive.
Improve the efficiency of filecheckerhandler.ashx.  The constraining factor is probably load on the server, rather than load on the client, so any efficiency gains on the server would likely make an impact.
Improve the efficiency of the communication protocol.  Each AJAX request is essentially a new HTTP request, with the only optimization being possible HTTP keep-alive, which might avoid the TCP handshake.  Consider a technique that is more suitable for client-to-server notifications, such as Comet.


There are two things that can be criticized here: Your coding style and your algorithm.

Code Style

There are unnecessary spaces inside some parens: new StringBuilder( source), for (…; start++ ){. Make a conscious decision to follow one style and follow it through.
Improve readability by consistently putting a space around most operators like =, -, + and <=.
Never ever catch (Exception e)! If there is a specific exception you would like to catch, then please do, but specify the appropriate class or interface. But often it is better to just let the exception bubble up through the call stack.

Do not catch exceptions you are not interested in actually handling. Do not catch exceptions you have no idea where they would come from. Why are you currently catching an…

… ArithmeticException? Is there any chance e.g. for a division by zero in your code?
… ArrayIndexOutOfBoundsException? Where are you using arrays?
… ArrayStoreException? Where are you storing stuff into an array?
… ClassCastException? Your code does not contain a single cast.
… ClassNotFoundException? You have no dynamic class loading in your code.
… CloneNotSupportedException? You don't call clone on any object.
…

Use good variable names that make it clear what a certain variable means. Shouldn't p be reversed or something like that?
I would not introduce a sb variable for the StringBuilder, but rather:

String reversed = new StringBuilder(source).reverse().toString();

The palindrome finding code is not callable as a method. Extracting code into sensible methods improves testability, and can make it easier to design good programs.

Bugs

Some bounds you choose are rather weird. For example, start <=source.length() should be start < source.length() or even better start <= source.length() - largest.
The indexOf method returns an index on success, and -1 on failure. The snippet if (p.indexOf(sub) > 0) is therefore misleading. Anyway, you should be actually using if (p.contains(sub)).
Your logic just asserts that the source string contains both a substring and the reversed substring. It does not assert that it contains any palindrome. For example, computers return will cause your code to output uter. You would have to check the actual indices, or better: that the substring equals itself reversed.

Algorithm

Your current algorithm works by extracting all possible substrings of length 2 or longer, and then checks whether the substring reversed is contained in the source string. As explained above, this is wrong. It is also quite inefficient, because your algorithm runs in O(n²) (two nested loops).

The problem could be solved in a fraction of the code by a recursive regular expression, e.g. in Perl/PCRE: (.)(?:(?R)|.?)\1. Sadly, the regex implementation of the Java standard library does not support this.

According to the Wikipedia article on Longest Palindromic Substrings, it is possible to find them in linear time. You may want to implement such an existing algorithm.


Recursively parsing JSON response using GSON

Have the following POJOs

class Result {
    private String resourceId;
}

class Next{
    private String url;
}

class Response{
    private boolean hasMore;
    private List<Result> result;
    private Next next;
}
// If other fields are required add them.
// Have their getters/setters.
// Have the hashCode,equals,toString

Your getListOfIps() could look like this:

List<String> ips = new ArrayList<String>();
Response response = null;
String url = getURL(alias);
do{
    String responseJson = getJsonResponse(url);
    try{
        response = new Gson().fromJson(responseJson , Response.Class);
    } catch( // Json Exceptions thrown by this function){
        // Log the exception and handle it .
    }
    // Check if response and response.result is non null
    // Loop through and extract the non-null resourceId
    // update url
    if(response.hasMore && (response.next!=null) && (response.next.url.length()>0)){
        url= response.next.url;
    }else{
        url = null;
    }
  } while(url);

The code is more of a "steps to follow". Hope it helps.
Try the code and you can post the updated code if its better.
For Gson help follow this link.


Scan a spatio-temporal cube and run a cross-correlation on it

Scale
Since you have
for ii in range (0,1750):
    for jj in range (31,351):
        for kk in range (31,351):
            pulse_2d = np.zeros((39,63,63))

your inner loop will be on the order of
$$
1750 \cdot (351-31)^2 \cdot 39 \cdot 63^2 = 27,738,547,200,000
$$
That is well (well) beyond the point that I would give up Python altogether and drop down to C. Even if you were to vectorize this further with Numpy as much as possible (and I'm not clear on whether that's possible), I doubt that you could get this down to a sane execution time.
Strongly consider GSL and/or BLAS.


Minor comments, but...

    else:
        if table[i] > -1:
            m += i - table[i]
            i = table[i]
        else:
            m += 1
            i = 0

This sort of construct, an else which contains only an if-else chain, can be simply written as an elif-else chain.

    elif table[i] > -1:
        m += i - table[i]
        i = table[i]
    else:
        m += 1
        i = 0

        table[position] = candidate + 1
        candidate += 1

These statements seem weird, why not first add one and then set?

        candidate += 1
        table[position] = candidate


Logic

Never omit the optional braces like that.  Think of yourself as a contributing factor to a future coding accident.  If you really want to omit braces, then put the statement on the same line, so that there is no possibility of misinterpretation.

The function does not check for overlong encodings, invalid byte sequences, or invalid code points.  Those caveats should be declared in JavaDoc.

I would eliminate the length > 6 check, as 6 is a magic number.  You don't need that special case anyway.

I would also incorporate the length == 1 special case into the regular logic.

In general, text is more likely to contain shorter UTF-8 sequences than longer ones, so you might as well handle the shorter cases first to save a few CPU cycles.

Rather than setting n to be the number of trailing bytes, set it to be the expected length of the array.  I'd rename n → expectedLen to be more descriptive.  That makes the code more readable (and saves one pointless subtraction).

Eliminate the bit-shifting.  Just AND with the bitmask to specify which bits you are interested in inspecting.

public static boolean validate(byte[] bytes) {
    int expectedLen;
    if      (bytes.length == 0)                     return false;
    else if ((bytes[0] & 0b10000000) == 0b00000000) expectedLen = 1;
    else if ((bytes[0] & 0b11100000) == 0b11000000) expectedLen = 2;
    else if ((bytes[0] & 0b11110000) == 0b11100000) expectedLen = 3;
    else if ((bytes[0] & 0b11111000) == 0b11110000) expectedLen = 4;
    else if ((bytes[0] & 0b11111100) == 0b11111000) expectedLen = 5;
    else if ((bytes[0] & 0b11111110) == 0b11111100) expectedLen = 6;
    else    return false;

    if (expectedLen != bytes.length) return false;

    for (int i = 1; i < bytes.length; i++) {
        if ((bytes[i] & 0b11000000) != 0b10000000) {
            return false;
        }
    }

    return true;
}

Interface design

It's rarely useful to validate a single character: usually, you'll want to validate a whole string.  You should name your function to avoid giving the impression that it checks for multi-character strings.

In Java, functions that perform a test and return a boolean are conventionally named isSomething() or hasSomething().  A function named validate() suggests that it performs an action as a side-effect, perhaps throwing an exception on failure.

Therefore, I'd rename your function to isValidChar(byte[] bytes).

So, what if I need to validate a string?  I'd have to somehow chunk it up into right-sized byte arrays first.  That's not really possible without examining the string using similar logic to what is in the function itself.  Even then, it would be wasteful to construct a byte array just for the function call.  Therefore, I think that it would be more useful to provide a function that validates a string.  To go further, you could make such a function return something more informative than just a boolean.

/**
 * Returns the number of UTF-8 characters, or -1 if the array
 * does not contain a valid UTF-8 string.  Overlong encodings,
 * null characters, invalid Unicode values, and surrogates are
 * accepted.
 */
public static int charLength(byte[] bytes) {
    int charCount = 0, expectedLen;

    for (int i = 0; i < bytes.length; i++) {
        charCount++;
        // Lead byte analysis
        if      ((bytes[i] & 0b10000000) == 0b00000000) continue;
        else if ((bytes[i] & 0b11100000) == 0b11000000) expectedLen = 2;
        else if ((bytes[i] & 0b11110000) == 0b11100000) expectedLen = 3;
        else if ((bytes[i] & 0b11111000) == 0b11110000) expectedLen = 4;
        else if ((bytes[i] & 0b11111100) == 0b11111000) expectedLen = 5;
        else if ((bytes[i] & 0b11111110) == 0b11111100) expectedLen = 6;
        else    return -1;

        // Count trailing bytes
        while (--expectedLen > 0) {
            if (++i >= bytes.length) {
                return -1;
            }
            if ((bytes[i] & 0b11000000) != 0b10000000) {
                return -1;
            }
        }
    }
    return charCount;
}

That's a more versatile function, for about the same amount of code.


Computing the cost for creating a perfect square (with N = 3)

Since the function is hardwired to 3x3 matrices, it would make sense to pass a 3x3 matrix as an argument:

int formingMagicSquare(const int s[3][3])

This way you will not worry about what to do if s_rows != 3.
stdlib provides int abs(int).
The line

    if(cost4_this_operation < cost)cost = cost4_this_operation;

better be split into

    if(cost4_this_operation < cost) {
        cost = cost4_this_operation;
    }

Even better, make a static inline int min(int, int) function.
I see nothing wrong with the loops.
Of course, the solution is not scalable for larger dimensions.


The easiest way to implement Timsort in Python is of course to use the built-in version:
def timsort(x):
    return sorted(x)

Since you don't learn anything from that, implementing it yourself is of course nice.
First, some general comments.

Python has an official style-guide, PEP8. It recommends using lower_case for variables and functions. It also recommends using empty lines sparingly.
You don't need to pass the length to the algorithm. Every indexable Python object has a length, so just use len(unsorted).
Your type hints say that this function can only take lists of integers. It works perfectly fine with lists of any comparable type, just like the built-in sorted.
Choosing to modify the input list in-place is perfectly fine for lists (after all, list.sort does the same thing). But if you do that, it should be noted in the docstring. You could, however, also choose to conform closer to sorted and first copy the iterable into a list (simply copying if it already is a list), sorting it in-place and returning it. This would change the signature to tim_sort(x: Iterable[Any]) -> List[Any].
The built-in sorting functions all take a key argument, which is called once per argument. This results in effectively sorting [key(element) for element in x] and afterwards returning only the second element from each inner tuple.

Now, let's take a closer look at your actual code.
You use while loops quite a lot. While (pun intended) they almost always work, they are not always the most efficient (in readability) way to accomplish your goal. In the merge function you can replace the last two while loops with list slice assignments. I would also simplify the setting of left_side and right_side by using left, middle and right instead of left, middle, len1 and len2.
def merge(unsorted: List[int], left: int, middle: int, right: int) -> None:
    """ Merges two sorted arrays """
    len1 = middle - left + 1
    len2 = right - middle
    left_side  = unsorted[left:middle + 1]
    right_side = unsorted[middle + 1:right + 1]

    i = j = 0
    k = left
    while i < len1 and j < len2:
        if left_side[i] <= right_side[j]:
            unsorted[k] = left_side[i]
            i += 1
        else:
            unsorted[k] = right_side[j]
            j += 1
        k += 1

    unsorted[k:] = left_side[i:]
    unsorted[k + len1 - i:] = right_side[j:]

Instead of slices, you can also create a new list and use extend:
def merge(unsorted: List[int], left: int, middle: int, right: int) -> None:
    """ Merges two sorted arrays """
    len1 = middle - left + 1
    len2 = right - middle
    left_side  = unsorted[left:middle + 1]
    right_side = unsorted[middle + 1:right + 1]

    i = j = 0
    k = left
    out = []
    while i < len1 and j < len2:
        if left_side[i] <= right_side[j]:
            out.append(left_side[i])
            i += 1
        else:
            out.append(right_side[j])
            j += 1
        k += 1
    out.extend(left_side[i:])
    out.extend(right_side[j:])
    unsorted[:] = out

The first while loop could also use iterators instead of indices, but that is left as an exercise for now.


HTML page compiling LaTeX code to nice mathematics display - 2nd attempt

I'll just go through this as I find issues:

Don't declare your main dependency as async. In case the server goes down that makes your page look stupid. What you should do instead is check that the script was actually loaded before trying to use it.
JS standard naming convention for functions is camelCase. see the js-standard api as well as every major js framework. This is not python: get_url_parameter \$\rightarrow\$ getUrlParameter.
Same applies for variable names throughout your code.
Use 'use strict' to force compliance to new JS standards. And use it in the largest scope you control alone:

function getUrlParameter(param) {
    'use strict'
    let pageUrl =  // ...

I like how you encapsulated the parameter getting into it's own method. I also like how you use standard functions to URI-encode correctly instead of rolling your own encoding
Last time I checked (which is a while ago) it was common to wrap top-level code into a self-executing function like this:

(function() {
    // ...
})();

the main reason why is outlined here on SO
use let over var to communicate mutability intents to other developers (and the script engine). Also don't rely on implicit variable declaration. that's cheap :)
I never understood the point of aligning an assignment operation's right hand side :/
You can make things a tad easier when creating the encodedUrlTextarea.value by using template interpolation:

encodedUrlTextarea.value = `${location.protocol}//${location.host}${location.pathname}?code=${encodeURIComponent(latexInput.value)}`;

This can be made a bit cleaner with some extraction:

let baseUrl = `${location.protocol}//${location.host}${location.pathname}`;
let code = encodeURIComponent(latexInput.value);
encodedUrlTextarea.value = `${baseUrl}?code=${code}`;

As we can see, the creation of baseUrl can be pulled out of the function. It won't change during the script lifetime. Take advantage of that. It's definitely debatable whether the call to encodeURIComponent now really needs to be outside the template string


There are more efficient ways to do this. Now you are buffering the whole file content into memory, when you perform fs.readFile(...). I recommend that you use a readStream, that for example using fs.createReadStream(<path>), pipe it into res. This way you will begin sending the file content earlier, and stop wasting your node processes memory. Also consider moving require to the top of your code, it is a bad practice to call require from function body.


Resizing a discrete uniform CSRNG distribution

There are things you can do to improve the efficiency of your filter solution with small values as the limit.

More efficient filtering

The most obvious one is actually given in the example of the function on the MSDN network - which is basically to extend the filter range to the highest multiple of limit, less than 256. I.e. if the limit is 20, then filter up to 240, and then the modulo is still uniformly distributed:

Copied from that page:

private static bool IsFairRoll(byte roll, byte numSides)
{
    // There are MaxValue / numSides full sets of numbers that can come up
    // in a single byte.  For instance, if we have a 6 sided die, there are
    // 42 full sets of 1-6 that come up.  The 43rd set is incomplete.
    int fullSetsOfValues = Byte.MaxValue / numSides;

    // If the roll is within this range of fair values, then we let it continue.
    // In the 6 sided die case, a roll between 0 and 251 is allowed.  (We use
    // < rather than <= since the = portion allows through an extra 0 value).
    // 252 through 255 would provide an extra 0, 1, 2, 3 so they are not fair
    // to use.
    return roll < numSides * fullSetsOfValues;
}

Statistically insignificant errors

You have another alternative too, which is to reduce any modulo bias to a statistically insignificant amount. You do this by using significantly bigger random numbers (bigger than 256). Combining multiple bytes for each output byte would accomplish this, for example, using 4 bytes. Using more bytes would further reduce any modulo bias:

/* Convert 4 bytes to a long */
private static IEnumerable<long> RandomLongs()
{
    var csrng = new RNGCryptoServiceProvider();
    return Cycle().Select(unused =>
    {
        var bytes = new byte[4];
        csrng.GetBytes(bytes);
        return  (long)(BitConverter.ToUInt32( bytes, 0));
    });
}

private static IEnumerable<int> RandomExtended(int chunkSize, int limit)
{
    var source = RandomBytes(chunkSize);
    foreach (long lng in RandomLongs())
    {
        var nxt = lng % limit;
        yield return (int)nxt;
    }

}

Using 4 bytes of source for your modulo (with max limit 256) will reduce the bias error to about 1 in \$2^{24}\$ ... which would be hard to measure.

This version is also shown here on ideone: https://ideone.com/maiQ70

Removed

On the other hand, there's a better way, that still guarantees uniform distribution, but relies on knowing what the previous value was. Conceptually, this solution relies on having uniform "gaps" between results, and so you can add a uniform random gap to the previous value, and then do the modulo on that.

I implemented it as:

private static IEnumerable<int> RandomWrap(int chunkSize, int limit)
{
    int prev = 0;
    foreach (byte b in RandomBytes(chunkSize))
    {
        prev = (prev + b) % limit;
        yield return prev;
    }

}

Note that it takes the byte-value as a "gap", adds it to the previous result, and then "wraps" it around in the limit range.

You can see the results here in ideone: https://ideone.com/BEbwsA


Most pythonic way to combine elements of arbitrary lists into a single list

Unless I actually needed the whole list at once, I would probably use itertools for this:

from itertools import chain

choice = chain.from_iterable(choices[i] for i in sequence)

If you do need the list, you can still use this with an explicit conversion:

choice = list(chain.from_iterable(choices[i] for i in sequence))

Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.


Locking in MySQL stored procedure for deduplication

Will this work as intended?

Not really.

You've indented the code as if you expect that the statements betweeb DO GET_LOCK... and DO RELEASE_LOCK... would only execute if the lock is obtained.

That is not the case.

You shouldn't use GET_LOCK() in a void context (with DO) unless you don't actually care whether you actually got the lock.  What you have written will wait up to 10 seconds for the lock, and if it isn't available, continues anyway with the next statement.  That does not sound like what you want.

A better solution for MySQL 5.5 and later looks like this:

IF GET_LOCK('my_lock',10) IS NOT TRUE THEN
  SIGNAL SQLSTATE '45000'
         SET MESSAGE_TEXT = 'timed out waiting for named semaphore lock';
END IF;

That will throw an exception and terminate the procedure after the timeout, if the lock has not been obtained.  (This is a useful tactic with the event scheduler, when you need to ensure that concurrent invocations of events don't pile up.)

Note that the logical operator IS NOT TRUE, used above, matches both 0 (FALSE) and NULL, either of which can indicate that you didn't get the lock.

The same is true of RELEASE_LOCK(), which returns TRUE only if you actually held the lock you tried to release.  If you try to release a lock you don't own, that does not throw an error.  You have to check return values.

  In particular, I'm worried that the commit won't happen until after the lock is released.

No, the lock is released after the commit, here.  The get and release operations are only functions.  They execute in sequence like everything else.

Also, it's usually best to leave the caller in charge of the transaction, because if this procedure is called while already in a transaction, START TRANSACTION silently commits the previous transaction and starts a new one, leaving the caller unable to roll back any work done before the procedure was called.  That may not be applicable, here, but it's good practice to handle it consistently across your code base.


A Tiny Text File Read/Write class Implementation in C#

Naming

FileIO: The File class resides inside the System.IO namespace. FileIO is quite a misfortune chose of name. TextFileWrapper, TextFileUtil or TextFileManager would be a more appropriate name for this in my opinion.
FileWrite: The general guidance is to start your methods with a verb. So, WriteFile would be a better name for this.
ReadTxtFile: This name is a bit misleading. txt can be considered as a file extension, so the caller may no specify the filename as you expect.
inputString: Please try to avoid Hungarian notation.

Please try to chase consistency (or symmetry).
Try to name your Read-Write method pair in the same fashion:

ReadTextFile, WriteTextFile
ReadFile, WriteFile
or simply just Read and Write

Stuttering:

Maybe it's just for me, but FileIO.Instance.FileWrite seems too repetitive.
TextFileManager.Write seems way more natural for me.

Robustness
Your implementation is quite naive. It does not deal with a lot of different cases:

What if the fileName points to a non-existing file?
What if the inputString is enormously large?
What if one of the parameters is null?
What if the file has been opened by another method and has not been closed yet?

Your implementation also relies on Encoding.Default, which is computer specific.
Which means you can end up in the following situation:

FileA.txt has been written to the disk on MachineA
FileA.txt has been copied from MachineA to MachineB

where the default encoding is different

MachineB could not read FileA.txt

Thread-safety

Your instance property does not make your class a singleton.

Please read thoroughly Jon Skeet's guidance.

If you make your class a singleton you have to make sure that your operations are thread-safe.

Reading and writing the same file from different threads are handled in a proper way.

As pointed out by others you have to do some clean-up as well.

To make sure that if something goes wrong then your file handles are closed properly.

Performance

Try to take advantage of async I/O
Try to take advantage of ArrayPool when you are calling the GetBytes method.

It has an overload which accepts a byte array

As always, measure, measure and measure.


You can use the not function to get all the details elements except one:

function show(sel) {
  var el = $(sel);
  el.fadeToggle(600);
  $('.details').not(el).fadeOut("slow");
}

$('.details').hide();

$('#item-a').click(function () {
  show('#detail-1');
});

$('#item-b').click(function () {
  show('#detail-2');
});

$('#item-c').click(function () {
  show('#detail-3');
});

$('.btn-close').click(function () {
  $(this).parent().parent().fadeOut("slow");
});


I think the idea to create an abstraction class for request handling is a good one..

A few remarks and/or changes to consider:

This code is flagged as C++14 but there is only C++11 specific code.
I like the idea of using scoped enumerations (enum class ...) instead of the old-style enumerations. Scoped enumerations are more strictly typed.
There are no include guards in resource.hpp. They can protect against (potential) double inclusions.
Copy construction and copy assignment have been deleted, but by convention, deleted functions are declared public, not private..
As for the (deleted) copy assignment, the argument should be a const reference.
In main.cpp, it is good pratice to keep the application specific include file (resource.hpp) under the system include files.
get and set methods are defined in resource.cpp, but these functions are so limited,
why not include them directly in the header file, which would essentially eliminate resource.cpp.
For a default, compiler generated, constructor, it is common practice to use:

Resource() = default;

However, since an uninitialized object is created and populated with values after that, why not set those during construction ? - the constructor then becomes:

Resource(const std::string &path, RequestMethod method, const Handler& callback)
    : m_path{path}, m_method{method}, m_callback{callback} { }

The object can still be modified by calling set functions later.
Resource::GetPath() returns a reference to an lvalue which gives callers direct access to Resource::m_path, which is private.
Many consider this a violation of data encapsulation. Consider changing the return type to a plain std::string.
A std::map is not used yet, but the intention seems to be to store a std::pair in a std::map called path_map. You can call std::make_pair directly on the map inserter:

std::map< std::string, ResourceSharedPtr> path_map;
...
path_map.insert(std::make_pair(resource_ptr->GetPath(),resource_ptr));

If you are planning to use only the ResourceSharedPtr in combination with the std::map pair, you could possibly eliminate m_path inside the Resource class and use the std::map key. Otherwise they are redundant.

With this, the updated source code becomes:

resource.hpp

#ifndef RESOURCE_H
#define RESOURCE_H

#include <functional>
#include <string>

typedef std::function<void(void)> Handler;

enum class RequestMethod {
  GET,
  PUT,
  POST,
  DELETE
};

class Resource {

  public:
    Resource(const std::string &path, RequestMethod method, const Handler& callback) :
        m_path{path}, m_method{method}, m_callback{callback} { }
    void SetMethodHandler(const RequestMethod method, const Handler& callback)
    {
      m_method = method;
      m_callback = callback;
    }

    Handler GetMethodHandler() { return m_callback; }

    void SetPath(const std::string& path) { m_path = path; }
    std::string GetPath() { return m_path; }

    Resource(const Resource& other) = delete;
    Resource& operator=(const Resource& rhs) = delete;

private:
    std::string m_path;
    RequestMethod m_method;
    Handler m_callback;
};

#endif // RESOURCE_H

main.cpp

#include <memory>
#include <iostream>
#include <map>

#include "resource.hpp"

void LoginMethodHandler()
{
  std::cout << "Code here to handle a login request." << std::endl;
}

using ResourceSharedPtr = std::shared_ptr<Resource>;

std::map<std::string, ResourceSharedPtr> path_map;

int main() {

  ResourceSharedPtr resource_ptr = std::make_shared<Resource>("/login",
                                                              RequestMethod::GET,
                                                              LoginMethodHandler);

  /* call to method handler */
  /* ideally in full blown application, logic will be search for path and
     method and call approriate handler */
  resource_ptr->GetMethodHandler()();

  path_map.insert(std::make_pair(resource_ptr->GetPath(),resource_ptr));

  return 0;
}


Replace for loop while with apply family function in R

You could replace the for loop with a function + sapply like this:

reduce.errors <- function(err) {
  while (err >= 10^(-10)) {
    df<-as.data.table(df)
    df[,K:= K1,by=c("a", "b")]
    df[,assetreturn:=c(NA,diff(log(K))),by=c("a", "b")]
    df[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("a", "b")]
    df[,iterK1:=(cap+L*exp(-rf)*pnorm(blackscholes(K,L,rf, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(K,L,rf, 1,rollsdasset[250])) ,by=c("a", "b")]
    df<-as.data.frame(df)
    err <- sum((df[df$V1 %in% err,"K"]-df[df$V1 %in% err,"K1"])^2)
  }
}
sapply(errors$V1, reduce.errors)

But I don't think this will make it faster at all. If I understand correctly you need the while loop there to reduce the error below a threshold, and so you need the iteration and this cannot be replaced with the "apply" functions easily.

If you want to improve the speed, I think you'll need to rethink come up with a different approach, if it's even possible.


Yes java already has that. What you're looking for is an Iterator:

Iterator<Hand> handIt = hands.iterator();
while (it.hasNext()) {
    Hand current = handIt.next();
    if (current.size() == 0) {
        handIt.remove();
    }
}

This can be simplified / changed to:

for (Iterator<Hand> handIt = hands.iterator(); handIt.hasNext(); ) {
    Hand current = handIt.next();
    // ...
}


There's no need to list all the moves.  Here is an unmemoized solution:

naiveWays :: Position -> Int
naiveWays (Position 0 _) = 1
naiveWays (Position _ 0) = 1
naiveWays (Position x y) = (naiveWays (Position (x - 1) y)) +
                           (naiveWays (Position x (y - 1)))

Note that it also takes better advantage of pattern matching.


I would do this:

protected void Button1_Click(object sender, EventArgs e)
{
    string[] str1 = new string[] {"87002", "87001", "87005"};
    string[] str2 = new string[] {"97002", "97003", "97004"};

    if (str1.Contains(TextBox1.Text))
        Response.Redirect("Page1.aspx");

    if (str2.Contains(TextBox1.Text))
        Response.Redirect("Page2.aspx");

    Response.Redirect("Unknown.aspx");
}

You don't need the ToString() calls - TextBox.Text should already be a string.


Sorting almost sorted array with a minimum heap

Algorithm complexity

I am not 100% sure, but it looks like a fancy heapsort which runs (after all) in \$O(n \log n)\$. In order to get this intuition, consider

for slice_start in range(0, length, k + 1):  # sliding window
        # push the next slice to min heap
        for index in range(slice_start, min(slice_start + k + 1, length)):
            heappush(min_heap, a[index])

        result.append(heappop(min_heap))

You operate in chunks of length k + 1 array components (save for the very last chunk that may be shorter). For each chunk, you load it entirely to the heap, and then pop only one element from it to the result array. Finally, in

for _ in range(len(min_heap)):
        result.append(heappop(min_heap))

you handle the majority of elements via heap sort, and that's linearithmic worst case running time.

Perhaps this one?

# This sort runs in O(n log k + k log k),
# which simplifies to O(n log k) whenever k = o(n)
# (k is sublinear in n).
def window_heapsort(a, k):
    if k > len(a):
        return sorted(a)

    window_width = k + 1
    window_heap = []
    result_array = []
    index = 0

    # Initialize the window heap:
    # Runs in O(k log k)
    for i in range(window_width):
        heappush(window_heap, a[i])

    # Keep sliding the window over the array:
    # Here, the size of the heap alternates between
    # 'window_width' and 'window_width - 1', which is
    # O(k), and thus pops and pushes run in O(log k).
    # Since we march over (at most) n elements, the
    # complexity of this loop is O(n log k).
    while index + window_width < len(a):
        result_array.append(heappop(window_heap))
        heappush(window_heap, a[window_width + index])
        index += 1

    # Dump the leftovers to the end of the result array:
    # Runs in O(k log k)
    while window_heap:
        result_array.append(heappop(window_heap))

    return result_array

You can find the entire test snippet here. Hope that helps.


I would have just gone for an if/else, this really isn't a good use case for a case statement and I've never seen anyone use a hash like that except for demonstration purposes:

def choose(value)
  if value < LOWER_LIMIT
    'a'
  elsif value <= UPPER_LIMIT
    'c'
  else
    'b'
 end
end

or possibly using a ternary

def choose(value)
  value < LOWER_LIMIT ? 'a' : value <= UPPER_LIMIT ? 'c' : 'b'
end

note that I find it easier to keep my conditions in ascending order.

If this is a common pattern I would consider extending ranges.

class Range
  def case(value, less, in, more)
    if value < first
      less
    elsif include?(value)
       in
    else
       more
    end
  end
end

(LOWER_LIMIT..UPPER_LIMIT).case(value, 'a', 'c', 'b')


Reading arbitrarily long lines from a file that is redirected as input

What can I do to reduce my code as I feel that it is getting too bloated.

No need for test.  Just call free();.  It handles free(NULL);

// if(strDate != NULL) {
//  free(strDate);
// }
free(strDate);

Minor: Style: I found the vertical spacing excessive creating challenges seeing the overall flow.  YMMV

What did I forget to do, what didn't I do right and what did I do that was unnecessary.

Certain functional error, lines is assigned a value that is not used.  Need to pass a "reference".

int expand(char **lines, size_t *lineMax) {
  char **tmp = realloc (...);
  ...
  lines = tmp;
  ...
  return SUCCESS;
}

Functional error (possible part of your "One small problem." comment).  If fgets() returns NULL, code should only dispose of the buffer if this is the first fgets() in readLine().  Or: if the reason for NULL is due to ferror() and not feof().
Functional corner case: strchr(buffer searches the buffer and can get fooled by fgets() reading a null charter and then a end-of-line such as "\0\n".  No true way to solve this and still use fgets().

  newLineFound = strchr(buffer + size, '\n');
}
while(!newLineFound && (size += BUFSIZ - 1));

Minor: Format to the presentation width.

// avoid
int allEntries = FALSE, errorStatus = FALSE; // errorStatus is so I can report memory failures.

// better
// errorStatus is so I can report memory failures.
int allEntries = FALSE, errorStatus = FALSE;

Use bool.  It is standard and well defined.

#include <stdbool.h>
// int allEntries = FALSE, errorStatus = FALSE;
bool allEntries = false, errorStatus = false;

Not all stderr are unbuffered. Suggest appending '\n' to your print to insure timely display.  Note either call below may make the same code with smart compilers.  2nd has the advantage of no problems with '%'

// fprintf (stderr,"Error, couldn't allocate any more memory.");
fprintf(stderr,"Error, couldn't allocate any more memory.\n");
// or
fputs("Error, couldn't allocate any more memory.\n", stderr);

Confusing code: simplification suggestion

// char **tmp = realloc (lines, (*lineMax) * 2 * sizeof(*lines));
size_t newsize = *lineMax * 2;
void *tmp = realloc (lines, sizeof(*lines) * newsize);
....
*lineMax = newsize;

Lost memory

char **tmp = realloc (lines, (*lineMax) * 2 * sizeof(*lines));

if(!tmp) {

  // Add
  free(lines);

  return MEMFAILURE;
}

Functional corner case:  If *lineMax could ever be 0.  Returning NULL is OK when the size of 0 and not a MEMFAILURE.

char **tmp = realloc (lines, (*lineMax) * 2 * sizeof(*lines));

// if(!tmp) {
if(!tmp && *lineMax) {
      return MEMFAILURE;
}

Functional: To be more resilient, check size before using the array.  getDates() does not control input of the count/size.

// move here
if((*numOfLines) >= (*lineMax)) ...

lines[*numOfLines] = strDate;
(*numOfLines)++;

// if((*numOfLines) == (*lineMax)) ...

Performance tips are welcome.

I/O is often a candidate for speed improvements.  For this code, if there is no other calls to stdin, I would use fread() and then process the lines  myself, reading large blocks.
On systems that use '\n' translation, improvement can be had by reading in binary mode.
When a file ends without a final '\n', code is probably faster  appending one, insuring the rest of code does not have to check for that expectation.

GTG


Vue + Vuex + Firebase serverless realtime chat

The code looks pretty straight-forward and I don't spot any obvious simplifications. I would suggest that you add error handling - especially for the case when uid is not null and remains that way. Perhaps an error message should be added if the request for the appropriate value fails.

Since ecmascript-6 is used (e.g. with the template literals) const could be used instead of var for any variable that doesn't get re-assigned (e.g. the components, db, etc.) and let for other variables (e.g. uid).

You could also consider providing a key attribute on the v-for where the messages are displayed, but the markup is quite simple for those so it may not add any benefit.

  It is recommended to provide a key with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.1

1https://vuejs.org/v2/guide/list.html#key


Defining pipelines of functions when passing a main argument across multiple functions

Without being familiar in use of sklearn, there are still some Python fundamentals that can be improved:
Superfluous comprehension
func_args = [k for k, v in inspect.signature(func).parameters.items()]

can probably be
func_args = inspect.signature(func).parameters.keys()

assuming that parameters has the interface of a regular dictionary. Also, since you're only using it to test membership, wrap it in a call to set().
Set intersection
If you do the above and make func_args a set, then this:
for k in dict(kwargs) if k in func_args

can be replaced by set(kwargs.keys()) & func_args.
Non-repeatable read
There's a potential issue with your use of pop(). This modifies your kwargs in a loop. Are you sure that you want a given kwarg to only apply to one function in your pipe, and not all of them?
Real tests
Convert this:
example_pipe= create_sequential_pipe([example_func_1, example_func_2, example_func_3])

out = example_pipe(2)
print(out)  # 2.0

out = example_pipe(2, power=2, sum=1, divide=5)
print(out)  # 1.0

into an actual unit test - you're already most of the way there, so you might as well.
Variadic function
create_sequential_pipe(func_list):

is a good candidate for being turned into a variadic function, i.e. accepting *func_list. This will make invocation simpler in some cases, including the one you showed at the bottom - there will be no need for an inner list literal.


Check if array A contains all elements of array B and vice versa irrespective of order

You can check this by keeping track of each value in a dictionary: adding one for items in the first array, subtracting one for items in the second array and finally checking that all tracked values are zero.

Also, implemented this way, there is no need to make the method array- or int-specific.

public static bool CheckEquality<T>(IEnumerable<T> first, IEnumerable<T> second)
{
    var dictionary = new Dictionary<T, int>();

    Action<IEnumerable<T>, int> setCounts = (items, change) =>
    {
        foreach (var item in items)
        {
            int count;
            // if not found, count will be the default value of 0
            dictionary.TryGetValue(item, out count);
            dictionary[item] = count + change;
        }
    };

    setCounts(first, +1);
    setCounts(second, -1);

    return dictionary.Values.All(value => value == 0);
}

The code is more complicated than sorting arrays, but it's also \$O(n)\$.