Before presenting my solution, I would like to quickly review your code. The first thing that popped into my mind was the extensive use of the keyword static, which I will address later together with your use of constants.

When looking over your code I have a hard time determining which variables and methods are different. All your variables start with the same characters. Your methods receiveLang() and receiveLanguage() easily creates confusion. What is it one does which the other don't? You also has a "silly assignment" where you write: $langUsed = self::$lang;. Since self::$lang is never changed you could use the static property and save a local variable. With that said I think your overall code looks good and your indentation is good. You could give more space and blank lines to increase readability though.

Pro Tip:

When using isset() you can reduce some of your conditionals to half the length. The difference between array_key_exists() and isset() is that isset() keeps going through keys even with multi-dimensional arrays. This means you could as an example reduce your first if condition in get() from:

if (isset(self::$langArray[self::$lang]) && isset(self::$langArray[self::$lang][$langString])) {...

to:

if(isset(self::$langArray[self::$lang][$langString])) {...

Now I would like to ask a question: why is your class completely static?. I know it's easier to interact with, but it also make testing your class harder.

I like your idea of using a file for each supported languages as it keeps concerns clear. But your use of constants that are defined outside your class, but is required lights some red warning signals to me. Consider me (another developer) or yourself in six months using this class. I could deduce that I need to provide a default path to languages files, but the default languages as well as the fallback language itself isn't so evident.

Considering your language class would only be used in a single view (right?), I would make this an instance class and provide the required constant values as parameters during construction to a __construct() method. Now if I would use your class I have to provide the required information. You would also have the benefit of (in some weird situation) having more than one language in your view as each instance would specify its preferred language.

Making the class an instance of course makes it more complicated to pass around the same instance, but it should be possible with a simple dependency manager.

I have written an alternative implementation of your class. It also implements a fallback language. The difference is that the solution I have written loads the fallback language first and then overwrites any language keys from the selected language. This makes the method for retrieving a language string much easier.

class Language {

    /**
     * @var array $language
     */
    private $language = [];

    /**
     * Create a Language instance.
     *
     * @param string $path     An absolute directory path to language files
     * @param string $used     A string declaring the language to use.
     * @param string $fallback A string declaring the default language.
     */
    public function __construct($path, $use, $default)
    {
        $this->language = $this->prepare($path, $use, $default);
    }

    /**
     * Determine if a language string exists.
     *
     * @param string $key
     *
     * @return bool
     */
    public function exists($key)
    {
        return array_key_exists($key, $this->language);
    }

    /**
     * Fetches the value of a language string associated with
     * the specified key.
     *
     * @param string $key
     *
     * @return string
     */
    public function fetch($key)
    {
        if($this->exists($key)) {
            return $this->language[$key];
        }

        /*
         * Throw an exception (preferred) or trigger an error/warning here; its your choice.
         *
         * I return an empty string to keep the return type consistent. You
         * can return NULL, but you would have to check the returned value
         * each time.
         */
        return '';
    }

    /**
     * Prepares the class by loading specified languages and
     * combining them into a single associative array.
     *
     * @param string $path
     * @param string $specified
     * @param string $fallback
     *
     * @return array
     */
    private function prepare($path, $use, $fallback)
    {
        /*
         * Load entire fallback language contents.
         */
        $language  = $this->load($path, $fallback);
        $overwrite = $this->load($path, $use);

        /*
         * I merge the language file recursively. The fallback language is
         * overwritten by the specified language.
         */
        return array_merge_recursive($language, $overwrite);
    }

    /**
     * Loads a language file and validates the returned contents
     * to an array.
     *
     * @param string $path
     * @param string $language
     *
     * @return array
     */
    private function load($path, $language)
    {
        /*
         * Build language filename.
         * An example format is: root/resources/languages/en.php
         */
        $filename = rtrim($path, '/') . '/' . strtolower($language) . '.php';

        if(!is_file($filename) || !is_readable($filename)) {
            throw new \RuntimeException("Cannot open language file: {$filename}");
        }

        $contents = require $filename;

        if(!is_array($contents)) {
            throw new \LogicException('Invalid language file structure. Expected an array.');
        }

        return $contents;
    }

}

This is a very crude implementation. You could easily build upon this, but the basics are there. You could even increase testability even more by extrating the load() and prepare() methods into a separate class. This class should only be responsible for loading your language files. You would then pass the loaded language as a parameter into the constructor

public function __construct(array $language) {...

Now consider testing this. You can now pass an array without loading any files and still test your class easily.

$array = [
    'welcome' => 'Welcome to this awesome site!'
];

$language = new Language($array);

I hope this can help you, happy coding!


Sorting by checking 2 distance away elements in a list, and check the method's accuracy

With python 2.7, you have xrange. The improvement in performance might be minimal (but an improvement nonetheless):

  The advantage of xrange() over range() is minimal (since
  xrange() still has to create the values when asked for them) except
  when a very large range is used on a memory-starved machine or when
  all of the range’s elements are never used (such as when the loop is
  usually terminated with break).

Split your \$ L \$ and use map as soon as possible.

L.append(map(int, raw_input().split()))

Swapping in python is as easy as:

a, b = b, a

No need to allocate a temporary dummy (and del it later):

if l[index] > l[index + 2]:
    repeat = True
    l[index], l[index + 2] = l[index + 2], l[index]

Now, for the time limit issue, since you know that you are actually sorting the even and odd indexes sublists disjointly; splice your \$ L \$ and sort those. Then, reattach them both by weaving them together.

# L has been read from user
l_even = sorted(l[::2])
l_odd = sorted(l[1::2])

and then join them together.


Fastest way to multiply two byte arrays in Java

Your code is somewhat hypothetical, in the example you give, it is 0 * 0, which will be pretty fast....

Still, let's put things in to perspective. You are performing 10 million loops in 1.5 seconds. A modern Intel CPU runs at 3.9GHz. In 1.5 seconds, that's about 6billion cycles (5.85 billion or so).

about 6 billion cycles for 10 million loops is about 600 cycles per loop. Now, in that loop, you are:

creating two byte arrays (OK, maybe you reuse those).
creating 2 BigInteger objects
running an add on those BigIntegers and computing a 3rd BigInteger
converting that third big-integer back to an array.
creating a ByteBuffer
copying the array content to the byte buffer
getting the byte buffer's internal array.

That is an amazing amount of work to do in 600 instruction cycles.I would expect the various object creates (three BigIntegers, two arrays, and a Buffer) are the most expensive things to do as they require multiple instructions, allocations/reservations, and registrations in the object creation, including CPU/cache management, etc.

Frankly, what you have is pretty good.

You could reduce the amount of work you are doing by completely removing the ByteBuffer from the last section. This code:

byte[] bytes = result.toByteArray();
ByteBuffer data    =  ByteBuffer.allocate(32);
System.arraycopy(bytes, 0, data.array(), 32 - bytes.length, bytes.length);

// expected 0x000000000000000000000000000000000000000000000000000000000000fe01
byte[] resultArray = data.array();

could instead be:

byte[] bytes = result.toByteArray();
if (bytes.length < 32) {
    byte[] tmp = new byte[32];
    System.arrayCopy(byte, 0, tmp, 32 - bytes.length, bytes.length);
    bytes = tmp;
}

But, what if the sum is more than 32 bytes?

Also, if you are at/near the limits, and you have negative input values, then you may end up with a negative result. I know your code appears to limit the negative impact by forcing a positive sign, but it could 'overflow' the 32 bytes.


Coq proof that type isomorphism relationship is transitive

You can make the proof a lot shorter by giving a constructor for the class Isomorphism and by destructing your arguments instead of inverting them:

Class Isomorphism A B :=
  MkIsomorphism {
    from: A -> B;
    to: B -> A;
    from_to x: from (to x) = x;
    to_from x: to (from x) = x
  }.

Definition compose {A B C} (f : B -> C) (g : A -> B) (x : A) : C
  := f (g x).

Definition trans {A B C} :
  Isomorphism A B -> Isomorphism B C -> Isomorphism A C.
Proof.
intros [AtoB BtoA AtoBtoA BtoAtoB] [BtoC CtoB BtoCtoB CtoBtoC].
apply MkIsomorphism
  with (from := compose BtoC AtoB)
       (to   := compose BtoA CtoB);
intro x; unfold compose.
 - rewrite AtoBtoA, BtoCtoB; reflexivity.
 - rewrite CtoBtoC, BtoAtoB; reflexivity.
Defined.


Wrapping WinAPI FindNextVolume as std iterator

This answer by another user to a similar question lists the whole set of features required by the Standard for a fully compatible iterator type. The list is quite long, and you probably won't need all those features, so this comment is mostly FYI.

You have chosen to make your class an Input Iterator, however, it is not fully compliant with the specification for such. It is missing the post-increment (it++) operator and the -> dereference operator, which are important and should at least be added.

The comparison operators are not const, which is a mistake, since they do not mutate member data. The proper signature would be, for instance with operator ==:

bool operator == (FindVolumeWrapper const& other) const;

Also, this calling syntax for operator == is not wrong, but it is unusual (though you've correctly reused it to implement !=):

 bool operator != (FindVolumeWrapper const& other)
 {
    return !operator == (other);
 }

I would expect this instead:

bool operator != (FindVolumeWrapper const& other) const
{
    return !(*this == other);
}

No special syntax, just a plain comparison.

This comparison is hard to read, too many conditions being checked at once:

bool operator == (FindVolumeWrapper const& other)
{
    return (this->m_dwError == ERROR_SUCCESS
            && other.m_dwError == ERROR_SUCCESS
            && wcscmp(m_curVolName, other.m_curVolName) == 0)
         || (this->m_dwError != ERROR_SUCCESS && other.m_dwError != ERROR_SUCCESS);
}

Some auxiliary variables would help:

bool operator == (FindVolumeWrapper const& other) const
{
    const bool bothGood = (this->m_dwError == ERROR_SUCCESS) &&
                          (other.m_dwError == ERROR_SUCCESS);
    const bool bothBad  = (this->m_dwError != ERROR_SUCCESS) &&
                          (other.m_dwError != ERROR_SUCCESS);
    const bool sameName = (wcscmp(m_curVolName, other.m_curVolName) == 0);

    return (bothGood && sameName) || bothBad;
}

Yes this will always evaluate all expressions, though the improvement in readability is still worth it in my book. The comparisons are negligible in any modern machine, so I wouldn't worry about that. The string comparison has the potential to be expensive, so if you really mind that, add an if to avoid wcscmp when the first condition is not met.

Instead of defining one constructor that takes a boolean and one that takes no parameters, with the objective of creating the start and end iterators, you could use a more descriptive method by defining two dummy types and using those instead. Example:

// These are empty, we just need the names
struct StartIteratorTag { };
struct EndIteratorTag   { };

class FindVolumeWrapper
{
public:
    FindVolumeWrapper(StartIteratorTag) { ... }
    FindVolumeWrapper(EndIteratorTag) { ... }
};

std::set<std::wstring> volumeNames(FindVolumeWrapper(StartIteratorTag()), FindVolumeWrapper(EndIteratorTag()));

Your current method is also not bad thought, this is just another alternative.

Finally, this SO question also discusses about iterator types, I recommend a look at it for further reference. And this one compares the Input/Forward Iterator types.


To illustrate my comment about accuracy, I wrote a small test program:

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

int main(int argc, char **argv) {
    unsigned long long n;
    double sum = 0;
    float fsum = 0;
    long double lsum = 0;

    if (argc > 1)
        n = strtoull(argv[1], NULL, 0);
    else
        scanf("%llu", &n);

    while (n > 0) {
        /* computing using double arithmetic */
        double m = 1.0 / n;
        sum += m;
        /* computing using float arithmetic */
        float fm = (float)1 / n;
        fsum += fm;
        /* computing using long double arithmetic */
        long double lm = (long double)1 / n;
        lsum += lm;
        n--;
    }
    printf("long double: %Lf\n", lsum);
    printf("double: %f, delta=%Lg\n", sum, lsum - sum);
    printf("float: %f, delta=%f\n", fsum, sum - fsum);
    return 0;
}

The following tests give this output:

~/dev/stackoverflow > time ./t41 10000000
long double: 16.695311
double: 16.695311, delta=-1.12868e-13
float: 16.686031, delta=0.009280

real  0m0.257s
user  0m0.244s
sys   0m0.004s

~/dev/stackoverflow > time ./t41 100000000
long double: 18.997896
double: 18.997896, delta=4.51783e-13
float: 18.807919, delta=0.189978

real  0m2.585s
user  0m2.558s
sys   0m0.010s

~/dev/stackoverflow > time ./t41 1000000000
make: `t41' is up to date.
long double: 21.300482
double: 21.300482, delta=1.79655e-12
float: 18.807919, delta=2.492563

real  0m25.287s
user  0m25.116s
sys   0m0.073s

My machine is not very fast, but it would take 10^13 seconds to complete the
calculation for 10^22 using your code.  Given the estimated age of the universe,
5.10^17 seconds, you should kill the process and think about a better algorithm.

Looking at the accumulated error for just 10^9 iterations between long double and double,
computing in double for 10^13 more iterations would given useless results.


What comes to the data structure, I don't think it gets any more efficient, not at least as long as you confine yourself to search by prefix. For that reason, I will "review" your actual code and not the algorithm.

self.isEnd = False

I believe more canonic name would be self.is_leaf. Note that isEnd is not idiomatic Python, is_end is.

You should have two empty lines before any class declaration.

import ...

class FooBar:
    pass

Also, in

for c,n in ...

PEP 8 requires a space after (each) comma:

for c, n in ...
      ^
    space!

What comes to renaming self:

def insert(self, word):
    node = self
    for w in word:
        node = node.children[w]
    node.isEnd = True

I would not do it, yet I have to admit that it is just an opinion.


In 1801, a guy called Carl Friedrich Gauss studied problems where the number line wrapped around, called Modular Arithmetic.

In his studies, he proved that:

$$
    (a \times b)\ \%\ n = [(a)\ \%\ n \times (b)\ \%\ n]\ \%\ n
$$

Also, 1000000007 is a prime number which means that there are other benefits...

And, it is also just less than half of Integer.MAX_VALUE.

Finally, two int values, no matter how large, when multiplied, will never be larger than Long.MAX_VALUE

Putting this all together, you can rewrite your code without the BigInteger math, something like:

for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
        if (j % B[i] == 0) {
            A[j] = (int)( ( (long) A[j] * C[i]) % 1000000007L);
        }
    }
}
System.out.println(Arrays.toString(A));

So, using some math, you can avoid the BigInteger problem entirely, and keep things as long and int values.

I imagine that this will be enough of a performance improvement to avoid the timeout.

Note, that for large numbers, BigInteger has \$O(s)\$ type complexity where s is the magnitude of the number, when doing multiplication. The bigger the number, the slower the product. Thus, your complexity for your current solution is \$O(nms)\$ where n is the size of the A array, m is the size of the B and C arrays, and s is the average size of the BigIntegers used. By reducing the problem to int-size values, we reduce the time complexity by a full order to just\$O(nm)\$.

There are likely ways for you to be able to solve the math in O(n) time as well.... I just need to think about how to restructure the if condition in the loops


count pairs of matching integers in a collection in Common Lisp

Stylistic consideration: a global variable is usually written with double "*" (earmuffs), so the global variable integers should be written as *integers*.
Now, for your questions.

I think your code is not particularly unidiomatic, just a little bit complex to read. What I find more unusual is your use of reduce to iterate over a list. In fact reduce is normally called with a binary function that takes pairs of elements of the same type, while you use it as a kind of iterator. In your case I would use a more classical iterator, like mapc, or, even better for me, loop. Another thing that I don't like is the use of the table to store also the global counter that will be used as result.

Summing all these considerations, I will rewrite your solution using
local helper functions, to reduce the complexity and simplify the
use of the parameters, and substitute the iterator while reducing by
one the number of auxiliary functions.
 (defun count-pairs (integers)
  (let ((pairs 0)
        (table (make-hash-table)))
    (flet ((make-pair (i)
             (incf pairs)
             (setf (gethash i table) nil))
           (keep-first-half-of-pair (i)
             (setf (gethash i table) t))
           (first-half-available-p (i)
             (gethash i table)))
      (loop for i in integers
        if (first-half-available-p i)
          do (make-pair i)
        else
          do (keep-first-half-of-pair i)))
    pairs))

If you need to return the table there is no other possibility. In the above solution this is not necessary, since table is not returned by the functions.

It's just a convention that you can follow or not. If you want to stick to Common Lisp common style, it is better to use the -p convention.

Yes.

Finally, for the fifth point, I would prefer a more concise solution, that counts all the elements, and only at the end counts all the pairs, in this way:
(defun count-pairs (integers)
  "returns the numbers the pairs of the list integers"
  (let ((table (make-hash-table)))
    (loop for i in integers
          do (incf (gethash i table 0)))
    (loop for v being the hash-value of table
          sum (truncate v 2))))


int count = remainingTasks.Count();

Since remainingTasks is a List, you can use the Count property here.

var exceptions = new List<Exception>();

This variable should be declared where it's used: in the if Interlocked.Decrement block.

if (task1.IsFaulted)

This means you're treating canceled tasks the same as successfully completed ones. Instead, you can check whether Exception is null.

You could also rewrite the inner foreach using LINQ:

var exceptions = remainingTasks
    .Select(task => task.Exception)
    .Where(e => e != null)
    .ToList();


Optimizing Sieve of Eratosthenes for larger numbers

Your question implies that you have a sieve of Erastosthenes, but you do not.

The sieve works from known-primes forward to a value with a given magnitude.

In other words, you start with a known prime (2), and then you eliminate all the multiples of 2 until you get to the end-point of the sieve. Then, you move forward from that known prime, to the next prime (which is the next number in your sieve that is prime). You then eliminate all multiples of that next prime too.

This ends up looking like a 2-stage process with a setup stage, and a double-loop stage.

Your code has a setup stage that is not used, and then has a three-loop structure that does things back-to-front.

The setup stage creates the sieve, which is a fixed size, that needs to 'cover' the 'nth' prime, wherever that may be. You may have to cover more than the exact value, which is why the formula 2*nthPrime*(int)Math.log(nthPrime) looks handy, but you should investigate this Wikipedia article about the approximate value of the Nth prime

So, once you have a large enough 'sieve', you then loop through it as follows:

for (int possiblePrime = 2; i < sieve.size; possiblePrime++) {
    if (sieve[possiblePrime]) {
        for (int notPrime = possiblePrime * 2; notPrime < sieve.size; notPrime += possiblePrime) {
            sieve[notPrime] = false;
        }
    }
}

Now, using those loops, you have a basic sieve of Eratosthenes, where all true values left in the sieve are primes. If the sieve is large enough, and you count them as you find them, then you can pull the Nth prime easily.

Note that the basic algorithm can be optimized in a bunch of ways.


Sending a C++ array to Python/NumPy and back

1. Review

It's not recommended to use using namespace std; — the problem is that this imports all of the identifiers from std, and some of these may shadow names from other modules that you need to use. See this question on Stack Overflow.
The code doesn't check for success/failure of many of the functions it calls. These can all fail:

new long double[SIZE][SIZE]
PyArray_SimpleNewFromData
PyUnicode_FromString
PyTuple_New
PyTuple_SetItem
PyObject_CallObject

(and maybe others that I didn't spot).
There's no Py_DECREF for pArgs.
It would be possible to avoid constructing the argument tuple, by using PyObject_CallFunctionObjArgs instead of PyObject_CallObject.
Error messages should be written to standard error (cerr), not standard output.
It's clearer to use the macros EXIT_SUCCESS and EXIT_FAILURE from <cstdlib> instead of 0 and 1.
The code calls PyArray_NDIM and PyArray_SHAPE on np_ret without checking to see if this object is in fact an array. Call PyArray_Check first.
Using value initialization for int variables seems perverse to me. With int i{} you have to remember that the default constructor gives the variable the value 0. With int i = 0 there's no need to remember (and the code is no less efficient: the compiled code doesn't actually create a temporary 0 object and then call the int assignment constructor).
This code doesn't provide as much information about errors as it could. In particular, errors inside Python cause Python to create an exception object containing information about the error (see "Exception Handling"). It would be a good idea to print this object if it exists, by checking PyErr_Occurred and then calling PyErr_Print.
Each block of error handling code has to undo the effect of all the previous successful blocks of code. This makes the length of the function quadratic in the number of error cases! This is risky, because every time you change something, you have to adjust all the error cases accordingly, and it is very easy to forget (as in §1.3 above). Also, the pain of writing out all the error-handling code makes it tempting to skip error handling for functions that you believe are likely to succeed (as in §1.2 above).

See the revised code below for one way to arrange that each "undo" operation appears just once.

2. Revised code

This is untested, so probably has some errors.

int _tmain(int argc, _TCHAR* argv[])
{
    int result = EXIT_FAILURE;

    Py_SetProgramName(argv[0]);
    Py_Initialize();
    import_array();

    // Build the 2D array in C++
    const int SIZE = 10;
    npy_intp dims[2]{SIZE, SIZE};
    const int ND = 2;
    long double(*c_arr)[SIZE]{ new long double[SIZE][SIZE] };
    if (!c_arr) {
        std::cerr << "Out of memory." << std::endl;
        goto fail_c_array;
    }
    for (int i = 0; i < SIZE; i++)
        for (int j = 0; j < SIZE; j++)
            c_arr[i][j] = i * SIZE + j;

    // Convert it to a NumPy array.
    PyObject *pArray = PyArray_SimpleNewFromData(
        ND, dims, NPY_LONGDOUBLE, reinterpret_cast<void*>(c_arr));
    if (!pArray)
        goto fail_np_array;
    PyArrayObject *np_arr = reinterpret_cast<PyArrayObject*>(pArray);

    // import mymodule.array_tutorial
    const char *module_name = "mymodule";
    PyObject *pName = PyUnicode_FromString(module_name);
    if (!pName)
        goto fail_name;
    PyObject *pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if (!pModule)
        goto fail_import;
    const char *func_name = "array_tutorial";
    PyObject *pFunc = PyObject_GetAttrString(pModule, func_name);
    if (!pFunc)
        goto fail_getattr;
    if (!PyCallable_Check(pFunc)){
        std::cerr << module_name << "." << func_name
                  << " is not callable." << std::endl;
        goto fail_callable;
    }

    // np_ret = mymodule.array_tutorial(np_arr)
    PyObject *pReturn = PyObject_CallFunctionObjArgs(pFunc, pArray, NULL);
    if (!pReturn)
        goto fail_call;
    if (!PyArray_Check(pReturn)) {
        std::cerr << module_name << "." << func_name
                  << " did not return an array." << std::endl;
        goto fail_array_check;
    }
    PyArrayObject *np_ret = reinterpret_cast<PyArrayObject*>(pReturn);
    if (PyArray_NDIM(np_ret) != ND - 1) {
        std::cerr << module_name << "." << func_name
                  << " returned array with wrong dimension." << std::endl;
        goto fail_ndim;
    }

    // Convert back to C++ array and print.
    int len = PyArray_SHAPE(np_ret)[0];
    c_out = reinterpret_cast<long double*>(PyArray_DATA(np_ret));
    std::cout << "Printing output array" << std::endl;
    for (int i = 0; i < len; i++)
        std::cout << c_out[i] << ' ';
    std::cout << std::endl;
    result = EXIT_SUCCESS;

fail_ndim:
fail_array_check:
    Py_DECREF(pReturn);
fail_call:
fail_callable:
    Py_DECREF(pFunc);
fail_getattr:
    Py_DECREF(pModule);
fail_import:
fail_name:
    Py_DECREF(pArray);
fail_np_array:
    delete[] c_arr;
fail_c_array:
    if (PyErr_Check())
        PyErr_Print();
    PyFinalize();
    return result;
}


Generate HTML file from Handlebars template and data object

First things first - syntax:

Why is generate an async function? You should change the way the files are read. Please read the answers to this question: https://stackoverflow.com/questions/46867517/how-to-read-file-with-async-await-properly

Logic:

The _validate function checks integrity of your object. All the data it needs is available in the constructor and this is where this function should be called. Never defer throwing an exception if you cannot avoid it.

Structure:

As for what design to use - your class is doing multiple things at the same time. Reading a template file from disk is one thing - and it requires handling an asynchronous operation. Then there is template compilation - which in case of HBS is not asynchronous and there is rendering - not asynchronous again. I'd recommend to restructure the solution a bit:

Use one class to read a file and return you a compiled template object. In case you needed to reuse your template objects - do not read from disk on every template call.
The returned class (let's call this one HandlebarsTemplate) should take a string as its constructor input and attempt compiling it as HBS. If the template was not correct - you get an exception thrown on object creation.
Note that HandlebarsTemplate could be reused for templates coming from sources other than files e.g. database or just a string literal in the code.
The object HandlebarsTemplate should expose a method called generate(data). This method should attempt rendering data the with the compiled HBS template.
This way you get reusable template objects

This would be up to you if you want to read the template each time or store a compiled instance in memory. Both approaches have their pros and cons.


Parser written in PHP is 5.6x faster than the same C++ program in a similar test (g++ 4.8.5)

Always Profile Optimized Code.

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rper-measure

Use -O3 optimisation: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

Use a profiler: https://github.com/KDAB/hotspot

https://en.wikipedia.org/wiki/List_of_performance_analysis_tools

Reduce the duplication
string inPath = argv[1];
string outPath = argv[2];

std::ifstream inFile;
std::ofstream outFile;

inFile.open(inPath.c_str());
outFile.open(outPath.c_str());

to
std::ifstream inFile(argv[1]);
std::ofstream outFile(argv[2]);

Avoid string operations and allocations as much as possible. Prefer std::string_view if the string is only being read.

Remove string makeCSVLine(vector<string> splitLine) and use a formatter library like {fmt} https://github.com/fmtlib/fmt. Just to make the code prettier in
  outFile << makeCSVLine(split);

, you're paying with a significant time penalty. OR use the good old (discussed below) fprintf if that turns out to be faster. If there is not a significant time gain, follow the guidelines and use fmt + streams.
 fmt::print(<FILE*>,
           "{},{},{},{},{},{},{},{},{},{},{}\n",
           vec[0],
           vec[1],
           vec[3],
           vec[4],
           vec[5],
           vec[6],
           vec[10],
           vec[9],
           vec[11],
           vec[7],
           vec[32]);

Make it a macro or a lambda, or a function with inline attribute set if you want to use it with other answers but in a separate block of code.
See speed tests by fmt also. source file

vector<string> splitStr(string line, const char delimiter = ',')
Avoid returning the vector and pass it by reference to fill it inside the function ( return type will be void). This makes it Return Value Optimisation independent. All compilers will treat it the same way.
Also, consider using .reserve(), and/or .emplace_back() for the vector. reserve() has been tested to improve performance.

Use stringstream + getline with a delimiter. If you doubt that this is time costly, profile. Don't guess the performance results, measure them.
void split_by_delim(const string &string, char delim, vector<string> &r_out)
{
  std::stringstream ss(string);
  string word{};   // reserve space if you can guess it right.
  while (std::getline(ss, word, delim)) {
    if (!word.empty()) {
       r_out.push_back(word);
    }
  }
}

Avoid fstreams iff the reader or writer are the biggest time sinks. fprintf has been 40% faster in my tests with no loss in flexibility (I used it for writing ints and floats, it may vary(edit: yes it varied and the gain is insignificant compared to the other benefits of streams (or with fmt) ) with strings.).
Re comments that Stream IO is as fast as printf family IO, take it from Herb Sutter & Bjarne Stroustrup:

It is often (and often correctly) pointed out that the printf() family has two advantages compared to iostreams: flexibility of formatting and performance. This has to be weighed against iostreams advantages of extensibility to handle user-defined types, resilient against security violations, implicit memory management, and locale handling.
If you need I/O performance, you can almost always do better than printf().

Emphasis mine.

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-streams

In the current code, the reading speed (getline()) is bound by splitting the string and the write speed. In other words, more lines cannot be read as long as file writer has not done its job. You're not using the disk's read speed to the full potential here.
Consider splitting them such that all reading is done at once and data is stored in memory and it is written out at once.
If you want to keep peak memory usage to minimum, make use of threads and separate the reader and the (splitter + writer) in asynchronous threads.

Addendum
Machine: MacBook Air 2017, macOS Mojave, MQD32LL https://en.wikipedia.org/wiki/MacBook_Air#Technical_specifications_2
Profiler: Instruments.app.
Compiler: Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Flags: -Ofast (and linking with {fmt} where required.)
PHP: 7.1.23 (cli) (built: Feb 22 2019 22:19:32) ( NTS )

Writer code to make CSV file, derived from Edward's answer for consistency: https://ideone.com/gkmUUN
Note that close enough timings should be considered the same due to fluctuations which can affect 3 to 5 seconds by a lot.
Matthew's code with the knowledge of line length and word length: 2.6s
Matthew's code as of rev 1 : 2.7s
Edward's algorithm with char array storage & {fmt}: https://ideone.com/Kfkp90. This depends on the knowledge that the incoming CSV has a maximum line length of 300 characters and a maximum word length of 20 characters. 2.8s.
Martin's code as of rev 7: 2.8s
For less bug-prone code, and dealing with unknown length strings: https://ideone.com/siFp3A. This is Edward's algorithm which uses {fmt}. 4.1s.
gdate +%s.%3N && php parser.php && gdate +%s.%3N where parser.php is in Edward's code as of rev 5 : 4.4s
Edward's code as of rev 1: 4.75s
Edward's code with fprintf https://ideone.com/0Lmr5P : 4.8
OP's code with basic optimisations, and fprintf https://ideone.com/5ivw9R : 5.6s
OP's C++ code posted in the question: 6.2s
OP's C++ code with -O2: 6.4s
OP's C++ code with -O0: 45s


Update only specific field of specific item (data) in List from YAML

I don't like that I need to provide all other fields in changing node
  alike (location x) etc...

You can "update" a field of a record like so:

where enR x = if rep == location x then x { hash = Just hash } else x

I would recommend against names like fnm, dat, ed, enR, etc. You should also use consistent casing (postRebuild instead of post_rebuild).


Creating consecutive words from a string

As @Michael Szyndel mentioned in a comment, Array#combination is the more appropriate method to use.

def get_separated_tokens query
  tokens = query.split
  (0..tokens.size).to_a.combination(2).map{ |i,j| tokens[i...j].join " " }
end


It looks good! Just a couple of points.

Instead of

let data = sr.ReadToEnd()
data

you can write

sr.ReadToEnd()

sprintf is more idiomatic than String.Format.
displayExchangeRate would be better written as a loop or using
List.iter (or Seq.iter).
DataContractJsonSerializer.WriteObject uses Encoding.UTF8, but you're decoding with Encoding.Default, which returns the OS's current ANSI code page.


Searching for the closest "stop" elements surrounding a start point

There is an overload of .indexOf that takes a second parameter indicating the starting location for the search.  That can be used to find the stop after starthere. Then you can use .slice to grab the part of the array before starthere with lastIndexOf to find the stop that comes before:

var i = arr.indexOf('starthere');
var stopafter = arr.indexOf('stop', i);
var stopbefore = arr.slice(0, i).lastIndexOf('stop');
document.write(stopbefore + '</br>' + stopafter);


First, you seem to have a minor typo on this line:

if (type == typeof(ushort)) return BitConverter.ToUInt32(bytes, offset).As<T>();

That should be:

if (type == typeof(ushort)) return BitConverter.ToUInt16(bytes, offset).As<T>();

Just as well, you have a bug in here that is a pretty big one (causes exception on any attempts to convert anything to sbyte with your method):

if (type == typeof(sbyte)) return bytes[offset].As<T>();

Should be:

if (type == typeof(sbyte)) return ((sbyte)bytes[offset]).As<T>();

If you really need speed, you should probably not use the BitConverter class in this situation. Use bitwise operators, as they are much faster.

See this answer for a comparison.

You should also not use .As<T> either, and instead cast within the method using: (T)(object). This eliminates unnecessary stack overhead.

Two improvements we can make immediately:

Replace all the BitConverter work with bitwise work.
Replace all the .As<T>() with (T)(object) casts instead.

Performance Evaluation

The performance difference, when those changes are made is significant for certain types of T.

ConvertTo1<byte> on 50000000 rounds, time (in ms) taken: 3465
ConvertTo1<short> on 50000000 rounds, time (in ms) taken: 4217
ConvertTo1<int> on 50000000 rounds, time (in ms) taken: 5586
ConvertTo1<long> on 50000000 rounds, time (in ms) taken: 7665
ConvertTo2<byte> on 50000000 rounds, time (in ms) taken: 4995
ConvertTo2<short> on 50000000 rounds, time (in ms) taken: 5775
ConvertTo2<int> on 50000000 rounds, time (in ms) taken: 6945
ConvertTo2<long> on 50000000 rounds, time (in ms) taken: 8492
ConvertToInt on 50000000 rounds, time (in ms) taken: 1092

Verifying results of conversions are same:
SByte test: 1, 1: True
Byte test: 1, 1: True
Short test: 10497, 10497: True
UShort test: 10497, 10497: True
Int test: 755378433, 755378433: True
UInt test: 755378433, 755378433: True
Long test: 4041804345027995905, 4041804345027995905: True
ULong test: 4041804345027995905, 4041804345027995905: True

Now, to explain, ConvertTo1<T> is the optimized method, ConvertTo2<T> is the original, and ConvertToInt is a strongly-typed method for converting directly to int.

By removing .As<T>() and replacing with (T)(object), and replacing all the BitConverter work with bitwise work, we cut our work down to:

69% original time for byte
73% original time for short
80% original time for int
90% original time for long

Also note that we returned the exact same values for all situations.

Just how bad is performance dragging because of the boxing?

Badly. If we consider another method, ConvertTo3 which is strongly typed around an int parameter, we can come up with the following result:

ConvertToInt on 50000000 rounds, time (in ms) taken: 1034

Now that is with a method that only returns an int value.

This leads us to be able to conclude that, due to the boxing of the generic types, and recasting them, we lose a lot of performance. (Around 500% or so right-off-the-bat.) The issues isn't the fact that you use generics, the issue is that you use boxing several times within, which creates extra overhead.

Using an .As<T>() method

While it would make sense to think that this would be fairly quick, with no drawbacks, this is actually much slower than inline calls due to the overhead of having an additional method call. Replacing .As<T>() with (T)(object) right out of the gate gave us significant performance back. It may even be acceptable to only make that change and continue using BitConverter.

In fact, upon further research, it seems that if you replace the ConvertTo2 method I supplied with this variant:

    public static T ConvertTo2<T>(this byte[] bytes, int offset = 0)
    {
        var type = typeof(T);
        if (type == typeof(sbyte)) return (T)(object)((sbyte)bytes[offset]);
        if (type == typeof(byte)) return (T)(object)bytes[offset];
        if (type == typeof(short)) return (T)(object)BitConverter.ToInt16(bytes, offset);
        if (type == typeof(ushort)) return (T)(object)BitConverter.ToUInt16(bytes, offset);
        if (type == typeof(int)) return (T)(object)BitConverter.ToInt32(bytes, offset);
        if (type == typeof(uint)) return (T)(object)BitConverter.ToUInt32(bytes, offset);
        if (type == typeof(long)) return (T)(object)BitConverter.ToInt64(bytes, offset);
        if (type == typeof(ulong)) return (T)(object)BitConverter.ToUInt64(bytes, offset);

        throw new NotImplementedException();
    }

The performance difference between ConvertTo1 and ConvertTo2 is very minimal. (Though, removing the BitConverter work still does seem to make it slightly faster, the difference is very insignificant at this level.)

Food for thought.

Code

Here's the code I used for conversions:

public static class Extensions
{
    public static T ConvertTo1<T>(this byte[] bytes, int offset = 0)
    {
        var type = typeof(T);
        if (type == typeof(sbyte)) return (T)(object)((sbyte)bytes[offset]);
        if (type == typeof(byte)) return (T)(object)bytes[offset];
        if (type == typeof(short)) return (T)(object)((short)(bytes[offset + 1] << 8 | bytes[offset]));
        if (type == typeof(ushort)) return (T)(object)((ushort)(bytes[offset + 1] << 8 | bytes[offset]));
        if (type == typeof(int)) return (T)(object)(bytes[offset + 3] << 24 | bytes[offset + 2] << 16 | bytes[offset + 1] << 8 | bytes[offset]);
        if (type == typeof(uint)) return (T)(object)((uint)bytes[offset + 3] << 24 | (uint)bytes[offset + 2] << 16 | (uint)bytes[offset + 1] << 8 | bytes[offset]);
        if (type == typeof(long)) return (T)(object)((long)bytes[offset + 7] << 56 | (long)bytes[offset + 6] << 48 | (long)bytes[offset + 5] << 40 | (long)bytes[offset + 4] << 32 | (long)bytes[offset + 3] << 24 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 1] << 8 | bytes[offset]);
        if (type == typeof(ulong)) return (T)(object)((ulong)bytes[offset + 7] << 56 | (ulong)bytes[offset + 6] << 48 | (ulong)bytes[offset + 5] << 40 | (ulong)bytes[offset + 4] << 32 | (ulong)bytes[offset + 3] << 24 | (ulong)bytes[offset + 2] << 16 | (ulong)bytes[offset + 1] << 8 | bytes[offset]);

        throw new NotImplementedException();
    }

    public static T ConvertTo2<T>(this byte[] bytes, int offset = 0)
    {
        var type = typeof(T);
        if (type == typeof(sbyte)) return ((sbyte)bytes[offset]).As<T>();
        if (type == typeof(byte)) return bytes[offset].As<T>();
        if (type == typeof(short)) return BitConverter.ToInt16(bytes, offset).As<T>();
        if (type == typeof(ushort)) return BitConverter.ToUInt16(bytes, offset).As<T>();
        if (type == typeof(int)) return BitConverter.ToInt32(bytes, offset).As<T>();
        if (type == typeof(uint)) return BitConverter.ToUInt32(bytes, offset).As<T>();
        if (type == typeof(long)) return BitConverter.ToInt64(bytes, offset).As<T>();
        if (type == typeof(ulong)) return BitConverter.ToUInt64(bytes, offset).As<T>();

        throw new NotImplementedException();
    }

    public static int ConvertToInt(this byte[] bytes, int offset = 0)
    {
        return (bytes[offset + 3] << 24 | bytes[offset + 2] << 16 | bytes[offset + 1] << 8 | bytes[offset]);
    }

    public static T As<T>(this object o)
    {
        return (T)o;
    }
}

And the test code:

public class CR_101636
{
    public static void _Main(string[] args)
    {
        var rounds = 50000000;
        var bytes = new byte[] { 1, 41, 6, 45, 163, 95, 23, 56 };

        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            byte result = bytes.ConvertTo1<byte>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1<byte> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            short result = bytes.ConvertTo1<short>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1<short> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            int result = bytes.ConvertTo1<int>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1<int> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            long result = bytes.ConvertTo1<long>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo1<long> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            byte result = bytes.ConvertTo2<byte>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2<byte> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            short result = bytes.ConvertTo2<short>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2<short> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            int result = bytes.ConvertTo2<int>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2<int> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            long result = bytes.ConvertTo2<long>(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertTo2<long> on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        sw.Start();
        for (int i = 0; i < rounds; i++)
        {
            int result = bytes.ConvertToInt(0);
        }
        sw.Stop();
        Console.WriteLine("ConvertToInt on {0} rounds, time (in ms) taken: {1}", rounds, sw.ElapsedMilliseconds);
        sw.Reset();

        Console.WriteLine("");
        Console.WriteLine("Verifying results of conversions are same:");

        Console.WriteLine("SByte test: {0}, {1}: {2}", bytes.ConvertTo1<sbyte>(), bytes.ConvertTo2<sbyte>(), bytes.ConvertTo1<sbyte>() == bytes.ConvertTo2<sbyte>());
        Console.WriteLine("Byte test: {0}, {1}: {2}", bytes.ConvertTo1<byte>(), bytes.ConvertTo2<byte>(), bytes.ConvertTo1<byte>() == bytes.ConvertTo2<byte>());
        Console.WriteLine("Short test: {0}, {1}: {2}", bytes.ConvertTo1<short>(), bytes.ConvertTo2<short>(), bytes.ConvertTo1<short>() == bytes.ConvertTo2<short>());
        Console.WriteLine("UShort test: {0}, {1}: {2}", bytes.ConvertTo1<ushort>(), bytes.ConvertTo2<ushort>(), bytes.ConvertTo1<ushort>() == bytes.ConvertTo2<ushort>());
        Console.WriteLine("Int test: {0}, {1}: {2}", bytes.ConvertTo1<int>(), bytes.ConvertTo2<int>(), bytes.ConvertTo1<int>() == bytes.ConvertTo2<int>());
        Console.WriteLine("UInt test: {0}, {1}: {2}", bytes.ConvertTo1<uint>(), bytes.ConvertTo2<uint>(), bytes.ConvertTo1<uint>() == bytes.ConvertTo2<uint>());
        Console.WriteLine("Long test: {0}, {1}: {2}", bytes.ConvertTo1<long>(), bytes.ConvertTo2<long>(), bytes.ConvertTo1<long>() == bytes.ConvertTo2<long>());
        Console.WriteLine("ULong test: {0}, {1}: {2}", bytes.ConvertTo1<ulong>(), bytes.ConvertTo2<ulong>(), bytes.ConvertTo1<ulong>() == bytes.ConvertTo2<ulong>());
    }
}

In your Program (or wherever):

CR_101636._Main(args);


The major question you should be asking is "what am I going to do with these bitmaps"? Threading is an issue when you have multiple threads writing the same data - multiple threads reading the same data (and only reading it) don't cause such problems. Whether you are going about this the correct way or not depends heavily on the answer to that question.

However, some of this code can be cleaned up and improved somewhat, regardless of that answer.

Calling mutex_.lock() and then explicitly calling mutex_.unlock() is dangerous. If anything in between those calls throws an exception, then your mutex will never be unlocked, and you'll have a deadlock. Solving this is easy, and just requires using what is known as RAII (Resource Acquisition is Initialization). In this case, this is done by using a std::lock_guard:

  static std::shared_ptr<Bitmap> loadBitmap(const std::string& filePath) {
      std::lock_guard<std::mutex> guard(mutex_);
      ...
  } // mutex_ is unlocked as soon as it goes out of scope

This ensures that mutex_ will always be unlocked, no matter how the function exists (whether normally or through an exception).

You use auto in a few places, so you might as well simplify:

std::unordered_map<std::string,std::shared_ptr<Bitmap>>::iterator delIter = cache_.end();

to:

auto delIter = cache_.end();

The loadBitmap function itself has dubious design. It isn't just loading a bitmap, but is also trying to clean out the cache. Performing this second step should absolutely be broken out into a separate function:

void remove_from_cache()
{
    if (cache_.size() >= kSlotThreshold) {
    auto delIter = cache_.end();
    for (auto iter = cache_.begin(); iter != cache_.end(); ++iter) {
        auto& item = *iter;
        if (item.second && item.second.use_count() == 1) {
            delIter = iter;
            break;
        }
    }
    if (cache_.end() != delIter) {
        (*delIter).second.reset();
        cache_.erase(delIter);
    }
}

The current cache size is very small (20 elements). If you expect this to remain small (< 1000 elements), you may want to consider using a std::vector instead. At this size, constants involved in the O(1) lookup for a hashmap dominate, and std::vector will (potentially) be quicker. If you expect many more lookups than insertions, a sorted vector could also work.

The reason I suggest is that this would make clearing out the cache much easier: using a std::vector (which would look something like std::vector<std::pair<std::string, std::shared_ptr<Bitmap>>> (which could really do with a using statement or 3)), then erasing values is simply:

using pair_t = std::pair<std::string, std::shared_ptr<Bitmap>>;
using container_t = std::vector<pair_t>;
container_t cache;

void remove_from_cache()
{
    if(cache.size() > kSlotThreshold) {
        cache.erase(std::remove_if(cache.begin(), cache.end(),
             [](const pair_t& p) { return p.second.use_count() == 1; }),
             cache.end());
    }
}

Whether this removal algorithm is any good or not is up for some debate, you might want to look at something like an LRU (least recently used) cache instead - currently, there is no guarantee that your algorithm will remove things from the cache. Also, this would require a (very minor) change to your lookup code:

 auto iter = cache_.find(filePath);

would become:

 auto iter = std::find_if(cache.begin(), cache.end(),
     [&](const pair_t& p) { return p.first == filePath; });

A few final small points:

Prefer to use std::make_shared instead of constructing the shared pointer directly, for example:

std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));

should be:

auto newPtr = std::make_shared<Bitmap>(filePath);

If you're defining a struct just to give things a scope to live in (and hence using static for everything), use a namespace instead.


Signed integer-to-ascii x86_64 assembler macro

The trick to not counting -0x80000000 as a negative number is to use unsigned division.  IDIV is signed, DIV is unsigned.
One option to consider: If you fill the buffer from the end and output the pointer to the start of the data, then you don't need to relocate things.  Admittedly, this makes it harder to use in some cases.
You might be better using DI (instead of R12) to hold your output address, and STOSB to store a character there.  It not only writes the character, but increments DI.


Minimum Value evenly divisible by all integers from 1 to n

Your code can be more pythonic.

Names of variables and functions should be more meaningful and descriptive. Also - read PEP8.
You should encapsulate your code in smaller functions responsible
for one thing. And signal what is the purpose of each function by
it's name (= meaningful names).
Use power which python gives you. To save memory instead of range() use xrange() in every case when you only need to iterate over. range() creates a list, so if you do range(1, 99999) it creates a list in memory with 99999 elements. In contrast xrange() is a sequence object that evaluates lazily.
There are more efficient algorithms than brute-force. But even your
brute-force approach can be improved. With xranege() you don't
need recursion any more. What is more it's wiser to iterate over
dividers in decreasing order. Which is dead simple in python, just use -1 as third xrange() parameter (step).

Take a look at this example:

def smallest_common_multiple(maximal_divisor):
    for number in xrange(maximal_divisor, sys.maxsize):
        if is_common_multiple(number, maximal_divisor):
            return number

def is_common_multiple(number, maximal_divisor):
    for divisor in xrange(maximal_divisor, 1, -1):
        if number % divisor != 0:
            return False
    return True

Comment:

In smallest_common_multiple() iteration starts from maximal_divisor because smaller numbers doesn't make sense. sys.maxsize works like to infinity.

:-)

Update

As Josay points out this can be even simpler. Thanks Josay!

from itertools import count

def smallest_common_multiple(maximal_divisor):
    for number in count(maximal_divisor):
        if is_common_multiple(number, maximal_divisor):
            return number

def is_common_multiple(number, maximal_divisor):
    return all([number % divisor == 0 for divisor in xrange(maximal_divisor, 1, -1)])


It seems like you should not be hard-coding concepts such as "kitchen", "garage", etc. into your code at all. You need to design that out.

Also I question the JSON structure.  sensor_* are meaningless property names, giving you an unnecessary level of nesting, so if you have control over JSON generation, you might consider an array of object like:

[
    {
        "location": ...,
        "temp_f": [
            ...
        ]
    },
    {
        ...
    }
]

But let's assume you can't do that, and think of ways we can get you the information make this whole thing more dynamic. I am not sure what params is even used for, so I am discarding this.

api.sensor_data.get(function(data){
    let sensorData = {};
    // loop through each sensoer object, ignore top level key value
    Object.values(data).forEach( (sensor) => {
        // reduce f_temp array to single entry with highest temp
        // and set to sensorData result object with location as key
        sensorData[sensor.location] = sensor.f_temp.reduce( (acc, metric) => {
            if(parseFloat(metric.value) > parseFloat(acc.value)) acc = metric;
            return acc;
        }, sensor.f_temp[0]);
    });

    $scope.sensorStats = sensorData;
}

Based on your comment regarding params, you might have something more like this:

    let sensorData = {};

    let sensors = Object.values(data);
    // filter by location
    if (location in params) {
        sensors = sensors.filter( (sensor) => sensor.location === params.location );
    }
    // loop through each sensor objects
    sensors.forEach( (sensor) => {
        let result = null;
        let metrics = sensor.f_temp;
        if(minTimestamp in params) {
            metrics = metrics.filter( metric => {
                return (Date.parse(metric.timestamp) >= params.minTimeStamp );
            });
        }
        if(maxTimestamp in params) {
            metrics = metrics.filter( metric => {
                return (Date.parse(metric.timestamp) =< params.maxTimeStamp );
            });
        }
        if(metrics.length > 0) {
        result = metrics.reduce( (acc, metric) => {
            if(parseFloat(metric.value) > parseFloat(acc.value)) acc = metric;
            return acc;
        }, metrics[0]);
       sensorData[sensor.location] = result;
    });

    $scope.sensorStats = sensorData;
}


Configuring toString via a public static variable

You could try to use Logger level to control verbose mode.

public String toString() {
    return toString(logger.isDebugEnabled());
}

public String toString(boolean verbose) {
    if (verbose) {
        return longDescription();
    } else {
        return shortDescription();
    }
}

Advantage of this approach is that it's easier to control toString() verbosity level - simply by config file for you logging framework, JMX extension, ...

This could also give you more flexibility - based on log level (INFO, DEBUG, TRACE), your could control how much information you put into toString().


This is some good looking code, there are just a few things that throw me. The first is that you're defining the integers but occasionally referring to them as "Nat"s. The natural numbers are non-negative integers, don't confuse the two.

toNat = toEnum :: Int -> ℤ
fromNat = fromEnum :: ℤ -> Int

This is a strange construction, give the type signature before the definition of the function and GHC will figure out which version of toEnum and fromEnum to use. Anything else is unusual and unnecessary.

Your Show instance should really just punt to the instance for Integers. Again, naturals numbers aren't integers so your "Nat: " tag is incorrect, it doesn't really add anything, and it makes writing a Read instance more difficult. Also there's no need to section infix functions by writing them prefix style. Thus:

instance Show ℤ where
    show = show . toInteger

instance Read ℤ where
    read = fromInteger . read

Your normalization function is more complex than it needs to be, but consider what having to normalize says about the representation you picked. Here's one version that doesn't change anything about your data types.

normalise = fromList . uncurry tailOfLonger . partition isOne . toList
    where
          isOne :: SimpleNat -> Bool
          isOne One = True
          isOne _   = False

          tailOfLonger :: [a] -> [a] -> [a]
          tailOfLonger    []     ys  = ys
          tailOfLonger    xs     []  = xs
          tailOfLonger (_:xs) (_:ys) = tailOfLonger xs ys

You have some unnecessary pattern match cases, such as n + Zero = n in the Num instance declaration. There's nothing wrong operationally with that case of course, but it's superfluous and the beauty of the inductive construction of the integers encourages me at least to be ruthless with flensing redundant code.

Here is an alternate construction that could obviate the need for all of the expensive normalization your version incurs. Writing the Num instance is pretty fun.

data Nat = Zero | Succ Nat

data Z = Negative Nat | NonNegative Nat


I read that function expressions aren't "hoisted"

Yes. See var functionName = function() {} vs function functionName() {}.

  so I can't get the proper values on $(document).ready

Why that? Unless the assignment to sameHeight did happen after the $(document).ready call, you can easily get the function.

  but I'm not sure how I could declare them with out making the code really messy and repetitive.

You already have declared them, they are hoisted and everything is fine. However, even if you did use function expressions:

var captHeight = function() {
    …
};
var sameHeight = function() {
    …
};
$(document).ready…

then everything would have been fine. Notice that, as @Flambino mentioned already in the comments, you can shorten the part where you install the event listener to

$(document).ready(sameHeight);

$(window).on('resize', sameHeight)
         .on('scroll', sameHeight);


A few comments:

import java.util.concurrent.*;

Never do wildcard imports unless you're doing a one-time, throw-away program. Maybe, in Java 20 or so, they introduce a class java.util.concurrent.Factorial (contrived example), and then you have a name collision with one of your classes. Better stick to individual imports (or have your IDE organize the imports).

Thumbs up for attaching javadoc to all public elements.

public long getFactorialWithRecursion(final int number) {
    return factorialRecursion(number);
}

I'd skip the indirection from getFactorialWithRecursion() calling factorialRecursion() and write

public long getFactorialWithRecursion(final int number) {
    if (number <= 0) {
        return 1;
    }
    return number * getFactorialWithRecursion(number - 1);
}

Other SO members already commented that computing a factorial with multiple threads might not be a useful application, but I understand that this is for exerecise purposes.

The while loop in getFactorialMultiThreaded makes it hard to read and understand the code, with the two loop variables startIndex and pivot having their operations spread over many lines of code. I'd write something like

for (int startIndex = 1; startIndex <= number; startIndex += JOB_SIZE) {
    int endIndex = Math.min(startIndex + JOB_SIZE - 1, number);
    partialFactorialJobs.add(new PartialFactorialJob(startIndex, endIndex));
}

Similar thing applies to the while loop in your call method, I'd prefer a for loop instead.

As your PartialFactorialJob class doesn't access anything from the enclosing Factorial instance, you should make it static (otherwise it carries around a useless internal reference to its enclosing instance, typically visible in your debugger as this$1 or similar).


Counting the amount of objects in an array that contain a certain key that doesn't have an empty value

Using String.replace means that you need to step over every character in every string you are testing. Not only that but it needs to allocate memory to hold the resulting new string.

Its much quicker if you test for a non white space characters. That way it need only test to the first non white space, and it needs no additional memory.

Also Object.hasOwnProperty is slow as it must work its way up the prototype chain to get an answer and should only be used if you think that the object you are testing has a prototype chain containing the property name you are testing.

Last point. This is not part of the code you have presented, but to improve the performance the property hour.description should not contain only white spaces. When you set that property vet it eg  hour.description = descriptionString.trim();

Thus If you have unvetted description strings

var i, count = 0;
for (i = 0; i < hours.length; i++) {
    count += hours[i].description && (/\S/).test(hours[i].description) ? 1 : 0;
}
return count;

Or

If the description has been vetted then the following will be the quickest

var i, count = 0;
for (i = 0; i < hours.length; i++) {
    count += hours[i].description ? 1 : 0;
}
return count;


Access an associative array value given an array of keys in PHP

Your code seems fine, but it's a bit verbose. You can make it more elegant with a foreach loop, clean up the way you exit the function, and if you're using PHP 5.6 or above you can use a real variable-length argument list. See:

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

class ConfigurationHandle
{
    protected static $configuration;

    <...>

    public static function get(...$arguments)
    {
        $value = &self::$configuration;
        foreach($arguments as $argument)
        {
          $value = &$value[$argument];
          if(empty($value)) return "";
        }
        return $value;
    }
}

I've written out full words, because there is no need to abbreviate. I think this code is more elegant, because it is easier to read and understand, but it is not more efficient.

It would be more efficient if you dumped the Config class altogether, and used a one dimensional array like this:

$configuration = ['DATABASE_SERVER' => 'localhost',
                  'DATABASE_NAME'   => 'adbname',
                  'DATABASE_USER'   => 'theuser',
                  'DATABASE_PASS'   => 'thepass'];

That is immeasurable more efficient, and might I say it's elegant too?

If top speed is not important to you, but multiple levels, and more control, are, then go for the class.


You can use Ruby's array intersection and check for matches. The empty string passed in your params is irrelevant.

def validate_audio_languages
    if audio_languages.any?
        enums = Language.languages.map(&:first)
        matches = enums & audio_languages.map!(&:downcase)
        matches.present? ? matches : errors.add(:audio_languages, "not a valid language selection")
    else
        errors.add(:audio_languages, "need to select a language")
    end
 end

You can shave off a couple more lines at the expense of readability, but it pays to keep things simple and readable.


Welcome to codereview. Here's a selection of suggestions.

num_generated = rand() % 3 + 1;

This is probably fine for this use case. Be aware that

rand() is generally agreed not to be random enough for many uses where you need a random number. Consider instead using the <random> header.
Using %3 to condense the spread of random numbers into 0 through 2 slightly biases the result. Consider what happens if rand() uniformly and randomly produced numbers between 0 and 4 and you used this approach: getting low values would be slightly more likely than getting high values.
rand() requires seeding with srand() or the results won't vary from run to run.
The + 1 goes from a range of 0 through 2 to a range of 1 through 3. That's not inherently a problem (it doesn't cause any issues with this program) but the very strong convention is that counting starts from 0. If, say, you had an array of moves and you used this random number to look up the array, one of the moves should be move 0.

Putting that in the constructor, specifically

Computer :: Computer(){
    num_generated = rand() % 3 + 1;
}

means that a given Computer object only ever produced one move. It would probably be better if you could reuse the same object.

public:
    Computer();
    void setMoveChoice();
    string getMoveChoice();
};

Consider setting up some sort of inheritance structure. If there was a base class Player which HumanPlayer and ComputerPlayer inherited from, it would be easier to write the program flexibly. You could have the same game logic, and swap in different sorts of players for PvP games, CvC simulations, and potentially new additions such as playing against another player on the internet.

move_selected = "rock";

For a problem like this, it's better to use integer (or better still enum) types. Keep strings for when the task is inherently about the text (including text input and output) rather than the thing the text represents. Among other things, strings are expensive to work with and tend to confuse the compiler in places where it would otherwise be able to help point out bugs.

On the topic of strings, there is a lot of redundancy in whoWon. Consider separating out the logic of working out who won from the logic of displaying it. Every output has the form.

cout<< "You chose " << player_move << " and the computer chose "<< computer_move <<", " << result <<endl;

A c++ specific issue:

using namespace std;

It is generally agreed that this should be avoided, especially in header files. Better to write std::string and such like in full. Otherwise there can be ambiguity (including in files that at some level include that header, which the programmer is not fully aware of) between functionality defined by the standard library and functionality defined by the programmer or third party libraries.

endl

C++ programmers generally prefer putting a newline (\n) into the string rather than using endl: endl both pushes a newline and forces the output buffer to flush. Only use it when you need the buffer to flush and the text to display immediately.

while(play_again == 'y'){

If you want to use a loop that always runs once, and then checks whether to run again at the end, consider a do { ... } while () loop instead. This avoids having to force the repeat condition before starting.


Displaying the number of elements larger than the average of an array

A few extra comments:

define main at the bottom so that prototypes are unnecessary
define local functions 'static'
if you are going to use EXIT_SUCCESS then also use EXIT_FAILURE
your comments are just noise (no useful information) and should be deleted
add a \n at the end of the final printf  (which is missing count)
you don't check for n being greater than SIZE, only for zero (although
the error printf says n is too big)
define loop variables in the loop and always use braces, even when not necessary:

for (int i=0; i<n; ++i) {
    // do something
}

findAverage and countAboveAverage should declare arr as const

static double findAverage(const int arr[], int n);

personally I'd avoid using unsigned types (suggested by @Sulthan) as it often
leads to unexpected arithmetic results.  If you do use it, make sure you
enable the necessary compiler warnings.


Perl script to rename multiple files with vi(m)

That is a nice and useful script, although a few things could be improved.

You specified the -w command line option. You should instead use warnings. While the result is identical for such a small script, the warnings pragma allows for fine-grained control of warnings.
You do not have to specify main:: when defining subroutines. When no package is specified, then you are already in the package main. Reduce the syntactic clutter, and simply write sub VERSION_MESSAGE { ... }.
In HELP_MESSAGE, I'd use the heredoc-marker differently: I'd prefer it to be <<'EOF'. Rationale: Double quotes allow interpolation of variables. For a reader of the code, this increases the cognitive load: where do you interpolate something? Nowhere. If I specify the marker with single quotes, I can just skip to the end marker; knowing that nothing interesting happens in between.

I'd also rather not put a space between the << and the 'END'. The heredoc-marker is syntactically one single token, and you can't specify the marker with other quoting operators like << q(END).

As we now use single quotes, no escapes are available, so your \n won't work any more. No problem, just use a literal newline:

<<'EOF';
Usage:
 virename [OPTIONS] [file_names]
...
EOF

for the same effect.
Why do you put the HELP_MESSAGE sub into the scalar $usage? You can invoke the sub directly like HELP_MESSAGE() instead of the much more complicated $usage->().
sub VERSION_MESSAGE { print "virename v0.1\n"; }. Nope. The documentation for Getopt::Std may not make this perfectly clear, but your VERSION_MESSAGE sub receives some paramaters. The first of these is the filehandle you are expected to print to. Error messages or information that is not the primary output of your script should generally not go to STDOUT, but to STDERR. So we will rewrite that to

# callback for Getopt::Std
sub VERSION_MESSAGE {
  my ($handle) = @_;
  print {$handle} "virename v0.1\n";
}

Notice also the comment that tells a reader why you put this seemingly unused sub here and why you chose a name in offending uppercase.

The same considerations hold for HELP_MESSAGE, which should be rewritten as well.
print "Not enough arguments!\n\n"; ...; exit 1. Nope.

First, what you are expressing is very close to die, so we'll rather use that. The above rant about how error messages shouldn't go to STDOUT applies here as well, but using die fixes that. But we would like to print out the usage without having to call a sub that prints it out. The solution is to put this message into a variable, e.g.

my $help_message = <<'EOF';
...
EOF

# callback for Getopt::Std
sub HELP_MESSAGE {
  my ($handle) = @_;
  print {$handle} $help_message;
}

Now we can say

@ARGV or die "Not enough arguments!\n\n", $help_message;
getopts 'vs', \%opts or die $help_message;

When an unknown flag is among the arguments and getopts returns a false value, I not only print the usage (as you do), but also terminate execution. I think this is preferable than continuing with possibly wrong arguments.
A comment here and there would not hurt. E.g.

if ( $opts{s} ) {
  # If a file is a symlink, we need to find the actual target
  # and put that into @names instead.
  ...
}

A short paragraph telling a reader what you are about to do can really help.
What the hell?

if ( !system "vim $tmp_name 2>/dev/null" ) {
}
elsif ( !system 'vi', $tmp_name ) {
}
else { exit; }

I do understand what you are trying to express, but it isn't exactly obvious. There is a nicer way to do that. Also, don't fail with a normal exit code when there clearly was an error, and don't exit abnormally without an error message!

system("vim $tmp_name 2>/dev/null") == 0
  or system("vi", $tmp_name) == 0
  or die "Can't launch vim or vi\n";

Note: Don't write code that isn't self-explanatory without a comment. Also, If you're using empty bodies for an if in Perl, this should raise an eyebrow.
chomp( @new_names = <$tmp> ); # Reading new names from tmp file

Thankyou for the comment, but that code is fairly self-explaining. Ergo, this comment is unneccessary.

As this is the first occasion where the @new_names variable is used, it should also be declared here, and not further upwards. This would work as well:

chomp( my @new_names = <$tmp> );

… altough others may not like embedding declarations inside an argument list. Then:

my @new_names = <$tmp>;
chomp @new_names;

exit if @names != @new_names;. I covered this already: Don't exit abnormally without reflecting this in the error code, and don't abort execution without an error message telling the user what went wrong:

@names == @new_names or die "Number of filenames changed. Did you delete a line?\n";

In the loop, you could consider changing the definition of $is_symlink to

my $is_symlink = $opts{s} && exists $symlinks{ $names[$_] };

This reduced a tiny bit of code duplicatation.
The following if/elsif/else confuses two unrelated topics: Loop control and error handling.

if ( -e $new_name ) {    #Skip if file already exists
    print "'$new_name' already exits!\n" if $opts{v};
} elsif ( rename $old_name => $new_name ) {
    ...
} else {
    warn ...;
}

If you want to move on to the next iteration of the loop, just use next:

if ( -e $new_name ) {
  print ... if $opst{$v};
  next;
}

I am not sure if what you are printing is considered regular output, or an error message. I assume it is normal output, so my STDERR ranting does not apply here.

Your rename and the correspondig error handling (in form of a warn) are seperated by a dozen lines. I would move them closer together:

rename $old_name => $new_name or do {
  warn ...;
  next;
};
...;

The __END__ marker is generally useless, unless you keep some non-code resources in the same file, or when you pipe the code to the perl interpreter. All this marker does is to stop the parsing of the source file.


Well, while the code surely works, it does look ugly. I would suggest something like this:

sequence [Just 5, Just 10, Just 100]

or, if you really want to use Applicatives instead of Monads,

sequenceA [Just 5, Just 10, Just 100]

from Data.Traversable.


Consider using existing template systems to help you that support inheritance. Template inheritance isn't a strict requirement, but is a powerful feature that makes maintaining templates a lot easier. Twig is easy to use, and feature-rich.

If you want to go it your own way, you could simply implement the use of layout files:

layout_default.php

<!DOCTYPE HTML>
<?php $root="/mywebdir"; ?>

<?php include("$root/inc/meta.php"); ?>
<meta name="description" content="<?php echo $description ?>" />
<meta name="keywords" content="<?php echo keywords?>" />
<title><?php echo $title ?></title>

<?php include("$root/inc/header.php"); ?>
<?php include("$root/inc/nav.php"); ?>

<?php echo $contents ?>

<?php include("$root/inc/footer.php"); ?>

example page.php

<?php ob_start() ?>

 main body html

<?php
$title = "x";
$description = "x";
$keywords = "x";
$contents = ob_get_clean();
require 'layout_default.php'

This is a very crude implementation, simply enough to illustrate the principle.


abstract class MergeSort

This class shouldn't be abstract, it should be static.

public static List<Node> Sort(List<Node> input)

Why does the method require List? Wouldn't it be better if it accepted any IList (or IReadOnlyList if you're on .Net 4.5)? Also, it would make sense to make your code generic, so that it would work on types other than Node.

List<Node> Result = new List<Node>();

The usual convention in C# is to name local variables in camelCase, not PascalCase.

return input;

Returning the input might be unexpected. If you don't want to change it, you should clearly document it.

Left.RemoveAt(0);

This is very inefficient operation for a List. Either use a collection that can do this efficiently (like LinkedList or Queue) or, even better, just use indexes instead of modifying the collection.

Your code also does a lot of copying and creating new lists. That's good for readability, but if you want your code to be fast, you need just two lists that you can modify.

You would need to work with sublists (list, start index, length), not whole lists. First, merge the 1-element sublists from list A to list B, then merge the 2-element sublists from B to A, etc.

Also, another optimization is not to start with 1-element sublists, but take advantage of the fast that there are likely to be some sorted sublists in the input already. This is especially effective if the input is already sorted (or mostly sorted). But I think it wouldn't work with your recursive approach.


Sort a scrambled itinerary (Google apac test problem)

Style notes:

The Ruby convention is 2 spaces of indentation
Use braces for single-line blocks, but do...end for multi-line blocks.
Keep the block parameters on the starting line; i.e. don't do this

(1..num_cases).each {
    |num|

Use #nil? rather than == nil, empty? when checking array lengths, #first/#last when accessing the start/end of an array, etc..
Postfix conditions for single-line, single-branch conditionals. E.g. this:

if arv == nil
    break #Done if we are out of tickets
end

becomes:

break if arv.nil? # Done if we are out of tickets

Instead of iterating through ranges like (0...n) you can use n.times instead. E.g. n.times { |i| puts i } will produce the same as (0...n).each { |i| puts i }
You missed a single pair of parentheses in a method call: .join ' ' :)
Granted, you can write Ruby without parentheses (Seattle style Ruby). Personally though, I like 'em (except for puts and print), but there are arguments for and against.

Code notes:

Instead of $stdin.readline.strip, you can use the more common gets.chomp. #gets is just a shortcut for $stdin.readline, and #chomp chops off the linebreak, but leaves other whitespace intact.

When possible use methods like #map and #reduce and their ilk instead of modifying a closed-over object from inside a block. E.g. this:

tickets = {}
# ...
(0...num_flights).each {
    tickets[$stdin.readline.strip] = $stdin.readline.strip
}

can be written in a few different ways - #each_with_object is probably the cleanest:

tickets = num_flights.times.each_with_object({}) do |_, tickets|
  tickets[gets.chomp] = gets.chomp
end

Alternatively, you could read the lines, and chunk them up afterward:

lines = (num_flights * 2).times { gets.chomp }
tickets = Hash[ lines.each_slice(2).to_a ]

You can do something similar in #print_flights instead of using step(2):

def print_flights(case_num, ordered_flights)
  tickets = ordered_flights.each_slice(2).map { |pair| pair.join("-") }
  puts "CASE ##{case_num}: #{tickets.join(" ")}"
end

Typically, Ruby coders avoid "raw" array indices and index arithmetic like array[i+1] in favor of more expressive code.

Lastly, #order_flights has side-effects: It deletes entries from the tickets hash you pass to it. Sure, it doesn't matter for this particular exercise, but side-effects are side-effects and should be avoided.

The algorithm itself looks fine to me. I might write it like so:

def read_tickets
  count = gets.chomp.to_i
  count.times.map do
    [gets.chomp, gets.chomp]
  end
end

def sort_tickets(tickets)
  flights = tickets.dup # make a copy to modify
  stops = flights.shift
  until flights.empty?
    from, to = flights.shift
    if from == stops.last
      stops.push(to) # could also use <<, but #push keeps "symmetry" with #unshift
    elsif to == stops.first
      stops.unshift(from)
    else
      flights.push [from, to]
    end
  end
  stops.each_cons(2).to_a
end

case_count = gets.chomp.to_i
case_count.times do |t|
  tickets = read_tickets
  ordered = sort_tickets(tickets).map { |ticket| ticket.join("-") }
  puts "Case ##{t+1}: #{ordered.join(" ")}"
end

Pretty much the same algorithm, just written differently. Notice however that I never actually use hashes, just nested arrays. Unfortunately, it's sloooow (the else branch and #each_cons are probably to blame, but I haven't checked). Still, style-wise it might give you some ideas.

An alternative, which does use hashes, would be to scan the tickets to find the first leg of the journey. After that, a single loop through should put them in order.

def read_tickets
  count = gets.chomp.to_i
  count.times.each_with_object({}) do |_, tickets|
    tickets[gets.chomp] = gets.chomp
  end
end

def print_sorted_tickets(tickets)
  inverted = tickets.invert
  from, to = tickets.detect { |from, to| inverted[from].nil? } # find first
  print " #{from}-#{to}"
  while tickets[to]
    from, to = [to, tickets[to]]
    print " #{from}-#{to}"
  end
  print "\n"
end

case_count = gets.chomp.to_i
case_count.times do |t|
  print "Case ##{t+1}:"
  tickets = read_tickets
  print_sorted_tickets(tickets)
end

I've combined sorting and printing only because I can. I'd prefer sorting and then printing, like above, or at least returning a string. The code can easily be changed to support that, but I figured I'd try combining the two. And this runs about as fast as your solution (somewhat surprisingly - I figured #invert would be more expensive).

By the way, one could "manually" create the inverse hash immediately when reading the input, instead of using #invert. But I don't think it'll make that much difference. Either case would be trading memory for simplicity.


Creation of MxM matrix: Python version much slower than Matlab version

You use very short variable names, so its hard to follow what your code is doing.

For speed in numpy, you need to use vector operations. So instead of writing

for ii in range(step):
    out[ii] = ii * x + b

You should write:

out = numpy.arange(step)*x + b

Individually accessing the elements of numpy array is actually quite slow. You need to write your code to do everything in vector operations.

Here is my rewrite of your inner loop to be vectorized. You could vectorize the outer loop as well, but this should make the biggest difference.

        f1 = int(bb[k][0])
        f2 = int(bb[k][1])
        f3 = int(bb[k][2])
        f4 = int(bb[k][3])

        ptj = np.arange(step_prob, 1.0 + step_prob, step_prob)[:, None]
        pfj = np.arange(step_prob, 1.0 + step_prob, step_prob)[None, :]

        out_t = f1*pti*ptj+f2*pti*(1-ptj)+f3*(1-pti)*ptj+f4*(1-pti)*(1-ptj)
        out_f = f1*pfi*pfj+f2*pfi*(1-pfj)+f3*(1-pfi)*pfj+f4*(1-pfi)*(1-pfj)
        sj = (1 - pfj + ptj) / 2

        the_max = np.maximum(sj, [si])
        s = ((1-out_f+out_t)/2)-the_max

        temp = s*(s>0)*np.tril(np.ones((len(s),len(s))).astype(int))
        improve[ii-1,jj-1]=improve[ii-1,jj-1]+temp.sum()


First of all, great that you used type annotations, as they're sometimes missing. However, there are some remarks:

"edge" and "general"` condition are usually called "base case" and "recursive case"
"base case" and "recursive case" aren't commented in Haskell code, as they are everywhere
split is generic enough to be defined at top-level
split has a little bit of duplication that we can remove with a single where clause
functions are usually named in camelCase instead of snake_case, so we'd call it quickSort.

If we apply that we end up with

quickSort :: (Ord a) => [a] -> [a]
quickSort []       = []
quickSort (x : xs) =
    let (lt, gt) = split x xs
    in  (quickSort lt) ++ [x] ++ (quickSort gt)

split :: (Ord a) => a -> [a] -> ([a], [a])
split x [] = ([], [])
split x (h : hs)
    | h <= x    = ( h : lt,     gt)
    | otherwise = (     lt, h : gt)
    where
        (lt, gt) = split x hs

That being said, split seems so helpful that there should be some function already in the standard library. And it turns out there is, namely partition :: (a -> Bool) -> [a] -> ([a],[a]) from Data.List:

split :: (Ord a) => a -> [a] -> ([a], [a])
split x = partition (<= x)

That's a lot cleaner than our own implementation. So how do we find partition if we don't know about it yet? We use Hoogle. However, a query for Ord a => a -> [a] -> ([a],[a]) does not yield partition. It's sometimes a good idea to generalize the query a little bit, for example to [a] -> ([a],[a]), as Hoogle also scans parts of the type signature. That way, we find partition.

If we're going for brevity, we can then inline split to gain

-- | Sorts the given list in an ascending order.
quickSort :: (Ord a) => [a] -> [a]
quickSort []       = []
quickSort (x : xs) =
    let (lt, gt) = partition (<= x) xs
    in  (quickSort lt) ++ [x] ++ (quickSort gt)

but that's up to personal preference, as the compiler will inline split anyway.


Getting a list of outdated versions with Python

Since everything is printed in order, the "obsolete" ones are all but the last version for the first word. That's tricky. But if we looked at the text backwards, we're printing all but the first one.

And that's easy with awk:

awk '!($1 in seen){print }{seen[$1] = 1}'

And then just invert the input twice:

run_your_version_cmd_here | tac | awk '$1 not in seen{print }{seen[$1] = 1}' | tac


Bug

The program doesn't count words correctly,
for example in "a     text   like this",
because it counts every whitespace character as a word,
without handling consecutive whitespace characters.

Reading character by character is inefficient

Reading a file character by character is not very efficient.
It would be better to use a buffered reader and process the file line by line.
Here's an example of doing that, which also solves the bug with word counting:

long[] counts = new long[3];
try(InputStream in = new FileInputStream(filename);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")))
) {
    String line;
    while ((line = reader.readLine()) != null) {
        counts[2]++;
        counts[1] += line.split("\\s+").length;
        counts[0] += line.length() + 1;
    }
}
return counts;

This might still not be accurate,
and probably there are corner cases where it will not count words correctly,
but it's still more accurate than the original.

Encapsulation

The implementation doesn't encapsulate well the results.
It returns a long[],
which is not great because you have to remember the array indexes that correspond to characters, words, lines, which is error prone.
Even if you add constants like CHARS_INDEX = 0, WORDS_INDEX = 1 to eliminate magic numbers,
it will not solve the encapsulation problem:
users of the function will know too much about the internal implementation,
that it uses a long[] for storage.
It would be cleaner to create a dedicated CountResult class to encapsulate the results.

For example:

private static class CountResult {
    private final long chars;
    private final long words;
    private final long lines;

    private CountResult(long chars, long words, long lines) {
        this.chars = chars;
        this.words = words;
        this.lines = lines;
    }
}

And then use it like this:

long chars = 0;
long words = 0;
long lines = 0;
while ((line = reader.readLine()) != null) {
    lines++;
    words += line.split("\\s+").length;
    chars += line.length() + 1;
}
return new CountResult(chars, words, lines);

Callers will not need to remember indexes,
the counts will be accessible intuitively by names.

Unused variables

You have some unused variables:

Reader buffer = new BufferedReader(reader)

String newLineChar = System.lineSeparator();

It would be better to remove them.


Modifying a Word document template with OpenXML

Using case-sensitive string matching like that is in my opinion the first nail in the coffin. Instead a case-insensitive dictionary would be a much better option.

Example:

var replacements = new Dictionary<string, Func<string>>(StringComparer.OrdinalIgnoreCase)
{
    ["Plan"] = () => $"{DateTime.Now.Year} Q2 Plan",
    ["Project Name"] = () => $"SUPER SECRET CODE NAME",
};

text.Text = replacements[text.Text]();

This is also much easier to extend/maintain.

You shouldn't mix full type names with var. You can use var not only for normal variables but also inside using statements or foreach loops. Keep it consistent.


C++ Template-Based ArrayList Implementation

Memory Allocation

This is a house built on sand, so to speak. Quite a bit of the house itself looks perfectly fine, but the foundation is completely rotten, so everything else is liable to fall over without notice.

The specific problem is using new [] to allocate storage. The problem with this is that it actually creates objects in the memory you allocate. If you're storing objects that are expensive to construct, this can impose unnecessary overhead. If you're storing objects that can't be default constructed...well, you're not storing those, because it just won't work.

The right (at least IMO) way to do this is to use the same strategy as vector does (at least by default). You allocate raw memory using operator new, and then construct objects in that raw memory using placement new. This means the unused part of the memory really is unused--i.e., it's just raw memory that doesn't contain any actual objects.

Naming

frontEndLength and backEndLength don't seem particularly descriptive, at least to me. Apparently they really mean something like "amount allocated" and "amount in use". If so, I'd change the names to reflect that more directly.

Exception Safety

Your assignment operator is written a lot like most of us typically wrote them in the '90s or so, before (for one example) Exceptional C++ was published. It has a number of problems. For example, if it ends up doing a self assignment:

ArrayList a;

// code that puts something into `a` goes here

a = a;

The self-assignment will often be somewhat indirect, such as passing the same collection as both the source and the destination of some function. Regardless of how it happens, it leads to a serious problem. It obviously shouldn't really do anything--but with your code, it destroys a. Nearly the first thing your operator= does is delete [] m_array;, so if the source and the destination are the same, you've just destroyed your source, and after that, everything breaks badly.

Quite a few people noticed this problem, so at one time it was pretty typical to see code that did something like this:

T &operator=(T const &r) {
    if (this == &r) // if source and dest are the same, do nothing
        return;
    // rest of the assignment goes here.
}

This fixes that particular problem, but leaves a more pernicious one. You'd typically like your assignment to either succeed entirely or fail entirely--but as it stands now, it might half-succeed, so you've lost the old contents, but gotten only part of the new contents. Worse, you aren't sure where in the copying process it was when the exception was thrown, so you don't have any way of knowing how much of the content is really valid.

One simple way of dealing with all of these is called the copy and swap idiom. It consists of creating a temporary copy of the source. Then when that's completed, you swap the destination with the temporary.

template<typename T>
ArrayList<T>& ArrayList<T>::operator=(const ArrayList<T> &arrayList){

    ArrayList<T> temp(arrayList);
    std::swap(*this, temp);
    return *this;
}

You can also shorten this a tiny bit by using the parameter as the temporary object:

template<typename T>
ArrayList<T>& ArrayList<T>::operator=(ArrayList<T> arrayList){

    std::swap(*this, arrayList);
    return *this;
}

Either way, if an exception is thrown during the copying process, the temporary is never created, and the swap never happens. The original stays exactly as it was. We normally expect (and typically enforce) that the swap can't throw any exceptions (pretty trivial in this case, because all it's doing is copying pointers and ints around).

Once that's done, the temporary gets destroyed, releasing the memory that was previously used by the destination object.

Of course, there are other ways to write an exception-safe assignment operator--this is just one that's simple, well-known and idiomatic.

Expansion factor

Right now, when you run out of space, you multiply the size by two. That's a fairly reasonable approach, but there's a theoretical argument to be made in favor of making the expansion factor less than or equal to the golden mean. I wrote a little more about it in an earlier reply.


public void _push(int data){

You've named a function in a way that suggests it shouldn't be used, but keep it public then support it via push(int... anyway.

There's no need to name your functions something different here; Java can do overloading just fine. If you name your function push, java knows when it needs to call push(int data) or push(int... data).

public int peek(){
    return top.data;
}

Your peek function causes a NullPointerException if the stack is empty. Consider returning -1 as well, since that's the value you use for "there was no data".


Project Euler Problem #4 - Palindromic number (Revision 1)

You were on the right track starting with number.ToString().  However, you don't need to duplicate the string, just check whether the value at each index is the same as the value at the index the same distance from the other end:

bool IsPalindrome(int number)
{
    string num = number.ToString();
    for (int i = 0, j = num.Length - 1; i < num.Length / 2; i++, j--)
    {
        if (num[i] != num[j])
        {
            return false;
        }
    }
    return true;
}


Rename DFS to DeepestLeavesSum.

Extract  depth + 1 to variable.

In here else if (depth + 1 == maxDepth) the else is reduant.

The order of depth + 1 and maxDepth is different between the Ifs. One time  maxDepth is on the left side and other time on the right side.

Usually, when writing recursion, you return the value and not store it in the class.

If you call DeepestLeavesSum twice with the same object the second call will return wrong results because it will use sum and maxDepth of the first call. A good practice is avoiding saving state.


Not really that bad, unless you consider the fact that __proto__ is non-standard (but is used in most browsers). While some developers argue that __proto__ isn't going away soon, I'd rather go for a more "standard-ish" approach.

The usual way is to just use prototypes like they were designed:

// Person class
var Person = function(){
  this.foo = 'hello';
  this.bar = 'world';
};
Person.prototype = Object.create(Object.prototype);
// Since we just clobbered prototype, we return the constructor
Person.prototype.constructor = Person;
// Add in methods
Person.prototype.read = function(){/*...*/};

// Programmer class
var Programmer = function(){
  // This is to run this object through the parent constructor so that it gets the properties.
  Person.apply(this,arguments);

  this.right = 'bob';
  this.left = 'alice';
};

// Then "inherit" the parent methods
Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;
Programmer.prototype.readCode = function(){/*...*/};

console.log(new Person());
console.log(new Programmer());

Now it's pretty ceremonious at this point, all that prototype stuff. You can skip all that if you create functions that automate that. Some libraries do the same thing, with sugar:

var ChildClass = BaseClass.extend();

One problem with this style of encapsulation is that your methods are defined per instance rather than shared. This will eat up memory:

function Class(){
  this.foo = function(){};
}

var instance1 = new Class();
var instance2 = new Class();
console.log(instance1.foo === instance2.foo); // false

Sometimes "forcing" private properties are just more hassle than originally intended. Besides, using the dev tools, your code is open to modification anyways. What most libraries do is use "pseudo-private", by prefixing the property with _. Technically, these properties are public, but it's a common programming convention telling the developer it's private.