Observations
Your rule of 5 implementation is basically wrong. You are implement copy operations for both copy and move (which means you may as well not have the move operations).
Your destructor is not doing any real work and thus adding unneeded code.
Your swap function does not work as expected as it can not be used with  Koenig lookup (ADL) and thus in most standard library would be replaced with std::swap resulting in a sub optimal swap.
Details
Here I don't see the need for creating a temporary.
    //Move constructor
    Test(Test&& other) noexcept {
        Test temp(other);
        swap(*this, temp);
    }

By creating the temporary your move is basically just as expensive as your copy. The whole point of the move is that it is cheap.
I would simply swap the current with other.
    //Move constructor
    Test(Test&& other) noexcept {
        swap(other);
    }

After the move construction the content of other has no guaranteed state (only that it is valid). Since you define m_size and m_buffer to auto initialize the current this is in a valid state and can simply be swapped with other.
    // Note I usually define a `noexcept` swap method.

    void swap(Test& other) noexcept {
        using std::swap;
        swap(m_size,   other. m_size);
        swap(m_buffer, other. m_buffer);
    }

I also define swap() with two parameters as a free standing function that simply calls the swap method. This is because the compiler can using Koenig lookup (ADL) to find the correct swap function.
    void swap(Test& lhs, Test& rhs) {
        lhs.swap(rhs);
    }

The Copy assignment is sub optimal.
    //Assignment operator
    Test& operator=(Test other) {
        if(this != &other) {
            swap(*this, other);
        }
        return *this;
    }

Since the parameter other is created via a copy construction it is guaranteed not to be the same as this. Thus the test if(this != &other) is just a pessimization as it is not needed.

Again you perform a copy during the move assignment.
    //Move assignment operator
    Test& operator=(Test&& other) noexcept {
        if(this != &other) {
            Test temp(other);
            swap(*this, temp);
        }
        return *this;
    }

This defeats the purpose of the move (as it is supposed to be cheaper than a copy). You can simply swap this and other as they should both be valid.
    Test& operator=(Test&& other) noexcept {
        swap(other);
        return *this;
    }

No need to check for self assignment as this is a pessimization of the normal more common situation. Even of they are the same object the swap will work correctly.

The destructor is useless:
    //Destructor
    ~Test() {
        m_size = 0;
        m_buffer = nullptr;
    }

The member: m_buffer will correctly clean up the memory.

Making this a static member is not doing you any favors as it prevents Koenig lookup (ADL).
    static void swap(Test& first, Test& second) noexcept{
        using std::swap;
        swap(first.m_size, second.m_size);
        swap(first.m_buffer, second.m_buffer);
    }

Make this a free standing function:
namespace PL
{

class TestStatic
{
    public:
        static void swap(TestStatic& lhs, TestStatic& rhs) noexcept
        {}
};

class TestFreeStand
{
    public:
};
void swap(TestFreeStand& lhs, TestFreeStand& rhs) noexcept
{}

}

int main()
{
    PL::TestStatic      staticA;
    PL::TestStatic      staticB;

    swap(staticA, staticB);

    PL::TestFreeStand   freeStandA;
    PL::TestFreeStand   freeStandB;

    swap(freeStandA, freeStandB);
}

Notice the only compilation error here is: swap(staticA, staticB);
This means that if you add using std::swap; this code will now compile but it will not use your static void swap() method it will use std::swap which makes a copy of the object. The point of writing your own version of swap is that you are providing an optimization over the standard swap.
Better Implementation
#include <cstring>
#include <memory>
#include <utility>

namespace Testing
{

    class Test
    {
        public:
            // Default constructor
            Test() = default;

            // Parametrized constructor
            Test(std::size_t len, const char* data)
                : m_size(len)
                , m_buffer(new char[len]())
            {
                // Should validate the input here.
                // It is the only time you get outside input.
                // Potentially you could throw here I choose
                // not too (because I can see it as a valid input)
                // Your use case may be different.
                if (data) {
                    strncpy(m_buffer.get(), data, m_size);
                }
            }

            // Copy constructor
            Test(const Test& other)
                : m_size(other.m_size)
                , m_buffer(new char[m_size]())
            {
                strncpy(m_buffer.get(), other.m_buffer.get(), m_size);
            }

            // Copy Assignment operator
            Test& operator=(Test other)
            {
                swap(other);
                return *this;
            }

            // Move constructor
            Test(Test&& other) noexcept
            {
                swap(other);
            }

            // Move assignment operator
            Test& operator=(Test&& other) noexcept
            {
                swap(other);
                return *this;
            }

            void swap(Test& rhs) noexcept
            {
                using std::swap;
                swap(m_size,    rhs.m_size);
                swap(m_buffer,  rhs.m_buffer);
            }
        private:
            std::size_t m_size = 0;
            std::unique_ptr<char[]> m_buffer = nullptr;
    };

    void swap(Test& lhs, Test& rhs) noexcept
    {
        lhs.swap(rhs);
    }
}


Is indentation of #if & #endif directives an important readability convention?

I think it makes sense this way, because the #if directives are pretty much outside of the normal syntax. For example, you can write something like:

#if DEBUG
    if (CheckConditionDebug())
    {
        DoADebug();
#else
    if (CheckCondition())
    {
        DoA();
#endif
        DoB();
    }

This is valid code in both states (DEBUG defined or not), but there is no good way to indent the directives.

Note: I'm not saying that this is a good use of #if, just that it is a possible use and that it makes sense to take this into account.


Let me quote the wonderful book Numerical Recipes in C++ (but also applicable):

We assume that you know enough never to evaluate a polynomial this way:
p=c[0]+c[1]*x+c[2]*x*x+c[3]*x*x*x+c[4]*x*x*x*x;

or (even worse!),
p=c[0]+c[1]*x+c[2]*pow(x,2.0)+c[3]*pow(x,3.0)+c[4]*pow(x,4.0);

Come the (computer) revolution, all persons found guilty of such criminal behavior will be summarily executed, and their programs won't be!

(You can find the page in your edition in the analytical index, under the entry "puns, particularly bad". I love this book.)
There are two reasons not to do that: accuracy and performance. The correct way to evaluate the polynomial is like this:
-t * (0.319381530  +  t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + 1.330274429 * t))))

And you can, of course, split at your convenience, as the newlines inside parenthesis are ignored. Remember the PEP: " The preferred place to break around a binary operator is after the operator, not before it."
-t * (0.319381530  +  t * (-0.356563782 +
    t * (1.781477937 + t * (-1.821255978 + 1.330274429 * t))))

Another alternative is to save the coefficients in a list:
coeff = [0, 0.319381530, -0.356563782, 1.781477937, -1.821255978, 1.330274429]
poly = coeff[-1]
for c in coeff[-2::-1]:
    poly *= x
    poly += c

I am doing operations in place to avoid allocating and deallocating memory, but this is only relevant if x is a NumPy array. If you are evaluating on a single number, you can just use instead the nicer expression:
poly = poly * x + coeff[i]

But I would stick with the first one because it is more general.
Of course, the result has to be multiplied by the prefactor:
return 1 - 0.3989423*math.exp(-z*z/2) * poly

Or, if you want to do it in place:
z2 = z * z # Be careful not to modify your input!
z2 *= 0.5  # Multiplication is faster than division.
np.exp(z2, out=z2)

probd = z2 * poly
probd *= -0.3989423
probd += 1
return probd

Bonus track:
If you are applying this function to large arrays (more than a thousand numbers), you may benefit from using the first technique in numexpr:
expr += '1 - 0.3989423* exp(-z * z / 2) * '
expr += '(-t * (0.319381530  +  t * (-0.356563782 +  t * '
expr += '(1.781477937 + t * (-1.821255978 + 1.330274429 * t)))))'
ne.evaluate(expr)

This will compile the expression for you and transparently use as many cores as you have.


A great deal here depends on what you want to accomplish.

If you want to ensure that the file occupies N bytes of storage space, then your current method may easily fail. Some file systems (e.g., NTFS) support file compression. Writing the same character many times gives highly compressible data, so as you've written it, the file is likely to use only a small amount of storage ("small" is relatively, but certainly a lot less than the ~10 megabytes you intended to write).

If you're all right with that sort of result, then you can probably do quite a bit better with something like this:

int main() {
    std::ofstream file("text_file.txt");
    file.seekp(10000000);
    file << 'a';
}

This will often be much faster than what you've written. It'll also typically occupy very little space on disk. A directory listing will still normally show it as being the same size though.

If you want to ensure that your file really uses ~10 megabytes of disk space, you'll probably need to fill it with semi-random data instead of just repeating a single value. One way to do this would be to use a random number generator:

std::mt19937 gen{ std::random_device()() };

std::uniform_int_distribution<> dis(0, 255);

std::ofstream file("text_file.txt");
std::generate_n(std::ostream_iterator<char>(file, ""), size, [&]{ return dis(gen); });

Code Review

Globals vs. locals

There seems to be no real reason for making file a global variable as you did. Even if you're going to write to all the bytes of the file, it's almost certainly better to make it local to main (and initialize it upon creation):

int main() {
    int size = 10000000; //~10MB
    std::ofstream file("text_file.txt");
    [...]

Standard algorithms

Given that you're trying fill a container with a specified value, you might want to also consider using a standard algorithm designed for precisely that purpose:

    std::ofstream file("text_file.txt");
    std::fill_n(std::ostream_iterator<char>(file), size, 'n');

Use of headers

As it stands right now, you've included fstream.h, even though you don't seem to be using anything that's declared in that header. It's generally preferred to include only the headers you actually use.


How about using a simple Where clause?

var songs = Context.Songs
    .OrderBy(x => x.Id)
    .Where(x => x.Id > 500)
    .Take(10);


This code is very hard to read. These are very simple geometric operations that you are programming (just things like subtracting vectors, or finding a vector's squared length) but their meaning is buried under a mountain of boilerplate.

Where you have:

boost::transform(p1,p2,diff.begin(),std::minus<ArmPos::value_type>());

could you find some way to write:

diff = p1 - p2;

instead? Similarly, where you have:

return boost::accumulate(diff,0,square<ArmPos::value_type>());

could you find some way to write:

return diff.lengthSquared();

instead? C++ supports operator overloading and virtual functions, so surely something along these lines would be possible.


First I would fix the variable naming to have a consistent naming structure. In the first class you have variables starting with capital letters (I agree) but in the second they start with lowercase.

I would suggest only passing in what you need for the view and leaving the rest out.

Can you show us your view? I see you have two IEnumerables that look like they are passing domain data to the view. How are you displaying them?

Is GivenLifeLines a Foreign Key or a count? Hard to tell.


I don't know the position you were interviewed for. Below is the embedded engineer point of view.

A room temp is not a class parameter. The AC cannot control it directly, so this.temperature++ and this.temperature-- are incorrect. The AC may only read the temp sensor.
The desired temperature OTOH is a class parameter. You should go an extra mile and provide the interface to set it. BTW, I'd expect temperatureSet to do just that: set the desired temperature.
As implemented, the program terminates as soon as a certain temperature is reached. I expect an AC system to run more or less forever.
In the if (this.temperature < temperature) clause you turn on heater no matter what. Move the this.heatingSystem = true; line outside of this.coolingSystem clause.

Assuming the above recommendations are implemented, the basic functionality should look like this:

    while(true) {
        ambientTemperature = this.temperatureSensor.read();
        if (ambientTemperature < this.targetTemperature) {
            if (this.coolingSystem) {
                this.coolingSystem = false;
            } else {
                console.log('Temperature has been lowered to ' + ambientTemperature);
            }
            this.heatingSystem = true;
        } else {
        ....

Of course there is a plenty of room to improve, but again that depends on interviewer expectations, and the AC schematics you'd agree upon.


Incrementing specified list values, with "catch-up"

li is the name of your list of counters. The fact they are counters matters more than the fact it's a list, so, I'd call it counters.
I like the clever way you updated all elements in the counters list by creating a new one, but it may be slower than looping through the list and changing all elements in place. It'll also use twice as much memory (before the old one is GC'ed).
Your previous version didn't update max_val. This was fixed since this was originally posted.


Some comments:

score method: With functional - instead of imperative - style, you'll get write more compact code.
You may use the abstraction Hash#values_at.
letter_scores is constant. It can be a class constant, then.
String interpolation: Use "#{var} = #{value}" style.
[edit] As you say, word should be an argument of score, not the class initializer.

I'd write:

class Scrabble
  LETTER_SCORES = {...}

  def score(word)
    scores = LETTER_SCORES.values_at(*word.upcase.chars)
    scores.compact.reduce(0, :+)
  end
end

scrabble = Scrabble.new
puts("Type in one word for scrabble scorer:")
word = gets.strip
puts("Scrabble score for #{word} is #{scrabble.score(word)}")


Separate the for loop to a function printFunction(f, N)

Since you are using a known formula I suggest you use the names in the formula. Meaning i->x
function->f.


Turning numbers into a string of words - challenge

I think the code in the post is fine: the English language rules are quite complicated, and it's going to take a certain amount of computing effort however you implement it.
The variables units, teens, tens, and so on are always the same, so they could be global constants, rather than being constructed again every time the function is called.
It's conventional in Python for constants to have names written in all capital letters (see PEP8), so UNITS instead of units.
Instead of writing:

UNITS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

I think this is easier to read:

UNITS = 'zero one two three four five six seven eight nine'.split()

It's convenient to combine UNITS and TEENS into a single list giving all the names for numbers less than 20.
The code reads a string from standard input, converts it to an integer (by calling int(num), then converts the number back to a string (by calling "%d" % number), then splits the string into pieces, and converts each piece back to a number (by calling int(new_number_string[i])). This back-and-forth conversion is unnecessary, because you can split a number into 3-digit groups by repeatedly calling divmod until you get down to zero:

>>> divmod(123456789, 1000)
(123456, 789)
>>> divmod(123456, 1000)
(123, 456)
>>> divmod(123, 1000)
(0, 123)

The function nums_to_words does two things: (i) it converts a number to English words; and (ii) it capitalizes the words, joins them and appends "Dollars". The principle of separation of concerns suggests that these should be two functions. And that would be useful, because then the function implementing part (i) could call itself recursively.

It's also slightly more convenient to generate the results (by calling yield or yield from) instead of constructing a list. Then you could write this for concern (i):

UNITS = """
    zero one two three four five six seven eight nine ten eleven
    twelve thirteen fourteen fifteen sixteen seventeen eighteen
    nineteen
""".split()
TENS = "zero ten twenty thirty forty fifty sixty seventy eighty ninety".split()
THOUSANDS = """
    zero thousand million billion trillion quadrillion quintillion
    sextillion septillion octillion nonillion decillion undecillion
    duodecillion tredecillion quattuordecillion sexdecillion
    septendecillion octodecillion novemdecillion vigintillion
""".split()

def english_words(n):
    """Generate words (excluding "and") naming the non-negative number n
    in English.

    """
    if n < 20:
        yield UNITS[n]
    elif n < 100:
        tens, units = divmod(n, 10)
        yield TENS[tens]
        if units:
            yield UNITS[units]
    elif n < 1000:
        hundreds, remainder = divmod(n, 100)
        yield UNITS[hundreds]
        yield "hundred"
        if remainder:
            yield from english_words(remainder)
    else:
        groups = []             # Groups of three digits from n.
        while n:
            n, group = divmod(n, 1000)
            groups.append(group)
        for i, group in reversed(list(enumerate(groups))):
            if group:
                yield from english_words(group)
                if i:
                    yield THOUSANDS[i]

and this for concern (ii):

def num_to_words(n):
    return ''.join(w.title() for w in english_words(n)) + "Dollars"


Your big mistake is not using iterators.

As a result you pass your vectors by value, which causes the vectors to be copied a lot.

std::vector<int> MergeSort(std::vector<int> arr)
                                            ^^^    A copy of the array is made when you call this function.

std::vector<int> Merge(std::vector<int> arr1, std::vector<int> arr2)
                                        ^^^^ Copy              ^^^^ Copy

Now, you could mitigate this by passing the values by reference. But I think a better solution is to pass iterators into the container. That way you also allow for other container types.

Luckily for you, a return is a move, not a copy - so that is not as  big a problem as a copy.

template<typename I>
void MergeSort(I begin, I end)

template<typename I,
void Merge(I src1Begin, I src1End, I src2Begin, I src2End, I dstBegin);


This may help with your second point about code concepts:

How about addressing the special case for when the user enters a palindrome?  It looks to me like you are assuming the entered number will not be a palindrome and you automatically add to it (calling RecurseUntilPalindrome).  How about adding an initial check to account for that case?  I think it would go along well with your numerical value input check (I consider invalid user input as a sort of special case as well).

To address your first point, I think your code looks pretty clean as is! Really easy to follow.


Find the highest number satisfying a condition in an infinite range

if/else inside the loop doesn't look clean. Consider splitting the code into two parts:

    # Find the "good" range

    while condition(hi):
        lo, hi = hi, hi * 2

    # At this point it is known that condition(lo) is True,
    # and condition(hi) is False. A normal bisection search
    # follows.

   return binary_search(lo, hi, condition)

It would be also worthy to factor the setup loop out in its own function.


Oh my goodness: How many selfies have I taken?

One by one, then:

  Is it good that I stored the posts in tables, or is it unnecessary?

It is unnecessary, in this case. What your table variables are doing for you here really is simulating a self-referencing join. You could instead use aliases on the actual table(s), for instance:

FROM Posts AS "Answers"
  JOIN Posts AS "Questions"
    ON "Answers".OwnerUserId = "Questions".OwnerUserId
    AND "Answers".ParentId = "Questions".Id
    AND "Answers".PostTypeId = @AnswerId
    AND "Questions".PostTypeId = @QuestionId
WHERE "Answers".OwnerUserId = ##UserId##
  AND "Questions".OwnerUserId = ##UserId##

(Note that double-quotes are not needed for aliases, but I personally like using them as a visual reference that something is an alias instead of an actual database object)

  Am I following good SQL practices/conventions?

Yes, I think that looks good (besides what I just mentioned).

  I was really confused on how I should break up the SQL into multiple lines, so, after much trial and error, it seemed to me having one instruction per line was the cleanest. However, if this is not recommended, I am open to change.

And...

  Am I missing indentation anywhere?

In SQL there are as many indentation/formatting styles as there are people who write SQL. One way that seems to work good for many is to have all your primary keywords at minimum indent, and the rest indented 2, 4 or more spaces, whatever is called for.

The primary keywords are (for SELECT statements):

WITH
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

Of course many times you won't use all of those, but this works pretty good as a thumb rule. For the rest, as long as you keep it readable and use some of your common sense you would apply for other languages, you should do fine.

Update: Addressing additional question.

  To me, reading SQL is just like reading English. Therefore, writing documentation seemed redundant. However, I am not familiar with good documentation and SQL, so is there anything documentation-wise that I should add?

The answer as usual is it depends. In simple queries like yours, documentation would probably just be clutter. In SQL as in every other language, if the code is written well (especially good naming, aliasing, etc.) you often don't need documentation.

There is one style of documentation which I have come up with that can be useful for queries where others might have to look at after you. Here's an example (imagine you were querying data over a certain period of time, which you could also do with SEDE by asking the user to input a period):

DECLARE /* The interval in Days how far back we want to query for values. */
    @DaysInterval INT = 90;
IF @DaysInterval > 0 /* meaning we would go into the future instead of the past... */
    SET @DaysInterval = @DaysInterval * -1;
DECLARE /* Variables for which dates to query from and up to, based on @DaysInterval. */
      @FromDate DATETIME = DATEADD(DAY, @DaysInterval, GETDATE())
    , @ToDate DATETIME = GETDATE();
DECLARE /** Filters for which tags to query.  */
    @TagsFilter TABLE (
        Tag VARCHAR(20)
    );
INSERT INTO @TagsFilter
    SELECT 'sql' UNION
    SELECT 'python' UNION
-- etc.

I take advantage of the fact SQL often reads like English to add in documentation that flows with it like that.

There are also cases when you would want to add documentation that explains why you are doing something a certain way, as it is now always obvious... For example:

/**
 * Temp table to hold results from the posts tables from each respective SE site database.
 * This will be used in conjunction with @TagsFilter in order to match records.
 */
IF OBJECT_ID('tempdb..#SESites') IS NOT NULL
    DROP TABLE #SESites;

CREATE TABLE #SESites (
-- etc.

Hope this helps :)


IsPrime

public static bool IsPrime(int n)
{
    for (int i = 2; i <= n; i++)
    {
        if (n % i == 0)
        {
            if (i == n)
                return true;
            else
                return false;
        }
    }
    return false;
}

Under what circumstances can the final return false be reached? Why not handle those special cases explicitly, and then simplify the loop body by reducing it?

public static bool IsPrime(int n)
{
    if (n < 1) throw new ArgumentException("n");
    if (n == 1) return false;

    for (int i = 2; i < n; i++)
    {
        if (n % i == 0) return false;
    }
    return true;
}

Of course, there are better ways of testing primality than trial division, but that's beside the point.

PrimeFactors

public static int[] PrimeFactors(int n)
{
    var factors = new List<int>();
    for (int i = 2; i <= n; i++)
    {
        while (n % i == 0 && IsPrime(i))
        {
            factors.Add(i);
            n = n / i;
        }
    }
    return factors.ToArray();
}

Any particular reason for returning int[] instead of IEnumerable<int>?

What's the purpose of the IsPrime call there? It's easy to prove that it always returns true (and so the IsPrime method isn't needed at all).

As a point of style, I prefer op= methods, but this is really subjective.

The loop guard might be more intelligible as n > 1.

public static IEnumerable<int> PrimeFactors(int n)
{
    var factors = new List<int>();
    for (int i = 2; n > 1; i++)
    {
        while (n % i == 0)
        {
            factors.Add(i);
            n /= i;
        }
    }
    return factors;
}

CreateCounterHash

private static Dictionary<int, int> CreateCounterHash(IEnumerable<int> mFactors)
{
    Dictionary<int, int> hash = new Dictionary<int, int>();
    foreach (var factor in mFactors)
    {
        if (hash.ContainsKey(factor))
            hash[factor]++;
        else
            hash.Add(factor, 1);
    }
    return hash;
}

Why does the return type use the implementation Dictionary rather than the interface IDictionary?

Why hard-code the type? You don't do anything with it other than equality checking, so it could be IDictionary<T, int> CreateCounterHash<T>(IEnumerable<T> elts) (and then could potentially be an extension method of IEnumerable<T>).

ContainsKey followed by a get is a minor inefficiency. Since TryGetValue will give default(int) (i.e. 0) if the key isn't, found, this can be fixed:

private static IDictionary<T, int> CreateCounterHash<T>(IEnumerable<T> elts)
{
    Dictionary<T, int> hash = new Dictionary<T, int>();
    foreach (var elt in elts)
    {
        int currCount;
        hash.TryGetValue(elt, out currCount);
        hash[elt] = currCount + 1;
    }
    return hash;
}

LCM

public static int LeastCommonMultipleByPrimeFactorization(int m, int n)
{
    //retrieve prime factors for both numbers
    int[] mFactors = PrimeFactors(m);
    int[] nFactors = PrimeFactors(n);

    //generate hash code to get counter for each factor
    var mFactorsCountHash = CreateCounterHash(mFactors);
    var nFactorsCountHash = CreateCounterHash(nFactors);

    var primeFactors = new List<int>();
    primeFactors.AddRange(mFactors);
    primeFactors.AddRange(nFactors);

    int result = 1;

    //On each distinct factor... check either which number factors
    foreach (int factor in primeFactors.Distinct())
    {
        int mfactorCount = 0;
        int nfactorCount = 0;
        if (mFactorsCountHash.ContainsKey(factor))
        {
            mfactorCount = mFactorsCountHash[factor];
        }

        if (nFactorsCountHash.ContainsKey(factor))
        {
            nfactorCount = nFactorsCountHash[factor];
        }

        int numberOfCount = mfactorCount > nfactorCount ? mfactorCount : nfactorCount;
        result = factor * result * numberOfCount;
    }

    return result;
}

Looks buggy: factor * numberOfCount will only be correct when numberOfCount == 1 or factor == 2 && numberOfCount == 2.

Also a tad repetitive. Can't you merge the two counts earlier?

public static IDictionary<K, V> MergeDictionaries<K, V>(IDictionary<K, V> d1,
                                                        IDictionary<K, V> d2,
                                                        Func<V, V, V> mergeFunc)
{
    // Left as an exercise
    // Only call mergeFunc when both dictionaries contain the key
}

You can also use a bit of Linq to do the aggregate, so the LCM simplifies to

public static int LeastCommonMultipleByPrimeFactorization(int m, int n)
{
    //retrieve prime factors for both numbers
    int[] mFactors = PrimeFactors(m);
    int[] nFactors = PrimeFactors(n);

    //generate hash code to get counter for each factor
    var mFactorsCountHash = CreateCounterHash(mFactors);
    var nFactorsCountHash = CreateCounterHash(nFactors);

    var combinedCounts = MergeDictionaries(mFactorsCountHash, nFactorsCountHash, Math.Max);
    return combinedCounts.Aggregate(1, (prod, primeWithMult) => prod * pow(primeWithMult.Key, primeWithMult.Value));
}


Time & Memory Complexity
Your code uses a lot of time and memory.
With an \$d\$ digit number, you will get roughly \$d!\$ different permutations of digits.  list(permutations(str(n))) will cause all of these permutations to be realized in a list \$d!\$ elements long.
You take this list, and then repeatedly take one permutation from it, convert it into a number, add append it to the end of a result list, growing the list one element at a time.  This can be an \$O(k^2)\$ operation, and since \$k\$ in this case is \$d!\$, you have \$O({d!}^2)\$ time complexity.
Next, you take this list, and sort it, which is an \$O(k \log k)\$ operation, or in this case \$O(d! \log {d!})\$.
Finally, you take this sorted list, and loop through it until you find the first value larger than the starting value.
Space complexity: \$O(d!)\$.  Time complexity: \$O({d!}^2)\$.
Removing the \$O(k^2)\$
The simplest way to avoid the creation of list, and repeated append operation (which may cause a relocation & copy of all previous elements for each additional element added to it), is to allocate an array of the correct size ahead of time.
Since this is such a common operation, Python even gives us a shortcut: list comprehension.  Any code of the form:
destination = []
for value in source:
    destination.append(func(value))

can be rewritten as:
destination = [func(value) for value in source]

The Python interpreter can (via the__length_hint__ from PEP424) tell that it will be allocating a new list of len(container) elements, and may pre-allocate that storage, and then start populating the elements of that list.
(Note: CPython, IronPython, Anaconda, and other big snakes may implement things differently under the hood, possibly amortizing individual appends down to an \$O(1)\$ operation, and may or may not use __length_hint__, but the point still is using list comprehension will always be faster than allocating a list and repeatedly appending elements one at a time.)
We can re-write your function as:
def next_bigger(n):
    per = list(permutations(str(n)))
    result = [int("".join(j)) for j in per]
    for i in sorted(result):
        if i > n:
            return i

Space complexity: \$O(d!)\$.  Time complexity: \$O(d! \log {d!})\$.
Removing the \$O(k \log k)\$
Sorting is an expensive operation.  We don't want to do it if we don't have to.  And we definitely don't have to here; we only want one value as a result.
You are looking for the smallest value, from a list of values, that is larger than the input.  We can filter out all values which aren't larger than the input:
    candidates = [value for value in result if value > n]

And then return the minimum of all candidates:
    return min(candidates)

No sorting.  Space complexity: \$O(d!)\$.  Time complexity: \$O({d!})\$.
Removing the \$O(d!)\$ Space Complexity
There is no reason to store any intermediate results.  You could generate your list of permutations, and for each permutation, convert it back to a number, discard any value that isn't larger that the original, and remember the smallest value which passes.
def next_bigger(n):
    per = permutations(str(n))

    result = (int("".join(j)) for j in per)

    candidates = (i for i in result if i > n)

    return min(candidates)

permutations(...) is a generator function, so per is assigned a generator object.  We use that generator to construct our own generator that converts a digits of a permutation into an integer, and store that generator in result.  We take that generator and create another one which only produces values larger than the original, assigning the generator to candidates.
At this point, no permutations have been created yet.  No digits have been joined, and converted to an integer.  And no values have been tested for whether they are greater than the original.  Only generators for these actions have been created.
Then, we pass the last generator to min(...).  The min(...) function asks this generator for a value, and then for another value and save the smaller, and then another value and saves the smaller, and so on.  Only the smallest value is preserved at each step.
No list creation.  Space complexity: \$O(1)\$.  Time complexity: \$O({d!})\$.
Readability
I've used your variable names (n, per, result, j, and i) unmodified in my "improvements".  But someone reading the code has to inspect the code to determine that j is a tuple of digits, and i is the corresponding integer value.  Better variable names go a long way towards more understandable code.  Type hints and """docstrings""" are also extremely useful.
from itertools import permutations

def next_bigger(number: int) -> int:
    """
    For a positive integer, returns the next larger number that can
    be formed by rearranging its digits. For example:

    >>> next_bigger(12)
    21

    >>> next_bigger(513)
    531

    >>> next_bigger(2017)
    2071
    """

    permuted_values = (int("".join(permuted_digits))
                       for permuted_digits in permutations(str(number)))

    return min(value for value in permuted_values if value > number)

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)

Of course, for a Code Wars submission, you'd strip out the docstrings, doctest, type hints in the pursuit of speed.
A Better Algorithm
The above are minor improvements on your existing algorithm.  As comments and other posts indicate, there is a better algorithm.


Beginner's level hovering effect on anchors

There's one bug and one tiny improvement, that I can think of:

In my browser (Chrome on Mac), border line on hover animated on top of text rather than under it. It was, because line bottom: 0 was ignored. Previous comment line broke the code. Removing it fixed my problem. There are no // comments in css, always use /* */ (or use scss).
When doing animation where object suddenly appears with border on hover, there might be small glitch if initial object is visible, because content has to adjust to newly gained border or size (depends on bounding-box). For example if initial width was 1%. For these reasons, I set transparent border to original element (in this case I mean a::after and on :hover I just add border-color.


You're adding a lot of complexity here. Plus, you're going against the point of a Service Layer and Domain Model. Your Domain Model should probably use either Active Record or Data Mapper.

The point of a Service Layer is to act as an end point (API) that holds common business logic that deals with integration of domain model objects. Your service layer should just query repositories and delegate calls to process business logic to your domain model (which should hold as much business logic as possible). Injecting it into your domain model adds persistence concerns, which it should not care about.


Finding the minimum in a sorted, rotated array

The algorithm does not work correctly.

It fails on the following:

int a1[] = {10,1,10,10,10,10,10};

printf("\n%d", getMinimIndex(a1,0, lastIndex(a1))); // 5

It prints 5 instead of 1.

The problem is in case the elements can repeat, you assumption that we can recurse on the left or right half is wrong.

In fact, if elements can repeat, any algorithm will be in the worst case Omega(n), while yours is always O(logn), so it is incorrect.


Display students of specific age using struct

#include <cstring>

You're not using any of the features in that header. Replace is with <string> and do use those. Also indent your code, it makes it more readable.

struct student
{
  std::string name;
  int year;
  int group;
};

Don't get into the habit of using this:

using namespace std;

See Why is “using namespace std;” considered bad practice?

int N;
int age;

You only need N a few lines down, and age only way below inside the loop. Declare them as close to their first use as possible, in the smallest scope possible.

cin>>N;
struct student student1[N];

A few issues:

You're not checking whether that read of an int actually worked (same for all the other inputs).
You don't need the struct keyword there. You need it in C where structs live in a separate namespace, but that's not the case in C++.
This is not standard C++: this uses a feature called variable-length arrays which are standard C but not part of C++ (but some compilers have support for it anyway). Instead, use a std::vector (don't forget to #include <vector> also).

return 0;

This isn't necessary, if main doesn't explicitly return anything, the standard guarantees that it will act as if it had returned 0. (This is only valid for the main function, all other non-void functions must return something on all their returning branches.)


Using strtol() and strtod() would be a preferable way to determine if a string converts to a number.  By using various locale settings, code can work with thousands separators too.  This is a advanced task for a learner, so we will stick with your code.
Avoid magic numbers.  Rather than code 13, use a derived limit.

// for(int b = 0; b < 13;b++){
for(int b = 0; b < sizeof numdig / sizeof numdig[0] ;b++){

Avoid negated variable names.  Rather than notnum --> valid_num
For boolean variables like notnum/valid_num, use tpye bool.  Be sure to include stdbool.h
Use standard functions like strspn().  This replaces the entire while loop.  Make numdig[] both static and const for better optimization and greater clarity as to its use.

static const char numdig[] = {"0123456789,$."};
bool hasdec = false;
bool valid_num = arr[strspn(arr, numdig)] == '\0';

// search for dp separate
if (valid_num) {
  char *p = strchr(arr, '.');
  // dp found, see if another exist.
  if (p) {
    hasdec = true;
    valid_num = strchr(p+1, '.') == NULL;
  }
}

Good use of const in function signature.

int check_is_numeric(const char *arr)

Surprised signs '-' and '+' were not allowed.
Surprised optional leading whitespace was not allowed; very idiomatic in C.
Tests.  I would have like to see the coding goals specifics and some of your sample test data to assess how thorough the claim "function works exactly as I want it to".  I suspect input like "1,234,,456.0" will pass.
Advanced: '.' as decimal point and ',' as thousands separators is locale dependent.  Research <local.h> for details to make a function that works outside the "C" locale.

char dp = localeconv()->decimal_point[0];

Code looks like it ends with no return. Drop else.  Avoid !.

 if(valid_num) {
   if(hasdec) return 2;
   return 1;
 }
 return 0;


Android app for sending username and password requests

Overdoing static is a code smell.  Basically you have to balance things.

Too much static code typically means not enough code in the objects, or not much object oriented structure.  Since objects provide boundaries between the in-object code and the rest of the system, they allow "leverage points" for future change (and for testing).  You can, for example, subclass an object to provide a variety of implementations of a particular class method.

With static methods, no such polymorphisim is possible.  This can lead to switch statements embedded within the static method (to function on key fields, acting somewhat like the state pattern).  The primary reason this tends to become a smell is that switch statements put the burden of code maintenance outside of the object.  In extreme cases, it begins to feel like the object is not encapsulating it's behavior, but rather the switch statement dictates external behavior depending on the data fields within the object.  Such code becomes difficult to maintain over time.

I would avoid static methods as much as reasonably possible; however, in some cases it is a better choice to use them.  For example, one would not typically benefit from subclassing the java core types.  So if I needed to write a method that operated on String objects, I would probably prefer to put that as a static method on a StringUtils class.  On the other hand, if it were a class that I had written, I would probably go out of my way to stay more object-oriented.

In your example...

MyAPIClient.getInstance().post(path, params,
            new JsonHttpResponseHandler()
            {
                @Override
                public void onSuccess(JSONObject responseObject)
                {
                    String responseAPIStatus = responseObject.getString("status");
                    if (status.isEquals("success")
                    {
                        responseHandler.callback(true, null);
                    }

                }

                @Override
                public void onFailure(Throwable e, JSONObject errorResponse)
                {
                    responseHandler.callback(false, new CustomError(e));
                }
            });

is going to be very hard to test.  If only you had made an interface on the MyAPIClient, you could do something like.

public SignIn(String username, String password,
    final SigninResponseHandler responseHandler,
    final MyAPIClient) {
   ...
}

which would make SignIn easily be unit testable, like so

SignIn signIn = new SignIn("bob", "supersecret", new JsonHttpResponseHandler() {...},
    new MockAPI() {... });
signIn.perform();

while the mainline code would look like

SignIn signIn = new SignIn("bob", "supersecret", new JsonHttpResponseHandler() {...},
    MyAPIClient.getInstance());
signIn.perform();


General review
Generally the code is OK and problems are due to lack of experience rather than bad style or habit.
I am unfamiliar with SpreadsheetApp so you should wait in case someone that is adds another answer before you accept this answer, if so inclined.
Rather than submit this answer I took a quick look at the DOC for SpreadsheetApp (I hope I got the correct one) and added to this answer at bottom under heading Performance.
Review points

Take care with indentation. all code blocks should be indented (If indentation mess is due to snippets poor formatting ignore this line)

When using var declare them at the top of the function.

Use constants const for variables that do not change.

Use i, j only for indexes or counters, if you are accessing coordinates, row, column, or x, y use names to match the axis name.
In this case it looks like you are only indexing by row index. In the rewrite I use the variable name row. Then a counter called i to count 25 and allow for the skipped row every 26 rows.
BTW When using i, j in loops the convention is i for the inner loop and j is the outer.

Don't calculate the same value many times. Eg you calculate i + j 3 times.

Avoid single use variables.

Use while loops in preference to for loops especially if you are incrementing the counter manually in the loops block.
While loops are generally syntactically cleaner and are less complex under the hood (if you use let to declare the counter).
Note that when using while loops it is easy to forget to add the incrementation so take care to not forget to increment / decrement

Use arithmetic assignment operators in this case += (Addition assignment) i += 25 rather than i = i + 25;

The is no need to create a new Date object every time you make a change.

Date object
The Date objects call Date.getFullYear always returns a Number as an integer.
There is no need to use parseFloat and the result of !isNaN(parseFloat(yearCompleted)) will always be true and is thus not required.
Further the variable yearCompleted is only used in the unneeded predicate and as such is not required at all.
To set the date to the first day of the month you don't need to use year, month + 1, 0 just set it to the 1st year, month, 1
The inner if statement
It is unclear if the call to get interval = ssData.getRange(i + j, 5).getValue() will return a number or not.
Because the use of monthCompleted is dependent on the valid numerosity of interval you can combine the two in one expression. However I suspect that interval will always be a number and as such there is no need for the isNaN test.
Rewrite
Using the above points the rewrite greatly reduces the code complexity. Without data there is no way to know if there is a need to vet the interval value. I added the test but it may not be needed.
function setDates() {
    var row = 4, i;
    const data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
    while (row < data.getLastRow()) {
        i = 25;
        while (i--) {
            const interval = data.getRange(row, 5).getValue();
            if (!isNaN(interval)) {
                const completed = new Date(data.getRange(row, 4).getValue());
                completed.setMonth(interval + completed.getMonth());
                completed.setDate(1);
                data.getRange(row, 6).setValue(completed);
            }
            row ++;
        }
        row ++;
    }
}

Performance
I have taken a quick look at the SpreadsheetApp docs and thus will address the performance problems you are concerned about.
The problem I think is the use of getRange(row, column) which you use to get each cell.
Rather...

Use getRange(row, column, numRows, numColumns) to get all the rows and columns in one call before you iterate the cells.

Then get an array of values from the range using range.getValues() make the modifications needed.

Then use range.setvalues() to set the changes made

This may get a significant performance increase.
Rewrite based on Docs
As I have no data or access to the API the rewrite is only a guess based on a quick read of the DOC's
The only problem I can foresee is why you skip every 26th row and why you start from the 5th row (index as row 4)
function setDates() {
    var rowIdx = 0;
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
    const range = sheet.getRange(4, 4, sheet.getLastRow() - 4, 3);
    const data = range.getValues(); // as 2D array of rows by columns eg...
                                    // data[0][0] is row 4 column 4
                                    // data[10][2] is row 14 column 6
    for (const row of data) {
        if (rowIdx > 0 && (rowIdx % 26)) { // skip every 26th row
            const interval = row[1];
            if (!isNaN(interval)) {
                row[2] = new Date(row[0]);
                row[2].setMonth(interval + row[2].getMonth());
                row[2].setDate(1);
            }
        }
        rowIdx++;
    }
    range.setValues(data);
}


Your intuition was accurate! Here is a shortened version with (almost-)identical functionality:

from random import choice

def picks(filename):
    with open(filename) as f:
        lines = [line.strip() for line in f]
    return choice(lines).split()[0]

def random_names(number_of_names):
    for _ in range(number_of_names):
        nselect = picks(choice(('femalenames.txt', 'malenames.txt')))
        print('{0:s}, {1:s}\n'.format(picks('surnames.txt'), nselect))

random_name(5)

Note the following:

str.strip removes whitespace (including newlines) by default, so you don't need to make the argument explicit;
random.choice is a neater way to select a random item from a list than generating and using an index;
random_names is a better name for the function, as you can specify a varying number of names;
You don't need to initialise nselect;
Why carefully adjust an index you aren't actually using by one? 0 is the default start for range, so we can just use number_of_names directly; and
Selecting directly from the two possible filenames makes the functionality more obvious (although you can no longer print(g), which was a bad name anyway).


This code looks good, I only have 2 minor items from a once over;

I would have a constant for -1 meaning an all day event

var ALL_DAY_EVENT = -1; // <-- Declared somewhere on top
if (position === ALL_DAY_EVENT) {
    ...

This:

if (secondHalf.indexOf("AM") !== -1) {
    var title = secondHalf.substring(secondHalf.indexOf("AM") + 3); //Title if has AM
} else {
    var title = secondHalf.substring(secondHalf.indexOf("PM") + 3); //Title if has PM
}

Declares title with var twice, you should declare title only once, ideally on top before your loop. Also, there is some serious code repetition there. I would suggest something like:

//Declare meridiem and title somewhere higher prior to the loop
meridiem = ~secondHalf.indexOf("AM") ? "AM" : "PM";
title = secondHalf.substring(secondHalf.indexOf(meridiem) + 3);


1. Introduction

It is not a good plan to leave code running for 30 hours. Until you have analyzed the code, and have figured out how its runtime varies according to the size of the input, then you have no idea how long it will take. Maybe it will take 31 hours, but maybe it will take a million hours.

In this situation you need to (i) analyze the algorithm to get an expression for its runtime complexity (that is, how its runtime depends on the size of the input); (ii) measure the performance of the code on small inputs; (iii) use the results of (i) and (ii) to extrapolate to the runtime for the full data set.

2. Review

There are no docstrings. What are these functions supposed to do?
dist can be simplified using math.hypot:

def dist(p, q):
    "Return the Euclidean distance between points p and q."
    return math.hypot(p[0] - q[0], p[1] - q[1])

The name join_pairs is misleading because it does not join anything. I am sure you could pick a better name.
It would be useful (for testing and performance measurement) to have a function that calls join_pairs in a loop until it returns False. I am going to use this function:

def sparse_subset1(points, r):
    """Return a maximal list of elements of points such that no pairs of
    points in the result have distance less than r.

    """
    points = points[:]
    while join_pairs(points, r):
        pass
    return points

The reason that I am taking a copy of points (rather than modifying the original) is so that I can call this function for testing or performance measurement without destroying the input data. See below for some examples.

3. Performance

Here's a test case of 1,000 random points:

import random
POINTS = [[random.random() for _ in range(2)] for _ in range(1000)]

The code in the post takes about 11 seconds to reduce this to a sparse subset of 286 points at least 0.04 apart:

>>> from timeit import timeit
>>> timeit(lambda:sparse_subset1(POINTS, 0.04), number=1)
10.972541099996306

Why does it take so long? The problem is that join_pairs removes just one point each time it is called. This means that you have to call it in a loop, but each time you call it it starts over comparing the same pairs of points that were already compared in the previous iteration. As a result of this algorithm the runtime is \$O(n^3)\$: that is, the runtime grows like the cube of the length of the input.

We can see this cubic behaviour by measuring the time \$t\$ taken by the function on a range of sizes \$n\$ and finding a cubic equation \$t = an^3\$ of best-fit:

>>> import numpy as np
>>> n = np.arange(100, 1001, 100)
>>> t = [timeit(lambda:sparse_subset1(POINTS[:i], 0.04), number=1) for i in n]
>>> a, = np.linalg.lstsq(n[:, np.newaxis] ** 3, t)[0]

We can plot this on a log-log graph using matplotlib:

>>> import matplotlib.pyplot as plt
>>> plt.xlabel("n")
>>> plt.ylabel("t (seconds)")
>>> plt.loglog(n, t, 'r+', label="data")
>>> plt.loglog(n, a * t**3, label="least squares fit to $t = an^3$")
>>> plt.legend()
>>> plt.grid(alpha=0.25)
>>> plt.show()

So extrapolating from this analysis and measurement, we estimate that if \$n=300000\$ then the time taken will be roughly:

>>> a * 300000**3
339550658.803593

That's about ten years! Looking at the graph, it seems that the slope of the data is not quite as steep as the line of best-fit, so maybe the true exponent is a bit less than 3 and the extrapolated time somewhat less than ten years. But as a rough analysis this tells us that there's no hope for it finish in a few more hours, and so we have to find a better approach.
It would be better to do the work in a single pass over the list of points, like this:

def sparse_subset2(points, r):
    """Return a maximal list of elements of points such that no pairs of
    points in the result have distance less than r.

    """
    result = []
    for p in points:
        if all(dist(p, q) >= r for q in result):
            result.append(p)
    return result

This builds up the modified point cloud in the list result and returns it (instead of modifying the input points). The code considers each point in the input, and adds it to the result so long as it is sufficiently far from all the points that have been previously added to the result.

To check that this is correct, we can compare the output against the original version of the code:

>>> sparse_subset1(POINTS, 0.04) == sparse_subset2(POINTS, 0.04)
True

This revised code takes \$O(nm)\$, where \$n\$ is the number of points in the input and \$m\$ is the number of points in the output. In the worst case \$m = n\$ and the code has to compare every pair of points. On the 1000-points test case, this is hundreds of times faster than the code in the post:

>>> timeit(lambda:sparse_subset2(POINTS, 0.04), number=1)
0.04830290700192563

To further improve the performance, we need a spatial index, that is, a data structure supporting efficient nearest-neighbour queries. For this problem, I'm going to use the Rtree package from the Python Package Index, which implements the R-tree data structure. An R-tree maintains a collection of rectangles (or hyper-rectangles if the search space has more than two dimensions), and can efficiently find the rectangles in the collection that intersect with a query rectangle.

import rtree

def sparse_subset3(points, r):
    """Return a maximal list of elements of points such that no pairs of
    points in the result have distance less than r.

    """
    result = []
    index = rtree.index.Index()
    for i, p in enumerate(points):
        px, py = p
        nearby = index.intersection((px - r, py - r, px + r, py + r))
        if all(dist(p, points[j]) >= r for j in nearby):
            result.append(p)
            index.insert(i, (px, py, px, py))
    return result

When this code appends a point to the result list, it also adds a corresponding rectangle to the R-tree. This rectangle has zero width and height, so it represents a single point. When considering a point p for inclusion in the result set, the code queries a rectangle centred on p with width and height 2 * r. All points within a distance r of p are inside this rectangle, but there might also be some points in the corners of the rectangle that are more distant than r. That's why the code has to further check each point in the query rectangle.

Again, we need to check that this is correct:

>>> sparse_subset1(POINTS, 0.04) == sparse_subset3(POINTS, 0.04)
True

An R-tree takes \$O(\log m)\$ to find an intersecting rectangle in an index of \$m\$ rectangles, so we expect the runtime of sparse_subset3 to be \$O(n\log m)\$, where \$n\$ is the number of points in the input and \$m\$ is the number of points in the output.

Let's make a much bigger test case, with 100,000 points:

POINTS = [[random.random() for _ in range(2)] for _ in range(10**5)]

The performance of sparse_subset2 and sparse_subset3 depends on \$m\$, the number of points in the result. We expect that when r is big, \$m\$ will be small and so there won't be much difference. Here we use r=0.05 and get a subset of 287 points, and the two algorithms have almost identical runtime:

>>> timeit(lambda:sparse_subset2(POINTS, 0.05), number=1)
3.5980678769992664
>>> timeit(lambda:sparse_subset3(POINTS, 0.05), number=1)
3.598255231976509

But if we reduce r to 0.01, getting a subset of 5994 points, then the R-tree shines:

>>> timeit(lambda:sparse_subset2(POINTS, 0.01), number=1)
87.03980600900832
>>> timeit(lambda:sparse_subset3(POINTS, 0.01), number=1)
4.6150341169850435

(I didn't try sparse_subset1 on this test case as it will take many hours.)

The worst case for sparse_subset3 is when r is zero and so all the points in the input end up in the result:

>>> timeit(lambda:sparse_subset3(POINTS, 0), number=1)
10.394442071992671

Extrapolating from this, you should be able to run your 300,000-point case in under a minute, which is a big saving on ten years.


If you want a UUID, generate one.  What you have isn't a UUID.  It's just a string of random numbers.

If you want to reuse a once-generated UUID multiple times, you can do that.

static NSString * const uuid = [NSUUID UUID].UUIDString;

If you're calling a variable URL, it should actually be a NSURL object and not an NSString object.

And nesting the method call that actually wraps it into an NSURL doesn't do anything but reduce readability.

So perhaps, we really want something like this:

static NSString * const uuid = [NSUUID UUID].UUIDString;
static NSString * urlString = [NSString stringWithFormat:@"%@%@", @"http://www.example.co.uk/untitled.php?=", uuid];
static NSURL * url = [NSURL URLWithString:URL];

Finally, we have a problem with our timer here.

Here's the timer code you show:

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(getOnline) userInfo:nil repeats:YES];

The problem is that this timer repeats, and it's firing an asynchronous task.

Now, I'd certainly look into JavaProphet's comment about long polling versus sending repeated requests, but I do want to address the issue you have here.

What happens if it takes the second more than one second to reply to a request?  More importantly, what if the server replies to three requests in a row in under one second, the fourth takes over two seconds, and the fifth goes back to taking less than a second?

We can easily get the responses out of order because we're not waiting around for the server to tell us.

Rather than a repeating timer, we need a timer that is rescheduled after every fire.  We don't want to ask the server every single second.  We simply want to wait for one second since the last poll before we ask again.

Any time we're using a repeating timer, we must stop and answer this question:

  Do we really want this event to fire every , or do we actually want this event to fire  since the end of the last event?

Importantly, when we pick the latter, it makes it impossible for two (or several more) of the events to be going at the same time.  So when we stop the timer, the most amount of asynchronous events that could be out in some background waiting to come back is just one.  Using your approach, the number of events that could still fire back after we invalidate the timer is only a function of however long the timeout is.

If the server suddenly stopped responding and you had a 5 minute time out, and you waited until the first "The server timed out" response before you stopped the timer, there'd be 5 minutes-worth of these events still off in a background thread waiting for the server's reply, so you'd get hit with the "The server timed out" response 300 times before it was actually fully stopped.


Safe multiplication of two 64-bit signed integers

Given that you are writing for gcc, is there a reason you're not using the builtins?

bool __builtin_add_overflow (type1 a, type2 b, type3 *res)
bool __builtin_sub_overflow (type1 a, type2 b, type3 *res)
bool __builtin_mul_overflow (type1 a, type2 b, type3 *res)

But as to your question, it looks correct to me, modulo the answer by the other poster.


Get data from user input as workbook or worksheet

This is a cleaned-up version I would suggest:

Option Explicit

Private Function ImportDataFromExternalSource(ByVal boolPickSheet As Boolean, Optional ByVal lngNumberOfColumns As Long = 0) As Variant
    Dim lngLastRow As Long
    Dim strFileName As String
    Dim xlApp As New Excel.Application
    Dim wbkTarget As Excel.Workbook
    Dim shtTarget As Excel.Worksheet

    ' ask the user to select a file and try to open it with Excel
    Set xlApp = New Excel.Application
    Do While wbkTarget Is Nothing
        strFileName = FilePicker()
        If strFileName = "" Then Exit Function ' user requested abort
        On Error Resume Next
            Set wbkTarget = xlApp.Workbooks.Open(strFileName)
            If Err <> 0 Then MsgBox "An error occurred while opening the file" & vbNewLine _
                                   & strFileName & vbNewLine _
                                   & vbNewLine _
                                   & Err.Description _
                                   , vbCritical
        On Error GoTo 0
    Loop
    Set shtTarget = wbkTarget.Sheets(1)

    ' let the user select the sheet to import from
    If boolPickSheet Then
        xlApp.Visible = True
        Set shtTarget = xlApp.InputBox("Pick a cell on the sheet you would like to import", Type:=8).Parent
    End If

    ' determine the data that should be imported
    If lngNumberOfColumns = 0 Then lngNumberOfColumns = shtTarget.Cells(1, Columns.Count).End(xlToLeft).Column
    lngLastRow = shtTarget.Cells(Rows.Count, 1).End(xlUp).Row
    ImportDataFromExternalSource = shtTarget.Range(shtTarget.Cells(1, 1), shtTarget.Cells(lngLastRow, lngNumberOfColumns)) ' convert Range to Array

    ' cleanup
    wbkTarget.Close False
    xlApp.Quit
End Function

Public Function FilePicker() As String
    With Excel.Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = False
        .Title = "Select the file with your data."
        .Filters.Clear
        .Filters.Add "Excel Document", ("*.csv, *.xls*")
        .InitialView = msoFileDialogViewDetails
        If .Show Then FilePicker = .SelectedItems(1)
    End With
End Function

Being called like this:

Public Sub Test()
    Dim x As Variant

    x = ImportDataFromExternalSource(False, 1)
    If IsEmpty(x) Then
        MsgBox "you've cancelled", vbInformation
    Else
        Debug.Print x(1)
    End If
End Sub

If you are interested in the reasons behind the changes I made, I can provide some detailed information if you like.

Issues that still needs to be addressed

It would be preferable to decouple the user interaction (file and sheet selection) from the import logic, known as the Model-view-controller pattern. Have one function asking the user for the file and (optionally) the sheet, returning a Worksheet object. Now you can feed that object to another function that retrieves the array from the given sheet.

This way you are more flexible if, for example, you decide at one point that the sheet should also be able to be automatically retrieved by some other means. Just implement that in a way that it returns a Worksheet object, and you are good to go.
The way you determine the last cell in the sheet will fail in some circumstances (e.g. if the sheet is empty). Have a look at https://stackoverflow.com/a/11169920/6216216 for a thourough discussion of more robust alternatives.

Notes on Error Handling

You switched error handling on at the beginning of the function - as it is often recommended. There is no good way to do proper error handling in VBA (one of VBA's bigger flaws), but I thoroughly dislike the variant of catching all errors and handling them in one monolithic error handling routine at the end of the function/sub.

This is why:

The handling of an error gets disconnected from the origin of the error. This makes the code harder to read and easier to mess up during maintanance. Furthermore, debugging becomes a pain.
You may cast too broad a net, you might catch errors that you didn't want to catch.

Especially the second issue can become a serious problem when you start handling unexpected errors the same way as expected errors, since the error handling routine has no way to tell them apart.

Exactly this happened in your original code: If you call ImportDataFromExternalSource(False) and you cancel the file picker, fileName contains the empty string "". Trying to open that as an Excel workbook will fail and the error handler is called. This seems to be expected, because a message is displayed and the program gracefully terminated by jumping to the CleanExit label. During cleanup however, targetBook.Close is called, which will fail, because there is no targetBook, and an unexpected error is raised. Since your error handler cannot distinguish this from the expected error, the same routine is called: the messagebox is displayed again, the code continues with the CleanExit label and... now you are stuck in an infinite loop, because targetBook.Close will again raise an error.

The paradigm I followed is to apply the error handler to as litte code as possible, that is, the statements that I expect to fail. In this case, that is the Workbooks.Open function. The error handling code follows directly afterwards. If the handling code is more complex you should move it after the On Error GoTo 0, otherwise errors occuring in that code would just be silently ignored.

Do the same to other parts of the function where you expect errors (generally speaking; there aren't any in this code), and you have a clean separation of error handling for expected and unexpected errors: Expected errors are handled right away where they occurred, unexpected errors are bubbled up the calling stack until some code handles them that is better suited to do so. The worst case would be a runtime error that is displayed to the user indicating what exactly went wrong, but that would be preferable in most cases to exhibiting undefined behavior (as the infinite loop in your code).

This way your code becomes more robust, fast-failing if something went wrong instead of hiding the error and resulting in arbitrary consequences.


Reading configuration from a file for video rendering

I see a number of things that could help you improve your code.

Make sure you include all required headers

The necessary headers are not included in the question which makes it a bit harder to review than it needs to be.  The standard ones that are required appear to be these:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

Pass file names as parameters

Rather than hardcoding a filename twice (leading to the potential error of not having them match!), pass it as a parameter instead.  This reduces the hidden linkages in the code and makes it easier to see what's happening.

Be careful with signed versus unsigned

The code currently contains this:

for (int i = 0; i < contents.length();i++){
    if (!(contents[i] >= '0' && contents[i] <= '9' || contents[i] == ' '))
        return false;
}
MySettings = std::stoi(contents);

However, on some platforms, size_t is unsigned, so the loop is comparing an unsigned and a signed number.  I'd avoid that problem by declaring i to be of type size_t.

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.  Once you do that, you'll see that you have been abusing NULL and using it as an integer value instead of just a pointer.  For example, the code includes this:

int pos1 = NULL, pos2 = NULL;

In that context, both of those should be 0 because the variables are not pointers.

Use namespaces when required

The std namespace is used in some locations within the code, but not all.  In particular, in this line:

fstream input("config.ini", fstream::in);

Needed to be converted to this to compile on my machine:

std::fstream input("config.ini", std::ios::in);

Create a default constructor

In the case there is no config file, you'd like to have some default settings.  The better way to do that is to have a default constructor for Config.  I'd write it like this:

Config() : renderer{1}, Width{640}, Height{480}, Fullscreen{0} {}

Create a stream inserter

At some point, you will undoubtedly want to write the configuration file.  To do that, I'd recommend writing a stream inserter like this:

friend std::ostream& operator<<(std::ostream& out, const Config& cfg) {
    return out << "//renderer options - 0: D3D8, 1: D3D9, 2: OpenGL"
        "\nwidth=" << cfg.Width <<
        "\nheight=" << cfg.Height <<
        "\nfullscreen=" << (cfg.Fullscreen ? 1 :0 ) <<
        "\nrenderer=" << cfg.renderer << '\n';
}

Eliminate goto

The above two suggestions allow you to eliminate the start label and the associate goto by writing the else clause like this:

else{
    std::ofstream out(filename);
    out << MySettings;
}

Use standard algorithms to simplify

The code contains ConfigValue which returns a bool indicating whether the configuration was updated.  However, a more generic way to handle this might instead be to write a function to take a line and extract a name, value pair.  Here's how I'd write such a function:

std::pair<std::string, int> value(std::string line) {
    std::pair<std::string, int> val;
    // remove any comments
    auto n = line.find("//");
    if (n != std::string::npos) {
        line.erase(n);
    n = line.find('=');
    if (n != std::string::npos) {
        line[n] = ' ';  // replace '=' with space
        std::stringstream ss(line);
        ss >> val.first >> val.second;
    }
    return val;
}

Write a stream extractor

In the same spirit as writing the stream inserter, we can write a stream extractor.  Using the value function above as a member function of Config, it could be this:

friend std::istream& operator>>(std::istream& in, Config& cfg) {
    Config temp;
    std::string line;
    int fields = 0xF;
    for (std::string line; fields && std::getline(in, line); ) {
        auto pair=temp.value(line);
        if (pair.first == "width") {
            temp.Width = pair.second;
            fields &= ~0x01;
        } else if (pair.first == "height") {
            temp.Height = pair.second;
            fields &= ~0x02;
        } else if (pair.first == "renderer") {
            temp.renderer = pair.second;
            fields &= ~0x04;
        } else if (pair.first == "fullscreen") {
            temp.Fullscreen = pair.second;
            fields &= ~0x08;
        }
    }
    if (fields == 0) {
        std::swap(temp, cfg);
    } else {
        in.setstate(std::ios::failbit);
    }
    return in;
}

Note that unlike the current code, this code only updates the default if all four values were successfully read.  If you don't want that, you can just omit all references to fields in this function.

Make the object take care of itself

Since all of this code is associated with the Config struct, why not just actually make it a C++ class and have it take care of its own initialization?  For that, we could replace the ConfigFile function with a constructor:

Config(const std::string& filename)
: renderer{1}, Width{640}, Height{480}, Fullscreen{0}
{
     std::ifstream input(filename);
    input >> *this;
    if (!input) {
        std::ofstream out(filename);
        out << *this;
    }
}

Test function

I created a sample main to drive this code.  It looks like this:

int main()
{
    Config cfg("configreader.test");
    std::cout << cfg;
}

Naturally, you'll want to add more error and range checking but I hope this inspires you to rework your code into something more object-oriented.


Menu items to enter and exit full-screen mode in JavaFX

This can be made a lot more elegant with the State Pattern.

We'll introduce an enum for the two states :

private static enum Mode {
    FULLSCREEN("Exit Full Screen"), NORMAL("Full Screen");

    private final String toggleActionText;

    private Mode(String text) {
        this.toggleActionText = text;
    }

    public String getToggleActionText() {
        return toggleActionText;
    }

    public boolean isFullScreen() {
        return FULLSCREEN == this;
    }

    public Mode other() {
        return isFullScreen() ? NORMAL : FULLSCREEN;
    }
}

Then, having added a properly initialized Mode field to the class, you can simplify your code to this :

final MenuItem fullScreen = MenuItemBuilder.create().text(mode.getToggleActionText()).build();

fullScreen.setOnAction(new EventHandler<ActionEvent>()
{
    @Override
    public void handle(ActionEvent e)
    {
        mode = mode.other();
        fullScreen.setText(mode.getToggleActionText());
        primaryStage.setFullScreen(mode.isFullScreen());
    }
});

view.getItems().add(fullScreen);

As you can see, it is a lot simpler to delegate the state dependent behavior to the Mode instance than to use an if whenever you have state dependent behavior.


Powershell to Convert HTML Table to Array of PSCustomObject

Parsing HTML

I won't lay into you too badly about using RegEx on HTML since you clearly already know it's a bad idea and are trying to parse it as XML instead. Not a bad idea.

I have to recommend HTML Agility Pack though. It is designed for HTML and it works well with imperfect HTML (unlike the XML parser which is very strict).

It seems to be designed with C# in mind but I've used it in PowerShell before with great success.

Also, you're relying on the parsing done by Invoke-WebRequest, which relies on Internet Explorer. This can have some side effects, for example it won't work on Server Core (because IE is not installed), and it won't work if it's run as a user who has never opened Internet Explorer before. It also sometimes messed up its check of whether IE is available.

Using agility pack won't rely on any of that. You can still use Invoke-WebRequest -UseBasicParsing to retrieve the page without doing the DOM parsing and it doesn't need IE for that call.

Aliases

This is a personal choice, but I don't like aliases in finished scripts that are intended to be reused. I would replace % with ForEach-Object and ? with Where-Object.

Create-Url

There's a bug in this. You accept a parameter called $Uri but refer to $url in the function body.

Once you fix that, it has another problem: it ignores the existing path of the passed in URI, and it ignores whether the form action is absolute (will break), relative with leading / (will work), relative with no leading / (will work when original URI has no path, but will break otherwise).

ConvertFrom-HtmlTableRow

if($headers[$i] -ne $null)

This could just be written as:

if($headers[$i])

ConvertFrom-HtmlTable

if ($headers -gt [System.String]::Empty)

You can use ![String]::IsNullOrEmpty($headers) for this, but really, it can be shortened to just:

if ($headers)


Syntax Error

In Cards.GetRandomCard(), the return statement is incorrectly indented.  (Also, I would recommend writing the return without parentheses.)

Style Conventions

Use lower_case_names for variables and methods.

For readability, please add one space after each comma, and one newline between functions definitions.

Modeling

Your Game class isn't useful.  You never set or use NameOfGame.  I recommend getting rid of the Game class altogether.

In a real-life card game, you would deal a card from the deck to each player, without replacement.  In your code, you deal with replacement (i.e., there is a chance of dealing the same card to both players).  A more realistic simulation would do a random.shuffle() on the array.  When dealing, you would pop() a card from the list to remove it from the deck.  51 is a "magic" number; you should use len(self.ActualCards) - 1.

Cards is really a Deck.  Rather than just a tuple of strings, you should have a Card class representing a single card.  The Card class should have a __str__() method that returns a string such as "Ace of diamonds".  If you also define comparison operators, then you can determine the winner using max(self.PlayerList, key=lambda player: player.CardForPlayer).

Expressiveness

In Python, you can usually avoid creating an empty list and appending to it:

self.ActualCards = [] #Empty List to Append
for Card in itertools.product(self.suits,self.values):
    self.ActualCards.append(Card) #Cartesian Product to Create Deck

Instead, you should be able to build it all at once:

self.actual_cards = list(itertools.product(self.suits, self.values))


Incremental Sieve of Eratosthenes Generator

// Unchecked because if it overflows, we don't really care, since primeCandidate would have overflowed earlier.
      unchecked { sieve[primeCandidate * primeCandidate] = primeCandidate; }

is wrong. For example, every int in the range 65537 to 80264 inclusive overflows to a value which is greater than itself.

The easy fix is to add an overflow check. That would also fix the memory problem, because sieve would have no more entries than there are primes below 65536.


This code is very easy to read, and very straightforward in its implementation. Nice work! Overall, it looks really good. I would say that it does follow abstraction and encapsulation fairly well. Below are some things that I think could be improved.
Functions Should Do 1 Thing
Your createList() function does 3 possible things:

Creates a new empty list with a set capacity
Creates a new list with double the capacity of an existing list, then copies the existing list to it
Creates a new list with half the capacity of an existing list, then copies the existing list to it

That's a little confusing. Also the name flag for the second parameter is not very helpful. If I were to keep the function as-is, I'd rename it to operation, or something like that to make it more clear. Usually a flag is a Boolean value of some sort. (It may be an int but is usually on or off.)
So I'd break createList() into 2 or 3 functions like this:
List* createList();
size_t setListSize(List* ptr, const size_t newSize);

Or you could break the second one into 2 functions, like increaseSize() and decreaseSize(), but I don't think that's necessary.
The new createList() function would just do what's inside of the if (flag == NEW_LIST) portion of your original function. For setListSize(), I'd pass in the new desired size. You can check inside the function if it's greater or less than the current size and do the appropriate thing. And the return value should be the size it was set to, which leads to my next point…
Handle Errors
None of your functions handle error cases. What if you attempt to increase the size of the list and you're out of memory? What if you want to reduce the size of the list, but can't allocate the smaller-sized array before doing the copy? With your current createList() function, it will return NULL, but none of the callers check that return value, so they could crash. Even worse, you allocate a List on the first line, then assume it worked and allocate the array. Then you assume that worked and start setting or copying to it. If any one of those steps fails, the next one will probably crash it.
If you return the size from setListSize(), the caller can check to make sure it worked and react appropriately if it didn't.
Modify the Existing List
Since your InsertItem() and DeleteItem() functions modify your list, the setListSize() function should too. Rather than create a new list, it would create the new array (either larger or smaller than the current one), do the copy, then free the existing one and replace it with the new one.


So, the only major comment I'd have on your code is that it's a bit hard to understand what's going on.  It becomes a lot easier when you have the Kata text to help, but ideally the code itself should be quite easy to understand just by looking at it.

I would split your code up into the seperate stages, rather than having a single function that does everything.  It should make it much easier to see what the code is actually doing at a glance.  There's also a few built in elixir  functions that you can use to simplify things.

So, essentially you have three stages:

Split the string into chunks.
Rotate or reverse each chunk.
Put the string back together.

I would write a function for each of these stages, then you can compose those functions to get the full process.

First, chunking.  You could do this manually, but there's actually already a function that does this in Elixir called Enum.chunk.  So you can convert the string into a list of it's unicode codepoints, chunk it, then join it back into a string, like so:

def chunks(str, sz) do
  str |> String.to_charlist |> Enum.chunk(sz) |> List.to_string
end

Next, we'll need a function to check if we should reverse or not.  You're implementation doesn't seem bad, but:

Elixir provides Enum.sum, which is easier than implementing the sum manually with Enum.reduce.
I would split the sum and the pow operations into two stages.
I wouldn't be afraid to use newlines and whitespace: it can be easier to read than a single line with a lot of operations going on.

So we could write this like:

def cube_digits(chunk) do
  chunk
  |> String.to_integer
  |> Integer.digits
  |> Enum.map(fn (x) -> x |> :math.pow(3) |> round end)
end

def should_reverse?(chunk) do
  (chunk |> cube_digits |> Enum.sum |> rem(2)) == 0
end

Your rotate code seemed fine, but lets pull it into a function:

def rot_left(chunk) do
  String.slice(chunk, 1, -1) <> String.first(chunk)
end

Then you can put this all together into a single function, making use of the into argument to for to join everything back together again:

def revrot(str, sz) do
  for chunk <- chunks(str, sz), into: "" do
    if should_reverse?(chunk) do
      String.reverse(chunk)
    else
      rot_left(chunk)
    end
  end
end

If you were performing some more complicated operations inside the for it might have been worth using pipes along with  Enum.map & Enum.join instead of for, but for this operation I think for ends up nice and concise.


Find if an array is arithmetic or geometric

I agree with @janos that sometimes returning a string and sometimes returning -1 makes this function hard to use.  In addition, it's unclear what your function is supposed to return for input that is both an arithmetic and a geometric sequence (every element is the same).

I find it odd that you base the difference and ratio on elements at indexes 1 and 2 rather than 0 and 1.  Such an arbitrary choice seems like an unnecessary failure mode for short input arrays.

Note that if the ratio is 0 or infinite, you can immediately declare the sequence to be not geometric.

A better approach is to assume that a sequence is arithmetic or geometric until proven otherwise.

function arithGeo(arr) {
    var diff = arr[1] - arr[0];
    var ratio = arr[1] / arr[0];
    var isArithmetic = true, isGeometric = isFinite(ratio) && ratio != 0;

    for (var i = 1, j = 2; (isArithmetic || isGeometric) && j < arr.length; i++, j++) {
        if (isArithmetic && arr[j] - arr[i] != diff) {
            isArithmetic = false;
        }
        if (isGeometric && arr[j] / arr[i] != ratio) {
            isGeometric = false;
        }
    }
    return isArithmetic && isGeometric ? 'both' :
           isArithmetic                ? 'arithmetic' :
                           isGeometric ? 'geometric'  : '';
}

For clarity, you might as well write it as two independent loops, because the classification problems are independent of each other.  There would be more lines of code, but the complexity of the algorithm remains the same.  Except in degenerate cases, only one of the loops is going to see much action anyway.

function arithGeo(arr) {
    var i, j;

    var diff = arr[1] - arr[0];
    var isArithmetic = true;
    for (i = 1, j = 2; isArithmetic && j < arr.length; i++, j++) {
        if (isArithmetic && arr[j] - arr[i] != diff) {
            isArithmetic = false;
        }
    }

    var ratio = arr[1] / arr[0];
    var isGeometric = isFinite(ratio) && ratio != 0;
    for (i = 1, j = 2; isGeometric && j < arr.length; i++, j++) {
        if (isGeometric && arr[j] / arr[i] != ratio) {
            isGeometric = false;
        }
    }

    return isArithmetic && isGeometric ? 'both' :
           isArithmetic                ? 'arithmetic' :
                           isGeometric ? 'geometric'  : '';
}


malloc()

In general, malloc may fail, and will return NULL when that happens, you should deal with that.

The result of malloc does not have to be cast to the target type, additionally it is usually safer to use the target variable in the sizeof expression.

stack *s = malloc(sizeof *s);
if (s == NULL) { // deal with it}

gets()

You have a buffer that is 100 chars wide, the long-deprecated gets() will just write over the end of the buffer, you should try and use fgets() e.g fgets(buffer, 100, stdin) or alternatively gets_s() if your compiler supports C11's optional Annex K.

Editing the string in place

Meaning changing the characters in the string without extra memory allocation. You're changing the string in place, this probably makes things much more complicated than they need to be. Using an input and an output string would clear things up. Using the pointer into the string rather than the string index might make things a little bit more readable as well. I don't think I would choose to edit the string in place unless I was forced to do it. Not shifting the string also makes it easier to visualize what's going on as you only have to move the index forward.

Accessing the string via an index

With char* buffer, buffer[i] and *buffer are equivalent; I'd probably trend more towards using the string pointer rather than the index, that might be a matter of taste.

Naming consistency

You have the node struct typedefed as SNode and the stack just typedefed as stack. It's easy to spot when someone is inconsistent, no matter if I agree with the style or not. Here there are two ways of how you define the struct and two ways (one capitalized, and the other not) of writing the typedef; stick to one way.

pop()

Popping an empty stack is a bug in most cases, if not you probably should treat it like a bug and assert on the empty stack. Returning \0 hides the fact that you tried to call pop on the empty stack making it harder to track down the bug

Warnings

isalpha() is defined in <ctype.h> which is not included

Bug

*+ab+cd is parsed as a + b * c + d and given operator precedence that is incorrect - the result should be (a + b) * (c + d).


Ok, first off: Passing in console.log as a paramater seems unnecessary. The function should have one task:

  Generate the skips

Then once you have the skips you can do whatever you want with it. So:

function skip(str, cb) -> function skip(str)

and:

skip('hello!', console.log); -> console.log(skip('hello'));

I would also not use a function within a function. I would try keeping the functions relatively small. Split the functions:

function skipHelper(val, index, arr) {
  var res = [];
  var i = index;
  var iterator = i + 1;
  for (i; i < arr.length; i += iterator){
    res.push(arr[i]);
  }
  return res;
}

function skip(str) {
  var input = str.split('')
  return input.map(skips);
}

Also, given that str.split('') isn't too much to explicitly write out, change:

  var input = str.split('')
  return input.map(skips);

To just:

  return str.split('').map(skips);

Also, your code doesn't run exactly as described. Add a .join('') to return res; and this should fix it:

return res; -> return res.join('');

All in all:

function skipHelper(val, index, arr) {
  var res = [];
  var i = index;
  var iterator = i + 1;
  for (i; i < arr.length; i += iterator){
    res.push(arr[i]);
  }
  return res.join('');
}

function skip(str) {
  return str.split('').map(skipHelper);
}

console.log(skip('hello!'));

There are probably some Javascript language specific stylistic choices I am missing, but this is for general code structure.


Getting rid of extra test during initialization of loop/recursion

You don't really need the helper function, the original maxesis pretty much equivalent to call maxes-helper with a sensible MIN_VALUE and empty sequence, so I refactored and joined both for you leveraging multi-arity

   (defn maxes
      "Returns a sequence of elements from s, each with the maximum value of (f element)."
      ([f s]
       (maxes f s Double/NEGATIVE_INFINITY '()))
      ([f s best-val collected]
      (if (empty? s)
        collected
        (let [new-elt (first s)
              new-val (f new-elt)]
          (cond (>  new-val best-val) (recur f (rest s) new-val  [new-elt])
                (== new-val best-val) (recur f (rest s) best-val (conj collected new-elt))
                :else                 (recur f (rest s) best-val collected))))))

Edited to replace nil by Double/NEGATIVE_INFINITY as suggested by @fmikes


Use with to handle file operations
A common way to handle files is by creating a file instance with open statement and closing it when you are done with the handler, while this would work, it is prone to error. What if you forget to close the file? It leads to either the file not saving or the handler might be corrupted with garbage. with automatically closes the file once operations on it are done. A simple example is as follow
with open('usernames.txt', 'r') as f:
    f.read()

Recursion is expensive
Your choices function uses recursion which might become expensive. Recursion creates temporaries in the stack frame and as it recur more and more, your stack frame might eventually be filled, though it can be elegant to solve a problem with recursion, limit it usage. Any function that can be written recursively can also be written with an iterative approach. Iterative approach tends to be faster and does not create temporaries
Consider reducing the complexity of choices
Right now choice does way too much, signs up a user and also login a user. Your functions should do just one thing and do it very well. The name choices is very misleading, from the name, I would expect it to make a choice or rather I make a choice among a list of values, rather is suprisingly signs up and login a user. Avoid function side-effect. Function side-effect is when a function promises one thing and does another.
Use a dictionary pair
I really think a dictionary is needed in this scenario. Dictionaries as we all know are very fast. Storing a key-value pair of username and password makes the code clean and easy to reason about.
Detour

You might want to use open('filename.txt', 'a') when you want to append to a file, using 'w' overwrites the content of the file and is similar to calling truncate on the file.

When you want to recieve string input, no need for this statement str(input("Enter")), input automatically recieves strings.

Avoid variable names suchh as f

This is an editted version of the code
def signup():
    with open("usernames.txt", 'r') as user:
        usernames = user.read().splitlines()
    with open("passwords.txt", 'r') as pwd:
        passwords = pwd.read().splitlines()

    info = dict(zip(usernames, passwords))

    print("Please Provide")
    username = input("Username: ")
    while username in info.keys():
        print("Username unavailable. Please Try Again.")
        username = input("Username: ")
    password = input("Password: ")

    with open("usernames.txt", 'a') as user:
        user.write(username + '\n')
    with open("passwords.txt", 'a') as pwd:
        pwd.write(password + '\n')

    print("Congratulations! You have successfully created an account. You may now login in.")

def login():
    with open("usernames.txt", 'r') as user:
        usernames = user.read().splitlines()
    with open("passwords.txt", 'r') as pwd:
        passwords = pwd.read().splitlines()

    info = dict(zip(usernames, passwords))
    username = input("Username: "))
    password = input("Password: "))

    if info.get(username, None) is None:
        print("Your username is either incorrect or nonexistent. You can either try again or create a new account.")
        signup()
        return

    if password != info[username]:
        print("Your password is incorrect. Please try again.")
        return

    print("Welcome Back " + username + "!")

if __name__ == '__main__':
    print("Please choose what you would like to do.")
    choice = int(input("For Signing Up Type 1 and For Signing In Type 2: "))
    if choice == 1:
        signup()
    elif choice == 2:
        login()


Algorithm to find all legal moves in Reversi game

Iteration
This:
for row_idx, row in enumerate(board):
    for column_idx, column in enumerate(board):
        if board[row_idx][column_idx] == -1:

is effectively incorrect. Is your board in row-major or column-major order? Whichever is true, you cannot iterate over the outer index of the board and get both a row and a column. What you likely meant instead is:
for row_idx, row in enumerate(board):
    for column_idx, cell in enumerate(row):
        if cell == -1:

Another problematic iteration is this:
i2, j2 = i, j
for _ in range(8):
    # ...
    i2 += i
    j2 += j

should simply be
for delta in range(1, 8):
    # ... use i*delta instead of i2
    # ... use j*delta instead of j2

Combined range checking
if row_idx + i < 0 or row_idx + 1 > (len(board) - 1) or column_idx + j < 0 or column_idx + j > (len(board) - 1):

should be
if not (0 <= row_idx + i < len(board)) or not (0 <= column_idx < len(board)):


public static string GetAvatar(this System.Security.Principal.IIdentity user)
{
    var service = SmObjectFactory.Container.GetInstance<IApplicationUserManager>();
    return service.FindByIdAsync(int.Parse(user.GetUserId())).Result.Avatar;
}

Do you know that you can access this static method not only as a extension method ? Assume the containing class is called UserExtensions one could execute this method using UserExtensions.GetAvatar(null) and if the creation of the service would take some time to be created it would nevertheless throw an ArgumentNullException. So adding a guard condition to the method like

if (user == null) { throw new ArgumentNullException("user"); }

would be a good idea.

Otherwise the method is looking good.

By using a private static ConcurrentDictionary<string, string> you could add caching to this like so

private static ConcurrentDictionary<string, string> avatarDictionary = new ConcurrentDictionary<string, string>();
public static string GetAvatar(this System.Security.Principal.IIdentity user)
{

    if (user == null) { throw new ArgumentNullException("user"); }

    string userId = user.GetUserId();
    string avatar;
    if (avatarDictionary.TryGetValue(userId, out avatar))
    {
        return avatar;
    }

    var service = SmObjectFactory.Container.GetInstance<IApplicationUserManager>();
    avatar = service.FindByIdAsync(int.Parse(user.GetUserId())).Result.Avatar;

    avatarDictionary.AddOrUpdate(userId, avatar, (key, oldValue) => avatar);

    return avatar;
}

Based on @mjolka's comment

  Using a ConcurrentDictionary as a cache in this manner could be problematic, depending on the number of users and the size of the avatars. As they say, "A cache without an expiration policy is another name for a memory leak."

you should add some mechanism to let the entries of the dictionary expire.

Like @DavidArno has correctly stated in his comment

  And now you have a global method with static state, which is not a good place to be.

this isn't the best way to do this. By having a static dictionary this just can't be tested correctly, because the dictionary keeps its content between tests which is a no go.

A better way would be to create an interface having the GetAvatar() method which is implemented by a simple class. The interface should then be constructor injected and stored in a private field.

public interface IAvatarService
{
    string GetAvatar(System.Security.Principal.IIdentity user);
}

public class AvatarService : IAvatarService
{
    private ConcurrentDictionary<string, string> avatarDictionary = new ConcurrentDictionary<string, string>();
    public string GetAvatar(System.Security.Principal.IIdentity user)
    {

        if (user == null) { throw new ArgumentNullException("user"); }

        string userId = user.GetUserId();
        string avatar;
        if (avatarDictionary.TryGetValue(userId, out avatar))
        {
            return avatar;
        }

        avatar = user.GetAvatar() // call of the extension method

        avatarDictionary.AddOrUpdate(userId, avatar, (key, oldValue) => avatar);

        return avatar;
    }
}

having a expire mechanism would still be needed and should be implemented.