using System;

If you're going to say using System then don't be putting lots of System.s in the file; the point of this is to eliminate those.

internal class Queue

Is the class intended to be subclassed? If not, seal it. You can always unseal it later if you need to design it for extension.

Why do you not implement IEnumerable<string> ? Surely one of the primary use cases of a collection is enumerating it.

There is nothing in here that is specific to strings; it would be just as easy to write Queue<T>.

private System.String[] _container

Using System.String, System.Int32 and so on is legal, but not idiomatic in C#. Use string, int, and so on.

public Queue(System.Int32 capacity = 5)

What led you to believe that 5 is the correct number here? The maintenance programmer in the future will want to know what the consequences are of changing it to 10 or 1 or a million. Document the things that are not obvious from the code, and avoid "magic numbers".

public bool IsEmpty() => Count == 0;

This could be a property.

    if(Count == _container.Length) ReSize(Count * 2);
    _container[_topHook++] = item;

You might consider making a private property Capacity:

private int Capacity => _container.Length;

And now your code reads better.

if(Count == Capacity) ReSize(Count * 2);

Remember, keep your code in the business domain as much as possible. The length of the container is a mechanism.

Use assertions to document your invariants. That way if you break them, you get informed in your tests:

    Debug.Assert(Count <= Capacity); // precondition of resize
    if(Count == Capacity)
      ReSize(Count * 2);
    Debug.Assert(Count < Capacity); // postcondition of resize

Do this throughout; any invariant you can think of, document it with an assertion. Like, the count goes up when you enqueue and down when you dequeue, and so on.

Now, of course, this code is still completely wrong.

Suppose the array length is 5, top is 0, bottom is 0.  We enqueue four strings, so top is 4, bottom is 0. Now we dequeue. Top is 4, bottom is 1.  Now we enqueue. Follow your logic:

count is 4 - 1 = 3
3 is not 5, so no resize
top increments to 5

Now we enqueue again

count is 5 - 1 = 4
4 is not 5, so no resize
and we dereference container[5], which is out of bounds.

Do you see your bug here?

The problem is that the condition you are attempting to avoid -- dereferencing out of bounds -- and the condition you are checking -- count vs capacity -- have nothing to do with each other. The code should be:

    Debug.Assert(_topHook <= _container.Length);
    Debug.Assert(Count <= Capacity);
    if (_topHook == _container.Length)
      ReSize(Count * 2);
    Debug.Assert(Count < Capacity);
    Debug.Assert(_topHook < _container.Length);
    _container[_topHook++] = item;

    _container[_topHook++] = item;

I understand that C programmers like this sort of thing. I don't. A line of code should have one effect, and this one has two, and requires that you correctly reason about the ordering of effects.  Write the code so that it is crystal clear:

    _container[_topHook] = item;
    _topHook += 1;
    Debug.Assert(_topHook <= _container.Length);
    Debug.Assert(Count <= Capacity);

if(IsEmpty()) throw new Exception("No Element In Queue");

Don't use Exception as anything but a base class in production code. This could be an invalid operation exception, or make your own exception.

    if(Count == _container.Length / 4) ReSize(Count * 2);

The logic here is correct, but is nowhere documented. The logic is: we wish to maintain two properties, first, that there is never more than a ratio of three to one for wasted space to used space, and second, that there is never a sequence of enqueue-dequeue or dequeue-enqueue operations that both cause an expensive resize. Give a justification here for why and how this logic maintains those invariants.

Consider also: who cares if we are "wasting" in a 4:1 ratio in the case where we have capacity 5 and count 1 ?  Resizing the array to size 2 in this case is a waste of time.  Consider taking a more sophisticated approach for small queues. Abstract the decision of whether to resize, and by how much, to a helper method that encapsulates that policy.

    var dequeuedValue = _container[_downHook++];
    _container[_downHook - 1] = null;

See what your obsession with putting the ++ in place has cost you? You do work in the decrement, and then you undo that work because you did it too soon! This is hard to reason about and a bug waiting to happen given any modification to this code.  If you find you are undoing work you just did, you are doing something wrong; write the code more clearly:

    var dequeuedValue = _container[_downHook];
    _container[_downHook] = null;
    _downHook -= 1;

"Resize" is a word; it's not "re size". So the method should be Resize, not ReSize.

As noted in the other answer the resize logic is wrong.  The correct logic is to copy all the elements from downhook to tophook-1 in the original array into 0 to count-1 in the new array.

Never just fix a bug. Ask yourself "how could I have better reasoned about this code so as to avoid the bug?" and "how could I have changed the design of the code so as to avoid the bug?"  For example:

Resizing a queue should not be affected in any way by the contents of the queue, and so if you are making a comparison against an element of the queue during a resize, you know immediately that you've done something wrong.

Also, resizing a queue should take as many operations as there are elements in the queue, but you do as many operations as there are in the array. So again, you could have known from first principles that the code was probably wrong.

Finally, this bug would have been never written in the first place had you made a generic Queue<T>, since there is no "null" T to use as a marker. Solving the more general problem is sometimes easier than solving a specific problem, because it forces you to not try to take advantages of specifics, like the nullability of strings.

Develop the ability to reason about these sorts of invariants, and you will find that you will write code that is more likely correct and better performing.

Also, there are already helper methods on Array to help you copy elements from one array to another, and added bonus, they are possibly faster than the code you're writing. Use them.

There's another bug in Resize. Suppose your user says that they expect the capacity to be 1000. Fine; we allocate a thousand items for the array. Then they do 250 enqueues and a dequeue. What happens? The capacity is reset to 500!

The user said that they had an expectation of how much storage they'd need, in order to cut down on the number of resizes on the way there. But you possibly give them a resize on the way to 1000 items.

Keep track of the user's capacity preference, and use that as the minimum array capacity; don't shrink to less than that. They said they're cool with using that much memory, so honour that request.

There is no logic in here that will help with debugging or testing. For example, it would be nice to see something like an implementation of ToString that dumps out a comma-separated list.

EXERCISE: Resizes are expensive; they are an O(n) operation, and so should be done as little as possible. Consider a queue where you enqueue a thousand items, then for the rest of the program you do enqueue-dequeue-enqueue-dequeue-enqueue-dequeue a few million times. How many resizes are there?

Plainly there could be zero resizes because the queue never grows in size beyond 1001 items in this scenario. And yet there are a great many resizes!  What can you do to eliminate resizes in this scenario?


I know you said you were fine with not using a parser combinator library like parsec, but I thought you might like to see the how the same thing might look using one, so I wrote an Attoparsec based parser for your data types:

{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE OverloadedStrings #-}

module IniParser where

import           Control.Monad               ( void )
import           Data.Attoparsec.Text        ( Parser
                                             , char
                                             , endOfInput
                                             , endOfLine
                                             , many'
                                             , many1
                                             , notInClass
                                             , parseOnly
                                             , satisfy
                                             , space
                                             )
import           Data.Map.Strict             ( Map )
import qualified Data.Map.Strict      as Map
import           Data.Text                   ( Text
                                             , pack
                                             )
import           System.Environment          ( getArgs )

type Ini = Map Text Section

data Section = Section
  { name       :: Text
  , properties :: Map Text Text
  } deriving (Show)

main :: IO ()
main = do
  [path] <- getArgs
  parseIniFile path >>= \case
    Right ini -> putStrLn $ "Parsed INI: " ++ show ini
    Left err  -> putStrLn $ "ERROR parsing ini: " ++ err

parseIniFile :: FilePath -> IO (Either String Ini)
parseIniFile iniFilePath = parseIni . pack <$> readFile iniFilePath

parseIni :: Text -> Either String Ini
parseIni = parseOnly ini

ini :: Parser Ini
ini = do
  defaultSection <- lexeme (Section "" <$> (Map.fromList <$> many' property))
  namedSections  <- lexeme (many' section)
  void $ endOfInput
  let allSections | null (properties defaultSection) = namedSections
                  | otherwise = defaultSection:namedSections
  pure . Map.fromList . map (\section -> (name section, section))
    $ allSections

section :: Parser Section
section = Section <$> sectionName <*> (Map.fromList <$> many' (lexeme property))

sectionName :: Parser Text
sectionName = char '[' *> sectionNameChars <* char ']' <* endOfLine

sectionNameChars :: Parser Text
sectionNameChars = pack <$> many' (satisfy $ notInClass "]\r\n")

property :: Parser (Text, Text)
property = (,) <$> propertyName <*> (lexeme (char '=') *> propertyValue)

propertyName :: Parser Text
propertyName = pack <$> many' (satisfy $ notInClass "=\r\n\t ")

propertyValue :: Parser Text
propertyValue = pack <$> many' (satisfy $ notInClass "\r\n")

lexeme :: Parser a -> Parser a
lexeme p = whitespace *> p <* whitespace

whitespace :: Parser String
whitespace = many' space

I think the main strength of the approach is self pretty self-evident.  It eliminates all the multi-line lambdas, the entire foldr, etc. which (at least IMHO) really obscures the essence of what the code is expressing.

Additionally I've restricted the use of qualified imports to a single one usage where I think it makes the code more readable, though your taste may vary.

You can see the whole stack based project here if you're interested.


Bash - Automating creation of test files

Add a shebang.
Keep naming consistent, I personally prefer and follow Google's style guide; you may use a different guide if available.
Try to make your script POSIX compliant, for a wider target reach (no need to rely on [[ expression from bash)
Define a function to create the test directory.
Use shellcheck.
The echo "Directory and __init__.py created." should happen after the creation has happened.
Use mkdir -p to allow for nested directories to also be created (if needed).
Let script throw error and stop as early as possible on errors. This is achieved with set -e.

Together:
#!/bin/sh

set -e

dir_name="$1"
file_name="$2"
test_dir="test/${dir_name}"
file_in_dir="${test_dir}/${file_name}.py"

add_file() {
    if test -f "${file_in_dir}"
    then
        echo "File already exists in directory, exiting."
        exit 0
    else
        touch "${file_in_dir}"
    fi
}

create_dir() {
    mkdir -p "${test_dir}"
    touch "${test_dir}/__init__.py"
    echo "Directory and __init__.py created."
}

[ ! -d "${test_dir}" ] && create_dir "${test_dir}"

add_file

The chunk of variable declarations (dir_name, file_name etc.) could also be localised to functions.


Read Twitter direct messages and check messages for links

Your get-url function could just use get-in:

(defn- get-url [message]
  (get-in message [:entities :urls 0 :expanded_url]))

links-from-direct-messages has quite a lot of nested calls.  When you've got a bunch of nested operations like that it can be nice to re-write them using one of the threading macros (-> and ->>).  These take an input, and then "thread" it through a series of forms as the first (in the case of ->) or last (in the case of ->>) argument.  By doing this, they allow you to rewrite nested calls sequentially.

This is mentioned in the style guide you linked.

In the case of links-from-direct-messages you're calling map and filter, which both accept the collection as their last argument, so you can use ->>:

(defn links-from-direct-messages []
  (->> (direct-messages :oauth-creds oauth-credentials)
       :body
       (filter trusted-user?)
       (filter has-url?)
       (map get-url)))


When working with number theory problems like this, efficiency improvements are usually found more in math than in code.

Let us deal with the first problem: For large primes, the factorials overflow. We can deal with this by finding the remainder the factorial leaves on dividing by p^2 instead of the factorial itself.

int factorialremainder(int n, int mod) {
    if(n == 1) {
        return 1;
    } else {
        return (n*factorial(n-1))%mod;
    }
}

Now how do we check whether a number is Wilson prime? Easy. Just check whether (factorialremainder(p-1, p*p) + 1)%(p*p) == 0.

That brings us to the next point, you seem to not know how to use the remainder operation. You can find the remainder on dividing x by y using x%y. x is divisible by y iff x%y == 0. You don't need to do (float(i)/j == i/j) gymnastics anymore.

Finally, your primality testing can be improved a lot. Most numbers have small factors so it actually makes sense to run the loop over j in the reverse direction. Also, you don't need to go till i-1, square root of i is enough. So to find primes you can just do

bool isprime(int n) {
  // Assuming n > 1
  for(int i = 2; i*i <= n; ++i) {
    if(n%i == 0) return false;
  }
  return true;
}

Actually, since you are interested in finding all primes upto a certain range, you should try using some method like Sieve of Eratosthenes.

Also, stack is a very weird data structure to use for the problem. Why not just use a vector?


If this is a reinventing-the-wheel question, let's check whether you actually reinvented union:

import Data.List (union)
import Test.QuickCheck

union' :: (Eq a) => [a] -> [a] -> [a]
union' = ...

prop_union :: [Int] -> [Int] -> Property
prop_union xs ys = union' xs ys === union xs ys

main = quickCheck prop_union

It will fail after some tests:

*** Failed! Falsifiable (after 4 tests and 2 shrinks):
[]
[1,1]
[1,1] /= [1]

While your union' returned [1,1] on [] [1,1], Data.List.union returned [1]. That's because it's left-biased. In order to actually reinvent the wheel, you need to get rid of duplicates on the second list:

union' :: Eq a => [a] -> [a] -> [a]
union' xs [] = xs
union' [] ys = nub ys

But it gets weirder. While the left hand side is allowed to have duplicates, elements on the right hand side that were already in the left hand side need to get discarded:

union "Hello" "World" == "HelloWrd"

However, your current version discards elements from the left hand side:

union' "Hello" "World" == "HeWorld"

Your version is right-biased. The original list xs should be contained completely:

union' xs ys = xs ++ deleteDuplicatesAndXSElements ys

The deleteDuplicatesAndXSElements is left as an exercise. If you define it correctly, you can get rid of all the other cases.

By the way, I don't agree with the previous answer concerning ++. Appending is a problem if you do it over and over again, since (a ++ b) ++ c will have quadratic runtime instead of linear with a ++ (b ++ c), but here you're doing it once.

Last but not least, don't use not .. elem. notElem is a function in Prelude.


Produce a nearly sorted (or K sorted) array

When you use a class in a 'hacky' way, like you do by using a PriorityQueue as a TreeSet, you should make sure that you document why the class is used, and what properties of the class are being leveraged.

Your code does not work in O(n log(k) ) time because it uses a PriorityQueue, which has O( log(n) ) time-complexity for add():

  Implementation note: this implementation provides O(log(n)) time for the enqueing and dequeing methods (offer, poll, remove() and add); linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size)

Your algorithm is not correct for the requirements given:

For a start, it will fail for input where the input array is smaller than k. It will throw an ArrayIndexOutOfBoundsException.
Secondly, you are working in k+1 space instead of k. Why? Where is the comment?

Further, because you auto-box all your values to Integer, from int, you have a significant performance penalty. If you keep your data as primitives (and use an array of primitives rather than a PriorityQueue), you will have better results.

The algorithm you need you use is strongly hinted at by the complexity requirement...

O( n log(k) ) strongly implies that you need to iterate over each value once, and, with that element, there is an O(log(k)) way to sort it.

For the loop, think a for-loop. For the log(k), think a binary search....

for (int i = 0; i < data.length; i++) {
    int from = i > k ? i - k : 0;
    int val = data[i];
    int pos = Arrays.binarySearch(data, from, i, val);
    if (pos < 0) {
        pos = -pos - 1;
    }
    System.arraycopy(data, pos, data, pos+1, i - pos - 1);
    data[pos] = val;
}


Sorted unidirectional list with add, delete and find

For starters, you should read PEP 8, the Python style guide. A few things that jump out from your code:

Variable names should be lowercase_with_underscores, not dromedaryCase.
Docstrings go inside the function body, not above the header.
Always put newlines after if, elif and else for multi-line statements. You do it inconsistently, which makes your code quite hard to follow.

Following these guidelines will make your code easier for other Python programmers to read.

Here are some brief, general comments on your code:

Pick better variable names. In the init function for the List class, you’ve got the variable name list. Pick something more meaningful (such as unidirectional_list, or whatever is appropriate).

Although List and Element aren't keywords, they are sufficiently generic that I’d suggest picking different ones.
Difference between __str__ and __repr__. The goal of __repr__ is to generate a string which can be eval()'d to return an equivalent object; the goal of __str__ is to return a human-readable interpretation.

The __repr__ method in List looks like it should really be __str__, and the __repr__ method for Element returns a singleton rather than something I can eval() to get another instance of the Element class.

See a question about this on Stack Overflow for more details.
Use a list comprehension in the __repr__/__str__ for List. Since we know that element.first is a Python list (although it’s not obvious from the attribute name; I’d suggest changing it), we can rewrite this using a list comprehension, then use join to construct the string. This is better than repeatedly appending to a string.

So you'd have something like:

def __str__(self):
    return '\n'.join(str(e) for e in self.first)

which is a lot cleaner.
Be explicit about comparisons to None. Maybe it’s just me, but I think x is not None is better than x != None.
Don't put examples/tests in the body of the script. At the bottom of the code are a few examples, which are helpful when I'm trying to review the code, but not in general use. Right now, if you import the file, all of those bits run and litter your output.

Either wrap them in an if __name__ == '__main__' block (see this Stack Overflow question for details), or consider using a dedicated library for tests. Then these examples will be executed if the file is run directly, but skipped if you import it in a larger file.


Service Locator with Lazy Loading in Swift

This is mostly good, but it can be improved.
You might want to constrain the Resolver and Register protocols to classes. Since you want to share instances this won’t work with structs.
protocol Register: class { ... }

Your store property doesn’t have to be lazy. Initializing an empty dictionary is cheap, so you can do that directly when your LazyServiceLocator is initialized.
The biggest issue I found is the ObjectIdentifier you use as the dictionary key. You don’t store the type of T (which would be T.self) but the type of the type of T - it’s metatype. I’m not quite sure if this can lead to problems, but it is unnecessary. Just use ObjectIdentifier(T.self).
The other thing you might want to consider is renaming your register(reference:) method to register(factory:). Calling something that creates an object reference is rather uncommon.
And finally you might want to consider adding an overload for resolve that takes the requested type as a parameter:
extension Resolver {
    func resolve<T>(_ type: T.Type) -> T {
        return resolve()
    }
}

With that you can write let x = resolve(Foo.self) instead of let x: Foo = resolve(). IMHO this is a bit more readable.


Implementation of Mahalanobis distances using Eigen

Is it effecient

Imposable to tell as we have no idea how stuff in Eigen is implemented.

Comments on code:

There should be some logic in the ordering of includes. So you can easily find ones that have been included or spot missing ones (or know where to put knew ones).

#include <iostream>
#include <Eigen/Dense>
#include <fstream>
#include <Eigen/Cholesky>

This set seems to be completely random. Personally (though the exact orders does not matter and you can pick your own scheme) I put them in groups (so in this case there would be an Eigen group and a standard lib group). Then I order the groups most specific to most general. Within the groups I am less pedantic but usually it is alphabetical unless there is some good reason to use another scheme.

#include <Eigen/Cholesky>
#include <Eigen/Dense>

#include <iostream>
#include <fstream>     // I usually group all the stream stuff together
                       // Then all containers then all the others in the standard lib.
                       //

Avoid the using-directive. In non trivial programs it causes more problems than it is worth. For short programs the extra cost of prefixing objects (in terms of typing) is negligible so prefix your types and objects (don't be lazy). (I always use std::cout not cout). If you feel this is too much work then selectively bring types/objects into the current namespace with a using statement.

using namespace Eigen;
using namespace std;

Prefer to prefix types/objects with their namespace
If you must selectively bring types/objects into current namespace

using std::cout;
using std::endl;

If you must do this then scope the using to minimize polution.

Try to not use using namespace X;

Does x change in the following code? If not then pass by const reference to indicate that it is not modified.

VectorXd mah(MatrixXd& x){

One variable per line:

 int p = x.cols(), n=x.rows();

This is a nasty trick to temporarily comment out blocks.

/*  ofstream file("test1.txt");
    if (file.is_open()){
            file <<  m << '\n';
    }
/**/

It is so easily broken that I would avoid it.
If you want to comment out a block then use #if 0

// To uncomment block just replace 0 with 1.
#if 0
    ofstream file("test1.txt");
    if (file.is_open()){
            file <<  m << '\n';
    }
#endif


I can't imagine any good reason for drawing an F using that approach.  Drawbacks include:

It is not obvious at all, just from looking at the code, what the expected output is.
Not only is the code hard to read, it is also hard to write and modify.
Using many small System.out.print() calls is very inefficient.

A solution like this, for example, is much easier to understand.  It would also be more efficient, since all of the output is done in one System.out.print() call.

public static final String F =
    "*****\n" +
    "*    \n" +
    "*****\n" +
    "*    \n" +
    "*    \n";

public static void main(String[] args) {
    // Print with 2x magnification
    System.out.print(F.replace("*", " *").replace("\n", "\n\n"));
}


Java Stream - Collections - remove duplicates based on string and presence/absence of local date value

Simplification

The code can be simplified using built-in methods from the Comparator API.

public int compareTo(Unique rhs) {
    Comparator<Unique> reverseDateComparator = (a, b) -> {
        LocalDate thisDodel = a.getDateOfDeletion() == null ? LocalDate.now().plusDays(1) : a.getDateOfDeletion();
        LocalDate thatDodel = b.getDateOfDeletion() == null ? LocalDate.now().plusDays(1) : b.getDateOfDeletion();
        return thatDodel.compareTo(thisDodel);
    };
    return Comparator.comparing(Unique::getName).thenComparing(reverseDateComparator).compare(this, rhs);
}

The reverseDateComparator is primarily used to handle null values. However, there are the built-ins comparators nullsFirst and nullsLast that exist just for this: they wrap an existing comparator and turn it null safe, by considering null values either greater or lower than non-null values.

As such, you can rewrite this method with:

@Override
public int compareTo(Unique rhs) {
    return Comparator.comparing(Unique::getName)
                .thenComparing(Unique::getDateOfDeletion, Comparator.nullsFirst(Comparator.reverseOrder()))
                .compare(this, rhs);
}

This directly passes the method-reference Unique::getDateOfDeletion to thenComparing and compares the dates by placing null values before other values and non-null in their reverse natural order (so that the most recent date is sorted before).

Using static imports makes the code a bit cleaner also. With the following imports,

import static java.util.Comparator.comparing;
import static java.util.Comparator.nullsFirst;
import static java.util.Comparator.reverseOrder;

the methods becomes very readable with regard to the initial goal (compare by name, then compare by dates reversed with first no deletion date):

@Override
public int compareTo(Unique rhs) {
    return comparing(Unique::getName)
                .thenComparing(Unique::getDateOfDeletion, nullsFirst(reverseOrder()))
                .compare(this, rhs);
}

In the same way, the following:

Comparator<Unique> uniqueComp = (a, b) -> a.getName().compareTo( b.getName() );

can be written:

Comparator<Unique> uniqueComp = Comparator.comparing(Unique::getName);

equals needs to be overriden

Since your Unique class implements Comparable, it is strongly recommended to let it override the equals method, and have a consistent implementation.

In this case, the equals should simply verify the equality of both the names of the date of deletion. To handle null values, you can make use of Objects.equals: this method returns true when the two given objects are either both null or both not-null and equal with regard to equals.

Other comments

Do you really need setters in your Unique class? Consider making that class immutable.
You have a trailing comma in

return "Unique [name=" +name + ", dateOfDeletion="+dateOfDeletion+"],";

Does it make sense to allow a null name? If not, you can validate that it is always present in the constructor with requireNonNull. Also, since the date of deletion might be null, a constructor overload without it may be simpler for the client.


C/C++ code to do customized string comparing

First pick a language.

Either use C or use C++. Do NOT use a mixture of the two (its sloppy and can introduce bugs). So first off you should have picked a language. You seem to have picked both:

 #include <cmath>                         // C++
 printf("%d\n", my_compare("ab", "1"));   // Why use printf in C++
                                          // It is obtuse dangerous (not type safe).

The two languages have a basic similar syntax but they are different languages treat them as such.

Know what is available from the standard libraries:

bool is_num(char x) {return (x>='0' && x<='9');}

This exists in the standard library as std::isdigit()

If this is C++ why are you passing C-Strings around.

int get_num(const char* s, int len)

Much better to write:

int get_num(std::string const& s)

Also there is no point in writing this function (especially since it is error prone to do so.

In c++ use operator>> to stream to an int.
In C use sscanf(s, "%d%n", &value, $length).

Also your variable names are bad. Pick names that make it easy to read the code and understand what you are doing.

    int j = 0;
    int ret = 0;
    while (len > 0)
    {
        // Why add the extra complexity of `j++` here.
        // You have made the expression hard enough to read as it is.
        // You don;t get points for being clever in an interview its readability
        // we want to see.
        ret += (s[j++] - '0') * pow(10, len-1);
        len --;
    }
    return ret;
}

Yes in C it is traditional to put all the variables at the top of the function (so fine for C). But in C++ this is considered bad practice and sloppy. Declare variables as close to the point you want to use them (preferably just before you use them). That way you can see the type at the point you are using them.

        int value1 = 0;
        int value2 = 0;
        bool is_t1_num = false;
        bool is_t2_num = false;
        int len_t1 = 0;
        int len_t2 = 0;
        const char*  t1;
        const char*  t2;

You are repeating the same processes twice.
First you scan over the string finding the length of the number.
Second you scan over the string calculating the value of the number.
There is no need to do that. Use one pass.

            while(is_num(*t1)&&(*t1))
            {
                len_t1 ++;
                t1++;
            }
            value1 = get_num(s1, len_t1);

Also you have the same boilerplate code for both t1 and t2. If you have code that does the same thing factor it out into a function.


CSS Good Practice on a JavaScript Plugin

You styles are pretty solid, it's mainly your selectors that have issues I feel. Here are some notes:

It's normally best to not include the type of element if it has a class. This is for maintainability and extensibility purposes, you could switch in
 for
 with less work for example. Inversely, if all
's have the same style, they don't even need the same class.
You never want to go too deep with you CSS selectors, more specific is less flexible.

/* Bad */
div.paginateContainer > ul > li.paginateActive > a

/* Good*/
.paginateContainer .paginateActive a

Avoid the use of the direct descendant > selector where ever possible, again it just locks your CSS down and makes it less flexible. I recommend only ever using this if you need it to add styles to a legacy application or have a situation where you have a hierarchy something like this that doesn't make sense to add different classes.

These target different elements

.menu > li { /* ... */}
.menu li { }

See in this situation putting a .submenu class on the inner
 won't make a different, .menu li will still target both.
Try to keep your selectors consistent, for example you refer to both ul.paginateList and ul to mean the same thing.
I would add a different class to your first
 so you don't need to refer to it as ul:first-child, you may want to change the order in the future for example. Maybe only include .paginateList on the first
.
Due to your use of specific pixel font sizes your plugin may require modification in order to be used on someone's site. Generally these days we use 'ems' which represent the size of the character 'M'. Currently your font-size is fixed at 18px and it will not change whatever site you put it on, using font-size:1.2em for example would scale to be 20% larger than the font-size of the element containing .paginateContainer.

It also allows for better mobile support, taking advantage of the default font size set by the user. This does require a bit of work though as you should apply it to padding, border-radius, line-height, font-size and min-width (everything except border-size).

And here is your modified CSS

.paginateContainer {
    display : block;
    text-align: center;
}

.paginateContainer ul {
    display: inline-block;
}

.paginateContainer li {
    /* Better to state the display explicitly */
    /*display: inherit;*/
    display:inline-block;
}

.paginateContainer a {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    text-decoration: none;

    /* Put the cursor rule on :hover */
    /*cursor: pointer;*/

    line-height: 20px;
    padding: 4px 12px;
    background-color: #ddd;
    color: #08c;
    font-size : 16px;
    min-width: 16px;
    float: left;

    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;

    /* Select None */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.paginateContainer a:hover {
    color : #fff;
    background-color: #2ae;
    border-top: 1px solid #2ae;
    border-bottom: 1px solid #2ae;
    cursor:pointer;
}

.paginateContainer ul:first-child .paginatePrevious a {
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    border: 1px solid #ccc;
    font-size : 18px;
    font-weight: bold;
}

.paginateContainer ul:first-child .paginatePrevious a:hover {
    border: 1px solid #2ae;
}

.paginateContainer ul:first-child .paginateNext a {
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    border: 1px solid #ccc;
    font-size : 18px;
    font-weight: bold;
}

.paginateContainer ul:first-child .paginateNext > a:hover {
    border: 1px solid #2ae;
}

.paginateContainer ul:last-child a {
    border-radius: 10px;
    font-size: 18px;
    font-weight: bold;
}

.paginateContainer ul:last-child {
    float: right;
}

.paginateContainer .paginateActive a,
.paginateContainer .paginateActive a:hover {
    color : #fff;
    cursor: default;
    background-color: #08c;
    border-top: 1px solid #08c;
    border-bottom: 1px solid #08c;
}

.paginateContainer ul:first-child .paginateDisabled a,
.paginateContainer ul:first-child .paginateDisabled a:hover {
    color : #bbb;
    background-color: #eee;
    cursor: default;
    border: 1px solid #ddd;
}

EDIT: As for you question about why I've used  tags instead of the class. It's a similar situation to why I've referred to your lists as ul and not .paginateList, the class literally provides no additional information because every single  tag has the class present. Changing it to use a instead of .paginateAnchor will make both your HTML and CSS more lightweight.

I also noticed just now that you're using inline styles applied with your JavaScript.

This would be an ideal situation to use classes, the elements that are inline-block can have no class (which will use div.paginateContainer > ul > li { display:inherit; }) and the hidden elements can have a class called .hidden. The reasoning for this is separation of concerns, your JavaScript should not need to do any styling, instead it should offload that detail to your CSS so everything is in one place.


Pretty good for a self-taught beginner, keep going like this and you're golden!

Recursion and infinite loop

This is probably the worst part of the script:

def remove_selection():
    while True:
        try:
            to_remove = int(input('To remove a selection enter the number of the selection you want removed here. >>> '))
            if to_remove <= len(playlist_):
                break
        except ValueError:
            print('Enter a number.')
            remove_selection()
        try:
            playlist_.pop((to_remove - 1))
            break
        except (IndexError, UnboundLocalError):
            print('Enter a vaild number')
            remove_selection()

An infinite loop, a misused exception handling,
an incorrect error handling, and recursive calls...
This is confusing and more complicated than it needs to be.

You can replace the recursive calls with continue.

Exception handling for converting the input to integer is appropriate, because there is no better way. It is not appropriate for validating the input is within range, because a better way exists using conditionals.

Also, it's not enough to check that the index is less than the length of the list, you also need to check that it's 0 or greater.

UnboundLocalError is thrown when trying to access a variable that hasn't been assigned. That's not an exception to catch, it indicates a problem in the logic that needs to be fixed.

Here's one way to address these issues:

while True:
    try:
        to_remove = int(input('To remove a selection enter the number of the selection you want removed here. >>> '))
    except ValueError:
        print('Enter a number.')
        continue
    if not (0 < to_remove <= len(playlist_)):
        print('Enter a valid number (within range: 1..{})'.format(len(playlist_)))
        continue
    playlist_.pop(to_remove - 1)
    break

Global variables

Try to avoid global variables as much as possible.

For example, instead of this:

def number_of_selections():
    while True:
        try:
            global number
            number = int(input('How many files would you like to add to playlist? >>> '))
            break
        except ValueError:
            print('Enter a number.')

It would be better to make the function return the number:

def number_of_selections():
    while True:
        try:
            return int(input('How many files would you like to add to playlist? >>> '))
        except ValueError:
            print('Enter a number.')

And then adjust the callers appropriately to pass the number as parameter where needed, for example instead of:

number_of_selections()
get_selections()

Write:

get_selections(number_of_selections())

Adjust the rest of the code accordingly, and try to eliminate the other global variables too, all_media and playlist_.
For these two, another good alternative will be to create a class, where these variables will be member fields.

Simplifications

Instead of this:

if ok == 'yes' or ok == 'y':

A bit simpler way to write:

if ok in ('yes', 'y'):

Optimizing imports, and coding style

The script is not actually using sys, so you can drop that import.

And the style guide recommends to import one package per line, like this:

import os
import random

Do read the style guide, it has many other recommendations that apply to your script.


Faster way to create linked list of length n in Python

The current algorithm has a failure in using the list_concat during list creation. The list_concat function walks to the end of the list for each node you want to add. So adding a node becomes O(n). This means creating a list of 10,000 items takes 1+2+3...+10,000 steps. That's O(n*n) performance.

As hinted, you should add the next node in the creation loop. You then get code that looks like this (I left out the list_concat function as it's not used):

class Cell(object):
  def __init__(self, data, next=None):
    self.data = data
    self.next = next

def create_list(length=1):
  linked_list = Cell(0)
  head = linked_list
  for prefill_value in xrange(1, length):
    head.next = Cell(prefill_value)
    head = head.next
  return linked_list

You could also create the list in reverse order, allowing you to immediately fill the next attribute of the Cell. Your create_list function then looks like this (the reversed function should not be used for really huge lengths (several million) because it's created in-memory):

def create_list(length=1):
  tail = Cell(length - 1)
  for prefill_value in xrange(length - 2, -1, -1):
    tail = Cell(prefill_value, tail)
  return tail


I am not sure about the overall algorithm but there are better ways for finding LCM. You should use a different algorithm. Try Euclid's algorithm to find the GCD.
Then calculate result(your LCM) in main() as
result = (lowerbound * upperbound)/gcd(lowerbound upperbound);
The problem with your LCM function is that subtraction isn't the best way for finding the GCD which you are currently doing. It will take too long. Just consider the case of x = 1 and y = 100000. It should be easy to see that number of subtractions is much higher in this case and the program would be very slow.

If you don't want to change the algorithm(which you should) then the least optimization that I can think is to not declare n1 and n2 separately in the function lcm. Just use x and y. Do the final division by the product in the main function. It will at least save you 2 variables.

EDIT
I came up with a much better optimization. In your main loop instead of going from the outside pairs i.e (1, n-1) to the inside pairs you would do much better by going from the inside.
Example

5 = (1,4) and 5 = (2,3). The maximum is found at 5 = (2,3).
7 = (1,6) , 7 = (2,5) and 7 = (3,4). The maximum is at 7 = (3,4).

The answer is in the middle. You'll get it without a loop.
But there is a big problem. This reasoning works only for odd numbers. I tried writing down numbers on paper and solved it by hand. I'll need some more time to find out a pattern for even numbers.
But for odd numbers this is probably the best optimization.
EDIT2
In the main function instead of
if(result >= max) you should be using if(result > max). What is the use of replacing the number with the same number? One less operation.
You don't need to initialize counter at the beginning. You are doing that in the for loop.
EDIT3:
For the case of even numbers the maximum lcm will be either lcm((input/2)-2, (input/2)+2) or lcm((input/2)-1, (input/2)+1). It's easy to find which will be maximum without calculating both of them.
If input/2 is even then lcm((input/2)-1, (input/2)+1) should be maximum otheriwse it should be lcm((input/2)-2, (input/2)+2).

EDIT After OP's Update 1
How about this as a better code
#include<stdio.h>

int main(void)
{
    int input, result;
    printf("Enter the input = ");
    scanf("%d",&input);

    while (input <= 0)
    {
        printf("Enter a positive non zero number :");
        scanf("%d",&input);
    }

    // (x % 2) used as a condition in C means checking x for odd number
    int middle = input/2;
    result = input % 2  ? (middle % 2 ? middle * middle - 4 : middle * middle - 1)
                        :  middle * (middle + 1);

    printf("Result = %d",result);
    return 0;
}

Removed unnecessary braces, spaces, comparisons and comments. Comments are needed but commenting obvious things is just noise. I prefer single space on both sides of operators.


In general if you have a goto statement, you should reorder your code to not need it. In this case, your code actually tries 9 times, not three, because you await client.GetAsync 3 times, and then jump back to your goto label up to 3 times.

The simple fix in this case is to remove the extra response=await... calls, enclose the entire try/except block in a loop and break or return if the call is successful. Something like:

for (int i = 0; i < 3; i++){
    try
    {
        HttpResponseMessage response = await client.GetAsync("jobs/" + id);
    }
    catch (CantConnectExcept as ex){
        await Task.Delay(2000);
        continue;
    }

    if (!response.IsSuccessStatusCode){
        await Task.Delay(2000);
        continue;
    }

    jobJson = await response.Content.ReadAsStringAsync();
    return JsonConvert.DeserializeObject<Job>(jobJson);
}
return null

It doesn't sound like waiting more seconds on later failures is important. If you find it is important, you can do something like:

List<int> waitTime = new List<int> {2000, 2000, 7000};
...
await Task.Delay(waitTime[i]);


Just from looking at both classes, CRUD_color is essentially putting methods on top of Color but those methods seem like something you'd want in Color. I would ask yourself what the purpose CRUD_color serves that Color should not. If there is no reason for the 2nd class, then get rid of it.

I would recommend overloading the __get() operator and get rid of the get methods, it'll clean things up a little bit in your first class.

Also I wouldn't have create_color accept an array of parameters, instead be explicit with what the values need. If you don't want to take this advice, then at least do some error checking for when those parameters don't exist in the array.

...Also I think CRUD_color should probably be static, or at least right now it seems like you are treating it as a static class. If you want it to act like a class which is inheriting from Color I would instead have a constructor and initialize a Color object which is a data-member of CRUD_color.


Regex - Input Checker Class - Lambda with two lists

I would tackle this problem by not adding the last regex to the list but to have this as a separate regex. Using a little "trick" by using Enumerable.Range() you can replace the for with a linq expression like so
if (Enumerable.Range(0, 4).Any(i => !regexList[i].IsMatch(dataFile[i]))) { return false; }

After the loop you have this line
var listOfMoves = dataFile.Select(x => x).Skip(4).ToList();

in which you neither need the call to Select() nor to ToList().
In the next line
var areaAnyMoveSequencesInvalid =
            listOfMoves.Select(x => regexList[4].IsMatch(x)).ToList()
            .Any(y => y == false);

A simple call to Any() would be sufficient but you could just return the value of a call to All() instead like shown below.
If the method in question is called quite often you should consider to use compiled regex. They take a little bit more time to create them but executing them will become faster. If you take this way you should initialize the regexes in the static constructor.
Summing this up will lead to
public static class DataChecker
{
    static DataChecker()
    {
        regexList = new List<Regex>();
        regexList.Add(new Regex("^\\d\\s\\d$", RegexOptions.Compiled));
        regexList.Add(new Regex("^(\\d,\\d )*(\\d,\\d)$", RegexOptions.Compiled));
        regexList.Add(new Regex("^\\d\\s\\d$", RegexOptions.Compiled));
        regexList.Add(new Regex("^\\d \\d [NESW]{1}$", RegexOptions.Compiled));

        lastRegex = new Regex("^[RLM]{1}( [RLM]{1})*$", RegexOptions.Compiled);
    }
    private static readonly List<Regex> regexList;
    private static readonly Regex lastRegex;
    public static bool IsGameInputDataValid(string[] dataFile)
    {
        if (dataFile.Length < 5) { return false; }

        if (Enumerable.Range(0, 4).Any(i => !regexList[i].IsMatch(dataFile[i]))) { return false; }

        return dataFile.Skip(4).All(x => lastRegex.IsMatch(x));
    }
}

Without knowing what the input looks like I can't come up with a better name for the last regex. In addition this isn't tested but should work like a charme.


Rövarspråket Language Encoder and Decoder

Your program has an unused import: import string. You can use tools like flake8, pylint to catch such errors.
I ran your code at pep8online and it pointed out 3 errors:

E302:3:1:expected 2 blank lines, found 1
E302:8:1:expected 2 blank lines, found 1
E302:15:1:expected 2 blank lines, found 1

Basically this means there should be two empty lines after imports, class definition, function definition. Check PEP 8 for more details.

VOWELS variable is well suited to be a global variable. Plus you can convert it to a string to make it easier to read: VOWELS = 'AEIOUYÅÄÖ'.
str.upper() is redundant as str objects already have upper methods, hence letter.upper() in VOWELS is all you need. Similarly str.lower() call can be changed to character.lower().
Note that the in check already returns boolean, hence unless you are trying to be extra explicit you can reduce those 3 lines to return letter.upper() in VOWELS.
You can assign word[i] to a variable inside the while loop to make it easier to read: character = word[i]. Plus i can renamed to better variable like index.
For case insensitive comparison you probably want to read up this thread: How do I do a case insensitive string comparison in Python?

Lastly add annotations to your function definitions so that it becomes more clear what type of arguments a function is expecting and what it returns. Function annotation can also be used to static analysis tools like mypy to catch errors beforehand.

VOWELS = 'AEIOUYÅÄÖ'

def main() -> None:
    word = input('Enter Phrase : ')
    final_word = rövarspråket(word)
    print(final_word)

def is_vowel(letter: str) -> bool:
    return letter.upper() in VOWELS

def rövarspråket(word: str) -> str:
    new_word = []

    for character in word:
        new_word.append(character)
        if character.isalpha() and not is_vowel(character):
            new_word.append('o' + character.lower())

    return ''.join(new_word)

def decode_rövarspråket(word: str) -> str:
    original_word = []
    i = 0
    while i <= (len(word) - 1):
        character = word[i]
        original_word.append(character)
        if character.isalpha() and not is_vowel(character):
            i += 3
        else:
            i += 1
    return ''.join(original_word)


Generally speaking I find a good implementation and like the simplicity of the approach. I would point out some problems I found though.

Inconsistent MVVM style

You are using two different ways to instantiate views and viewmodels and linking them together in both views, an inconsistence that could get bigger the and messier the more complex the program becomes.

In the MainPage you're creating the viewmodel in the view's constructor, and assigning it to the BindingContext right away. But in the LoginPage you create the viewmodel in the handler of the main page and pass it to the constructor of the view (not show here, but I guess it also assigns the BindingContext with it).

Specially for bigger applications, it's important to clearly define one style, either view first or viewmodel first, and live with it (I don't even know if it's called "style", but it sounds like that to me). A more concerning problem is that when VMs begin to take dependencies on services and other stuff, you most likely will want to use an IoC container for injecting them, and then it becomes more important to clearly define who'll create viewmodels and how. Personally, I like viewmodel-first approach, in which viewmodels create other viewmodels and are passed to the views.

MainPage viewmodel

Why are ShowLoginModal and HideLoginModal plain public fields? In situations like this, I would expect them to be normal events, raised from the viewmodel and handled in the view. This way feels a bit non-standard.
On the ShowLoginModalCommand method, the viewmodel creates the login viewmodel directly. Maybe its unnecesary now, but consider using an IoC container or other factory to create this, as generally when other viewmodels take extra dependencies it becomes harder to create them all inline.
The Customer setter doesn't needs to be public, a private one will do. You only want to set the current user from the login and nowhere else, so make that crystal clear.
The invocations of the ShowLoginModal and HideLoginModal delegates don't contain a null validation, and will result in a NullReferenceException if no one suscribed to them. A nice shortcut to call them safely is to use the ShowLoginModal?(lvm); syntax.

LoginPage viewmodel

Beware of the async reentrancy in the LoginCommand method. The VerifyLogin call inside it could potentially be a slow one, but since it's an await call, the UI will remain responsive. That means the user could do other things in the meanwhile, including changing the user/password or even click the login button again! That could have many unanticipated effects. I would counter it by disabling the UI while the verification takes place, using something like this in the VM:
public bool EnableForm { get; set; }
public ICommand LoginCommand => new Command(async () =>
{
    //Disable UI before doing anything
    EnableForm = false;
    OnPropertyChanged(nameof(EnableForm));
    var customer = await VerifyLogin(); // Assume valid login.
    LoginSucceeded(this, new LoginSuccessEventArgs(customer));
}

And in the view bind the controls to that property:
<Button Command="{Binding LoginCommand}" Text="Login" IsEnabled="{Binding EnableForm}"/>

In the LoginSuccessEventArgs the Customer property doesn't needs to be read-write. Once again, since you're just informing a value, there is no benefit in changing it after creation. Also, the constructor should check for null on the customer passed.
Possibly it's not shown here or just a work-in-progress thing, but there is no handling of the login failure case, that should just reenable the controls (following my above suggestion), show some error message to the user and not raise the LoginSuccess event.
Like in the main page, the raising of the event is not null checked and will blow up if nobody happens to be suscribed.
The call to the VerifyLogin method, although maybe simplified here, could imply a lot of work under the cover. That's the kind of thing that's better delegated to a service to do all the heavy work, and just have the presentation layer handle the visual thing. I would inject it in the constructor and call it passing the user/password entered, and it would return success or failure. Something along the lines of this:
private readonly ILoginService _loginService;
public LoginViewModel(ILoginService loginService)
{
    if(loginService == null) throw new ArgumentNullException(nameof(loginService));
    _loginService = loginService;
}
public ICommand LoginCommand => new Command(async () =>
{
    var customer = await _loginService.VerifyLogin(Username, Password);
    if(customer == null)
        //show some error message here
    else
        LoginSucceeded(this, new LoginSuccessEventArgs(customer));
}


Refactored 2 functions into 1 - Verify UPC/EAN13 barcode

Some thoughts:

Why would you silently trim() and potentially transform an invalid bar code value into a valid one?  This would seem to give unexpected results.  If a string value needs to be trimmed, let the caller do it before calling this method.
What happens if you are not passed a string? To me this might be an exceptional event and worthy of throwing exception from this function, as this is something the developer writing code calling this function needs to be aware of.
Do you really want to use is_numeric() to validate the input format?  This can lead to false positives (for example +123.45678e9 would pass your current format check). If what you are expecting are 12 or 13 digits in this string, then precisely test for that. In addition to your questionable use of is_numeric(), you also have your length conditions set inappropriately.  You should be using OR between the digit criteria and length criteria as either cause failure.  Right now a string like foobar will actually pass your conditional because it does not satisfy both conditions.

For example:

if (!preg_match('/^[0-9]{12,13}$/', $barcode)) {
    return false;
}
// rest of code

or

if (!ctype_digit($barcode) || $bcLen < 12 || $bcLen > 13) {
    return false;
}
// rest of code

I think the logic to determine check digit can be done in a more simplified manner. Part of this simplificatoin could be to explictly convert the barcode string to an array to make it easier to work with. I have done a function rewrite below which I hope demonstrates some simplification.

Example:

function isValidBarcode($barcode)
{
    if (!is_string) {
        throw new InvalidArgumentException('String value expected.');
    }
    if (!preg_match('/^[0-9]{12,13}$/', $barcode)) {
        return false;
    }
    $barcodeArray = str_split($barcode);
    $lastDigit = (int)array_pop($barcodeArray);
    $sum = 0;
    for($i = 0; $i < count($barcodeArray); $i++) {
        $sum += (int)$barcode[$i];
        if ($i % 2 === 0) {
            $sum += (int)$barcode[$i] * 2;
        }
    }
    $checkDigit = 10 - ($sum % 10);
    return $lastDigit === $checkDigit;
}

Be careful using loose comparisons as your default means for comparing.  I would suggest you get in the habit of using exact comparisons as default unless there is good reason to do loose comparison.  I don't see any actual bug in this code (since PHP's built-in type juggling should take care of string to integer conversions in your specific use case here).  Bu,t you might not always be so lucky. PHP's loose typing can be useful, but it can also be a source of hard-to-identify bugs.  To me when reading code, I would like the code writer to explicitly demonstrate their understanding of types being applied to the variables.
Style-wise, I have a few concerns.  You are mixing camelCase and snake_case in your code.  Ideally you should pick one style and stick to it (though PHP as a language is not very good about this).  There are too many comments, most of which are not really necessary. You also have inconsistent spacing around your = assignments near the end of code. Trying to horizontally-align assignment operators can be a bit of a fool's errand if you try to do this throughout your codebase. Every time you want to make changes to variable names and such, you end up having to redo spacing.  Is it worth it?
Why are you concerned with the "efficiency" of this code?  Are you planning to execute this code thousands of time in any one script execution such that every millisecond spent in this function gets compounded?  If not, you might be prematurely optimizing this bit of code.  Sure, you want to make sure it runs with reasonable efficiency (which I think your code does since it is such a simple data structure - a string - that you are working with), but I don't think you want to necessarily squeeze out every millisecond out of this function if it means making the function hard to read or maintain.  That code quality aspect should likely be you primary concern with a function such as this which you are not likely to spend a large percentage of your overall processing time in.


Adding to a dictionary and skipping duplicate keys

Generating and handling exceptions is considered to be an expensive operation, so if(! x.ContainsKey()) is better. Yeah, the code example I see in MSDN uses try/catch but that's to illustrate the exception not advocate that as "best practice."  Documentation I've read is pretty adamant about not throwing exceptions needlessly.

And you don't need try/catch to trap the duplicate key; just an else to the above if.


Its pretty good:

Don't do this:

using namespace cv;
using namespace std;

Its a bad habit that one day will get you into a lot of trouble. The reason the namespace names are so short is so that adding std:: or cv:: before identifiers is not overburdensome.

Read more about the issues: Why is “using namespace std” considered bad practice?

I suppose this is valid:

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

But most people use this:

int main(int argc, char* argv[]) {
                         ^^^^   => argv: argument value
                       ^     ^^ => Easier to see its an array of pointers rather **
             ^^^^               => argc: argument count

Declare variables at point of usage.

In C++ we don't tend to declare all the variables at the top of the function. It is much nicer to declare them just before you use them. Remember all objects have constructors that are run so declaring it before you need it may cost you in execution if you don't need it.

But the main reason is that types are important. If you declare it at the point you use it then it becomes easy to see the type and thus reason about it. If I have to scroll back to the top of the function it makes it hard to keep track of thing.

Streams can detect when they have gone bad.

Not opening the file is not the only type of error. So only testing for that seems like a short cut that may backfire.

    if (!textFile.is_open()) {
        return -1;
    }

I would use:

    if (!textFile) {    // If a std::fstream is used in a boolean context
        return -1;      // it converts itself to bool be checking is_good()
    }                   // which will fail if you can't read from it in any
                        // way.

Not sure if that is true for VideoCapture type (have a look). But given the read works like a std::stream (see the while loop) I am suspecting it does.

    if (!vid.isOpened()) {
        return -2;
    }

Prefer pre-increment

        for (int i = 0; i < curFrame.rows; i += 1) {
            for (int j = 0; j < curFrame.cols; j += 1) {

Sure that works. But prefer ++i (or ++j). It is more idiomatic. Also when you start incrementing using iterators the pre-increment is the cheapest increment.

Don't need found

                bool found = false;
                if (curPixel[j][0] != pastPixel[j][0]) {
                    numDiff += 1;
                    found = true;
                } else if (!found && curPixel[j][1] != pastPixel[j][1]) {
                    numDiff += 1;
                    found = true;
                } else if (!found && curPixel[j][2] != pastPixel[j][2]) {
                    numDiff += 1;
                }

Each of those pieces of code are completely unique. Because you use else only one of those branches can be executed.

I would simplify and write as:

            numDiff += ((curPixel[j][0] != pastPixel[j][0]) ||
                        (curPixel[j][1] != pastPixel[j][1]) ||
                        (curPixel[j][2] != pastPixel[j][2]))  ? 1 : 0;

Based on Toby's comments this can be simplified too:

            numDiff += curPixel[j] != pastPixel[j] ? 1 : 0;

Cloning is probably expensive

        pastFrame = curFrame.clone();

Have your tried to see if a move operation exists?

        pastFrame = std::move(curFrame);

Don't manually close files

    textFile.close();

Unless you are checking to see if the close worked and generating an error message when it fails. Otherwise just let the constructor call close and throw away any potential exceptions that are generated.

On the same note. Do you really need to manually release the vid?

    vid.release();

Version 2

#include "opencv2\opencv.hpp"
#include <fstream>

int main(int argc, char* argv[])
{
    std::ofstream textFile("diffs.txt");
    if (!textFile.is_open()) {
        return -1;
    }

    cv::VideoCapture vid("E:\\videos\\video.mkv");
    if (!vid.isOpened()) {
        return -2;
    }

    int numFrames = 0;

    cv::Mat pastFrame;
    vid.read(pastFrame);

    cv::Mat curFrame;
    while (vid.read(curFrame)) {
        int numDiff = 0;
        for (int i = 0; i < curFrame.rows; ++j) {

            cv::Vec3b* curPixel = curFrame.ptr<cv::Vec3b>(i);
            cv::Vec3b* pastPixel = pastFrame.ptr<cv::Vec3b>(i);

            for (int j = 0; j < curFrame.cols; ++j) {
                numDiff += curPixel[j] != pastPixel[j] ? 1 : 0;
            }
        }
        numFrames += 1;
        double size = curFrame.rows * curFrame.cols;
        textFile << numFrames << ","
                 << fixed
                 << setprecision(2) << numDiff / size * 100
                 << "\n";
        pastFrame = curFrame.clone();
    }
}


You don't give us much context for this problem, so it's unclear to me exactly what you are trying to achieve. But in your example, you have a pair of NumPy arrays containing integers in the range 0–2, and you seem to want to count the number of occurrences of each pair of values.

So I suggest encoding pairs of integers in the range 0–2 into a single integer in the range 0–8, using numpy.bincount to do the counting, and then using numpy.reshape to decode the result, like this:

>>> import numpy as np
>>> x, y = np.random.randint(0,3,200000), np.random.randint(0,3,200000)
>>> counts = np.bincount(x * 3 + y).reshape((3, 3))
>>> counts
array([[22282, 22093, 22247],
       [22084, 22295, 22396],
       [22012, 22243, 22348]])

A quick check that I got the encoding/decoding right:

>>> counts[0,2] == np.count_nonzero((x == 0) & (y == 2))
True

This runs much faster than the code in your question (assuming I have interpreted your profile screenshots correctly):

>>> from timeit import timeit
>>> timeit(lambda:np.bincount(x * 3 + y).reshape((3, 3)), number=1000)
2.7519797360000666


Scrabble algorithm review and performance suggestions

If what you are trying to do is store a huge list of valid words in such a way that you can test whether a given string is a valid word, a Trie works well.  See this Stack Overflow question.

Load the wordlist into the Trie when your server starts, and use the same Trie for all games (assuming this is a client server game).  It's trickier than the linked thread if you need to include more than the standard 26 letters of the alphabet, but I've done a Unicode Trie for a chat filter before and I could help if you need that.

I don't understand what you are trying to do with the rearrange method.  Can you explain?


IRepository Pattern - Interface Segregation Principle

The ISP is indeed taking a beating with all these NotImplementedException. If we boil this interface a little (ok a lot), we get this:

public interface IRepository<TEntity>
{
    TEntity Find(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);
}

These two should always be implemented, assuming all entity types can at least be selected. I haven't included GetById because it makes things more complicated, and it's really Find all over again (especially when you have an entity with a composite PK).

That said, TEntity Find(...) feels a bit awkward: one could expect a "Find" method to return more than a single result, like FindAll does. I think it's the naming that's off: Find should be Single, or perhaps Select (consistent with the LINQ method that does the same thing), and then FindAll could become Find.

IQueryable<TEntity> shouldn't be permitted to exist beyond the data access layer - there's no reason FindAll can't materialize the query itself and return an IEnumerable<TEntity> instead, making sure that any further LINQ code on the client side doesn't get to the database.

I'd make Find return an IEnumerable<TEntity>.

Now to keep the ISP happy, we'd have an IInsertable<TEntity>, an IUpdatable<TEntity> and an IDeletable<TEntity>, respectively with Insert, Update and Delete methods; a repository that supports updates will implement IUpdatable<TEntity>, and a repository that doesn't support deletions won't implement IDeletable<TEntity>.

I don't think it's ideal, but it strips the repository interface down quite a bit - in fact it could even be renamed ISelectable<TEntity> at this point. An ApiController would use an IInsertable<Invoice> to insert an invoice in a method, and an IDeletable<Invoice> to delete that invoice in another method - and both methods would actually be dealing with an InvoiceRepository.


Don't hard-code your transformation

With your current approach, as soon as you are faced with a new PairType or StimType you will have to adjust your function accordingly to account for them. What your current code is doing is really a hard-coded version of a wide-form to long-form conversion of the column data - and Pandas has methods to allow you to do that in an automated way.

Two options would be df.melt, or a combination of df.unstack and reset_index.

Either way, after this step you'll nearly be all the way there.

>>> model_err.melt(var_name='PairStim', value_name='Err')

   PairStim     Err
0      fan1  0.0000
1      fan1  0.0625
2      fan1  0.0625
3      fan2  0.0000
4      fan2  0.0000
5      fan2  0.0000
6     foil1  0.0000
7     foil1  0.0625
8     foil1  0.0000
9     foil2  0.1250
10    foil2  0.1250
11    foil2  0.3125

The only other step in automation is to split the PairStim column up into its components, and do some cleanup. Wrapping this up in your function:

def longform_model_error(model_err: pd.DataFrame):
    melted = model_err.melt(var_name='PairStim', value_name='Err')
    melted[['PairType', 'StimType']] = (
        melted['PairStim'].str.extract('(\w+)(\d+)', expand=True)
    )
    melted['PairType'] = melted['PairType'].str.capitalize()
    melted['StimType'] = melted['StimType'].astype(int)
    return melted.drop('PairStim', axis='columns')

Comments on your current approach

Consider using the .size attribute on a Series (or the .shape attribute) instead of len. This makes it more clear to me that model_err.fan1 is indeed a Pandas type.
If you did want to hard-code the transformation for some reason, creating a DataFrame for each group and concat-ing them together is not ideal - you might as well remain in NumPy-land for as long as possible before turning it into a DataFrame. You would also benefit from hard-coding the separate columns instead of separate rows, as the dtypes of the columns are homogeneous, so you'd avoid the subsequent casting. Perhaps something like

def longform_model_error_hardcode(model_err: pd.DataFrame):
    n_per_type = model_err.shape[0]
    pair_types = ('Fan', 'Foil')
    stim_types = (1, 2)
    n_stims = len(stim_types)

    cols = {
        'Err': model_err.values.ravel('F'),
        'PairType': np.repeat(pair_types, n_per_type*n_stims),
        'StimType': np.tile(np.repeat(stim_types,
                                      n_per_type),
                            n_stims)
    }
    return pd.DataFrame(cols)

This will be faster, though if you were to go down the hard-coding avenue there isn't really much point in using Pandas at all if you're not performing other operations on the data - might as well just stick to NumPy in that case.
Nitpicking, df_plotable and new_model_err don't really help me understand what the function is supposed to do, or how new_model_err is different from the input DataFrame. Try and use some more descriptive variable names.


Removing duplicate characters from a string

Design.

Do you actually need to count all the characters?
I would just record that I had already moved them as I moved them from source to destination.

std::set<char>  moved;
std::copy_if(str.begin(), str.end(), newstring.begin(), [&moved](const auto& value) {
    return moved.insert(value).second;
});

Comments

To be honest I don't find your comments objectionable. Maybe slightly too many but not egregiously so.

Remember do not make your comments describe the code. If I can read the code the I will not need the comments. You should use comments to describe WHY and the code shows HOW.

 // Loop over the array
 for_each(array.begin(), array.end() ,

That's a bad comment as I can read the code and see that it loops over the array I don't need the comment to tell me that. Bad comments are worse than no comments. So best to write Self Documenting Code (this just means your variables and function names should be descriptive so I can read the code and understand what is happening).

Code Review.

Don't need the {} to default construct an empty table.

    std::map<char, unsigned int> ctable{};

Rather than std::for_each I would use the new range based for.

    std::for_each(str.begin(), str.end(), [&ctable](const auto& value) {
        ++ctable[value];
    });

    // try
    for(auto value: str) {
        ++ctable[value];
    }

I would avoid the resize() and prefer reserve() in this situation.

    std::string newstring = "";
    newstring.resize(str.size());

Then when inserting into newstring I would use a back inserter. The reserve() makes sure that you will never need to reallocate the space but you don't make the string too long. Then use the back inserter to increase the size of the string as needed. At the end you don't need to shrink to fit.

    std::copy_if(str.begin(), str.end(), std::back_inserter(newstring), [&ctable](const auto& value) {
        return ctable.erase(value) > 0;
    });

The new version of the standard has added std::begin() and std::end(). Prefer to use these rather than the member functions. This will help when your code is templatized and somebody passes an array rather than a standard container.

std::string removeDuplicates(const std::string& str)
{
    std::set<char> moved;
    std::string    result;
    result.reserve(str.size());

    //Only copy one character of each type to the new string
    std::copy_if(std::begin(str), std::end(str),
                 std::back_inserter(result),
                 [&moved](const auto& value) {return moved.insert(value).second;}
                );

    return newstring;
}


Validating Shift class through builder pattern

Don't be mad at me because I will again suggest you a different approach than your current implementation that exists in .Net for exactly that purpose, this is, validating models ;-)

But first a few comments about this one.

The ShiftBuilder requires a collection of validators to build the object IEnumerable<IShiftValidator>. This is a good start because you can use various validations however the current ones don't follow this principle yet. The example you showed has two responsibilities, this means it validates two things:

if (shiftToValidate.Duration.TotalMinutes <= 0)
{
    FailedValidationException = new ArgumentOutOfRangeException(nameof(shiftToValidate.Duration));
    FailedValidationMessage = "Shift's duration cant be less than 1 minute.";
    return false;
}
if (shiftToValidate.Duration.TotalHours > SharedSettings.MaximumShiftHours)
{
    FailedValidationException =
        new ArgumentOutOfRangeException(nameof(shiftToValidate.Duration));
    FailedValidationMessage = "Shift's duration cant be longer than the maximum allowed hours.";
    return false;
}

There are two ifs where each can fail. This means you need to split this validator into more specific one to test only one condition at a time.

Other then this I find this is a very complex implementation that leads me to the alternative suggestion which uses the ValidationAttribute. C# already has a system for constructing model validations. Here's a small example.

You can create a bunch of custom attributes that you use to decorate the properties of the Shift class with.

public class Shift
{
    public string Name { get; private set; }
    public TimeSpan StartHour { get; private set; }

    [GreaterThen(nameof(StartHour))]
    public TimeSpan EndHour { get; private set; }

    [GreaterThenZero]
    public TimeSpan Duration => EndHour - StartHour;

    public Shift()
    {
        // Just an example to make the validation fail.
        StartHour = TimeSpan.FromSeconds(100);
        EndHour = TimeSpan.FromSeconds(50);
    }
}

There are various ways of implementing them so you'll need to read more about them to know all options. I show you one of them where they implement the IsValid method in a very generic way (might not be perfect yet but it should make the point).

So you may need one attribute to validate the Duration:

public class GreaterThenZeroAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return
            ((IComparable)value).CompareTo((IComparable)TimeSpan.FromSeconds(0)) > 0
                ? ValidationResult.Success
                : new ValidationResult($"{validationContext.MemberName} must be greater then zero");
    }
}

but on the other hand if you add GreaterThenAttribute the GreaterThenZeroAttribute for the Duration is no longer necessary.

public class GreaterThenAttribute : ValidationAttribute
{
    private readonly string _otherPropertyName;
    public GreaterThenAttribute(string otherPropertyName)
    {
        _otherPropertyName = otherPropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var otherProperty =
            validationContext
                .ObjectType
                .GetProperty(_otherPropertyName)
                .GetValue(validationContext.ObjectInstance);

        return
            ((IComparable)value).CompareTo((IComparable)otherProperty) > 0
                ? ValidationResult.Success
                : new ValidationResult($"{validationContext.MemberName} must be greater then {_otherPropertyName}");
    }
}

You may however need a new attribute for

shiftToValidate.Duration.TotalHours > SharedSettings.MaximumShiftHours

to make sure the duration does not exceed a certain number like MaxHoursFromSettings etc. and you can read the actual value from the settings later.

Finally to invoke the validation you use the Validator

var shift = new Shift();
Validator.ValidateObject(shift, new ValidationContext(shift), true);


Job shop scheduling with Clojure's core.logic

A terser way to write sort-tasks would be:

(sort-by (juxt :job :id) tasks)


Find two numbers that add up to a given total, from a formatted string

Improved algorithm

You can significantly reduce the memory requirements of your algorithm by not creating any objects, including avoiding Maps, Sets, and String concatenations (the +s you use in print statements). You only need to use a constant amount of memory, comprised completely of primitives stored on the stack (avoiding garbage collection).

You can significantly reduce the time requirements of your algorithm by using a simple trick that allows you to scan the input list only once by moving toward the middle from the left and the right.

public final class SumPairs {
    public static final void printSumPairs(final String input) {
        final int inputLength = input.length();

        // On the left, move to the very first number.
        int leftStartIndex = 0;
        int leftEndIndex   = input.indexOf(',', 1);
        int leftNumber     = parseIntFromSubstring(input, leftStartIndex, leftEndIndex);

        // On the right, move to the very last number.
        int rightEndIndex   = input.lastIndexOf(';', inputLength - 2);
        int rightStartIndex = input.lastIndexOf(',', rightEndIndex - 2) + 1;
        int rightNumber     = parseIntFromSubstring(input, rightStartIndex, rightEndIndex);

        // Figure out the desired sum.
        final int desiredSum = parseIntFromSubstring(input, rightEndIndex + 1, inputLength);

        boolean noOutputYet = true;

        while (leftStartIndex < rightStartIndex) {
            final int currentSum = leftNumber + rightNumber;

            if (currentSum > desiredSum) {
                // On the right, move to the previous distinct number.
                int oldRightNumber;
                do {
                    oldRightNumber = rightNumber;

                    rightEndIndex   = rightStartIndex - 1;
                    rightStartIndex = input.lastIndexOf(',', rightEndIndex - 2) + 1;
                    rightNumber     = parseIntFromSubstring(input, rightStartIndex, rightEndIndex);
                } while ((rightNumber == oldRightNumber) && (leftStartIndex < rightStartIndex));
            }
            else {
                if (currentSum == desiredSum) {
                    if (noOutputYet) noOutputYet = false;
                    else System.out.print(';');

                    System.out.print(leftNumber);
                    System.out.print(',');
                    System.out.print(rightNumber);
                }

                // On the left, move to the next distinct number.
                int oldLeftNumber;
                do {
                    oldLeftNumber = leftNumber;

                    leftStartIndex = leftEndIndex + 1;
                    leftEndIndex   = input.indexOf(',', leftStartIndex + 1);
                    leftNumber     = parseIntFromSubstring(input, leftStartIndex, leftEndIndex);
                } while ((leftNumber == oldLeftNumber) && (leftStartIndex < rightStartIndex));
            }
        }

        if (noOutputYet) System.out.print("NULL");
        System.out.println();
    }

    // Java 7 and later's String#substring creates a new char[] array just about every time it's used.
    // Since Integer#parseInt requires a full String, we'd have to let String#substring create a lot of char[]s if we used Integer#parseInt.
    // We'd like to avoid that to reduce memory requirements and to eliminate garbage collection.

    // WARNING: This method doesn't actually check whether there is a valid number.
    //          That's your job!
    private static final int parseIntFromSubstring(final String str, int start, final int end) {
        int result = 0;
        final boolean negative = str.charAt(start) == '-';
        if (negative) start++;

        for (; start < end; start++)
            result = 10*result + str.charAt(start) - '0';

        if (negative) return -result;
        else return result;
    }

    public static final void main(String[] args) {
        printSumPairs("1,2,3,4,5,6;6");
    }
}

Critiques

Problem statement

The part about outputting "NULL" should be in the section about output, not the section about input.
The characters in the input are not fully specified. Will there be spaces or other characters to ignore mixed in? Can numbers have a decimal point? Can numbers be negative? Are newlines separators for separate problems to solve?
The CodeEval challenge says not to output duplicate pairs. For example "3,3,3,3;6" should output "3,3", not "3,3;3,3;3,3;...".

Your solution

The problem statement says to read lines from a file, but your algorithm doesn't do that.
You don't need to sort the array of ints. The problem statement says they'll already be sorted.

Time complexity

Your code shouldn't be regarded as \$O(3n)\$ for a few reasons:

Big O notation ignores constant multiples like 3. It should be \$O(n)\$, not \$O(3n)\$.
You use Arrays#sort when you don't need to. While it uses a nicer version of quicksort than normal, it still has a \$O(n^2)\$ worst case time complexity.
If you're limiting your algorithm to a list of unique 32-bit integers, there's only so many of those available to put in your input list. This means that there will be an input that takes the longest amount of time to produce an answer. This means that you have a constant upper bound on the time needed, which makes your algorithm (including your 'naive' one) \$O(1)\$.

If you're not limiting your algorithm to a list of unique 32-bit integers, then you should realize that it takes a lot longer to add together two integers with billions of digits than it does to add 1 and 2. The time complexity of addition is \$O(m)\$, where \$m\$ is the number of digits in the largest number in the input list. This means your complexity will be \$O(mn)\$.


Rendering column headers, some of them with a cellRenderer attribute

Passing undefined in for cellRenderer should be the same as not passing it in at all. Because of this, the duplication can be removed by doing the following:

{headers.map((header, i) => {
  return (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
      cellRenderer={header.index ? this._generateCheckbox : undefined}
    />
  )
})}

Alternatively, you can build up an extraProps object and then spread it into the column.

{headers.map((header, i) => {
  let extraProps = header.index ? {
    cellRenderer: this._generateCheckbox
  } : {}
  return (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
      {...extraProps}
    />
  )
})}


The code is reasonably clear and obvious, but has some severe inefficiencies.

First, let's pick up some simple oversights.  Both isPalindrome() and longestPalindrome() ought to have internal linkage (using either the static keyword or the anonymous namespace), and the str arguments should be reference to const:

namespace {
    bool isPalindrome(const std::string& str);
    int longestPalindrome(const std::string& str, std::string& palindromeStr);
}

In passing, we can simplify the interface of longestPalindrome().  It doesn't need to return the string and its length; if we simply return the longest palindrome, then obtaining the length is trivial:

    std::string longestPalindrome(const std::string& str);

    // main() can now look like:
    //   std::string palindromeStr = longestPalindrome(str);
    //   std::cout << palindromeStr.size() << '\n';
    //   std::cout << palindromeStr << '\n';

The next oversight is that std::string::length() returns a std::size_t, so don't compare it with (signed) int:

for (std::size_t i = 0, j = str.length()-1; i<j; ++i, --j)
//   ^^^^^^^^^^^

Note that I've left a bug there (that's neatly missed because we always call this with a non-empty string): if str.length() is zero, then j starts at a very large positive value (because the subtraction is unsigned, and wraps).

BTW, there's a neat way to test a string for symmetry (at the expense of repeating the initial comparisons), using <algorithm>:

static bool isPalindrome(const std::string& str)
{
    return std::equal(str.begin(), str.end(), str.rbegin());
}

Now to the matter of efficiency.  We're creating new string objects for every possible substring of the input.  That's a lot of copying.  We could reduce that by using std::string_view.

That's only part of the way towards an efficient solution, though.  We really need to change the algorithm.  My recommendation is to iterate over each character as a possible mid-point of an embedded palindrome, and at each position, determine what's the longest palindrome possible from there (in most cases, it will be 1 or 2 chars).  There's no need to consider longer substrings centred on that position once you have a failing case, so that eliminates much of the unnecessary work we're doing here.

Hint: for this we can use std::make_reverse_iterator() and std::mismatch().

Finally, the single test we have in main() isn't really enough.  At a minimum, we want examples of odd- and even-length palindromes, and also check that we handle the trivial case of empty string as input.

Update - using iterators

I've developed the idea I hinted at in the second section; there's probably a little more scope for reducing duplication:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <string_view>

namespace
{
    template<typename Iter>
    // requires BidirectionalIterator(Iter)
    void updateBest(Iter forward_start,
                    Iter forward_end,
                    std::reverse_iterator<Iter> backward_start,
                    std::reverse_iterator<Iter> backward_end,
                    std::string_view& best_so_far)
    {
        auto span = std::mismatch(forward_start, forward_end,
                                  backward_start, backward_end);
        auto start = span.second.base();
        auto end = span.first;
        std::string_view candidate{ &*start, static_cast<std::size_t>(std::distance(start, end)) };
        if (candidate.size() > best_so_far.size()) {
            best_so_far = candidate;
        }
    }

    std::string_view longestPalindrome(const std::string& str)
    {
        std::string_view best_so_far;

        // Work out from the middle of the string
        auto const halfway = (str.size() + 1) / 2;

        // first, loop from midpont to end of string (but we can stop
        // when there's no room for a bigger palindrome)
        for (auto i = str.begin() + halfway;  i + best_so_far.length()/2 < str.end();  ++i) {
            // test for odd-length palindrome
            updateBest(i, str.end(),
                       std::make_reverse_iterator(i), str.rend(),
                       best_so_far);
            // test for even-length palindrome
            updateBest(i + 1, str.end(),
                       std::make_reverse_iterator(i), str.rend(),
                       best_so_far);
        }

        // then, loop from midpont to beginning of string (but stop
        // when there's no room for a bigger palindrome)
        for (auto i = str.rbegin() + halfway;  i + best_so_far.length()/2 < str.rend();  ++i) {
            // test for odd-length palindrome
            updateBest(i.base(), str.end(),
                       i, str.rend(),
                       best_so_far);
            // test for even-length palindrome
            updateBest(i.base(), str.end(),
                       i + 1, str.rend(),
                       best_so_far);
        }

        return best_so_far;
    }

}

int main()
{
    for (std::string s: { "",
                "forgeekskeegfor",
                "abc abc",
                "forgeeksskeeg",
                "geeksskeegfor" }) {
        auto palindromeStr = longestPalindrome(s);
        std::cout << "Found palindrome of length " << palindromeStr.size()
                  << " in " << s << ": " << palindromeStr << '\n';
    }
}


I'd have to ask - do you have to Console.WriteLine() the output? Most code testing sites want a return value from a method rather than looking at the console output and clearly, the console output is going to be the vast majority of the time spent in the application.

Secondly, I have a few quick and easy tips for increasing performance:

Ditch the string.Concats - you have the StringBuilder in hand and can just
.Append() each of those items in turn:

stringBuilder.Append(count);
stringBuilder.Append(char.GetNumericValue(digit));

in the loop and

stringBuilder.Append(count);
stringBuilder.Append(digit);

after the loop.

Pre-allocate list size: List<string> sequence = new List<string>(nthTerm + 1) { "1" }; This will reduce reallocations as the list grows (it starts at 4 and then increases by twice the size as necessary).
Measure with precision - surround your processing code in Main with var SW = Stopwatch.StartNew(); and Console.WriteLine(sw.Elapsed);. This will show you the time your code actually took.

After I did these all the things listed above, 2 ran in 00:00:00.0006395 and 50 ran in 00:00:00.5806011.


A thorough review would very much depend on what you're trying to achieve.

For example, it seams mighty clumsy to have to type multiply instead of just *. Also, a case-insensitive match would be much better. For that, you might want to check method lower or how to use regular expressions in Python.

Judging from your use of print, you're aiming at Python 3. If this is the case, then - unlike in Python 2 - you don't need

x = float(x)
y = float(y)

in function Divide. Of course, if you want your code to work in both Python 2 & 3, it's O.K. to keep that code. However, even in that case, converting only one of these two variables to float is enough.

Like most (all?) interpreted and pseudocompiled languages, Python has eval function. So, you can basically do result = eval(expression), where expression is a string with any Python code. For example, if you have a string "1+2*3", and send it to eval, you'll get 7 (unless my math is off :-)). This might help you significantly, but be careful to not pass on just any (potentially junky) user's input.

One thing seems strange to me. You do

if operation == "Multiply" or operation == "multiply":
    12 lines to input x and y
    Multiply(x,y)
elif operation == "subtract" or operation == "Subtract":
    THE SAME 12 lines to input x and y
    Subtract(x,y)
...

Why don't you first input x and y, and then do if-elif block for the actual computation, or, at least, make a function to input x and y and return them (functions in Python can return multiple values)? You have functions for simple expressions which are called only once (multiplication, subtraction, etc), which seem completely unnecessary, but you don't make one for 12 lines of code which are invoked 4 times in your code.

Regarding your naming of functions, function names should be lowercase, with words separated by underscores as necessary to improve readability, i.e., you shouldn't capitalize the names of your functions.


Regarding the two different methods for the encrypt/decrypt, yes, you can reduce them to just one function. The PrivateKey and PublicKey classes both extend the Key interface, and that's what's needed for the init(...) function.

Note also, that you are doing some code-style things "wrong". Your try/catch code should be using the more modern try-with-resources mechanism, and there's no need to declare the byte[] array outside the try block.

So, reducing it all down to a single method, with improved code style, it would be:

private static byte[] doCrypto(int cipherMode,  Key key, byte[] inputBytes)
          throws CryptoException {

    try (Cipher cipher = Cipher.getInstance("RSA")) {
        cipher.init(cipherMode, key);
        return cipher.doFinal(inputBytes);
    } catch (NoSuchPaddingException
            | NoSuchAlgorithmException
            | InvalidKeyException
            | BadPaddingException
            | IllegalBlockSizeException ex) {
        throw new CryptoException("Error doCrypto", ex);
    }
}


Executing multiple steps to handle a purchase using currying

I take it here that you mean “algebra” to mean lambda calculus and by extension, combinatory logic.

The takeStep function is essentially (disregarding side-effects): $$
\lambda ab.b
$$ in lambda calculus, or in JS in terms of identity (using Haskell Curry’s combinator naming):

I = a => a
K = a => b => a
KI = K(I)

So as the takeStep function is simply disregarding the first argument, and the walk function calling the second argument with the previous (/initial) value there and then, I’m wondering if you would really be after the B-combinator $$
   \lambda fga.f(ga)
$$ (or, as JS: B = f => g => a => f(g(a)), often named compose) with possibly the C-combinator $$
   \lambda fab.fba
$$ (C = f => a => b => f(b)(a)) for reversing the arguments (often named pipe or sequence for f => g => a => g(f(a))).

(I’m not sure if the commutativity of the functions or JS evaluation strategy plays a role here.)

Regarding currying, I wonder if you were thinking of partial application instead.


You can avoid assemble, disassemble, tag_datum if you leverage on key param of both itertools.groupby and sorted and condense them into one simple function.
Build a custom function for key param
Write a function to return the length of each value in the dictionary.
val_len = lambda x: len(x['ids'])

Now pass this as argument for key in both itertools.groupby and sorted
from itertools import groupby

def transform(data):
    sorted_data = sorted(data, key=val_len)
    return [list(group) for _, group in groupby(sorted_data, key=val_len)]

transform(data) # data taken from question itself.
# [[{'ids': [1]}, {'ids': [4]}, {'ids': [3]}, {'ids': [2]}],
#  [{'ids': [3, 4]}, {'ids': [1, 2]}]]

Details
sorted_data = sorted(data, key=val_len) # sorts data based the length of
                                        # the value of 'ids'
# [{'ids': [1]}, ---|
#  {'ids': [4]},    |-- group with length 1
#  {'ids': [3]},    |
#  {'ids': [2]}, ---|

#  {'ids': [3, 4]},---|-- group with length 2
#  {'ids': [1, 2]}]---|

groupby(sorted_data, key=val_len) # groups data based on the length of
                                  # the value of 'ids'


Maximal pythagorean triplet that sums to n

The code returns the first product, not the maximum product. For example, it returns 6240 instead of 7500 on input 60:

(60)  10² + 24² = 26² ; 10 * 24 * 26 = 6240
(60)  15² + 20² = 25² ; 15 * 20 * 25 = 7500

This is easy to fix: loop and take the maximum.

  I have been told there is a better solution.

There are solutions that take fewer steps. One could attempt to improve the current solution by shrinking the possible ranges. Given:

\$c^2 = a^2 + b^2 ; sum = a + b + c\$

Neither a nor b can be larger than c. This also means that neither a nor b can be larger than half the sum.

For c: it can't be smaller than any other term, and it must be at least one-third of the sum.

  // the "sum - 1" accounts for a being at least 1
  for ( int b = (sum - 1) / 2; b >= 1; b-- ) {
    for ( int c = Math.max(b, sum - 2*b); c < sum-b-1; c++ ) {
      int a = n - b - c;
      if ( a*a + b*b == c*c ) {
        // found a triple
      }
    }
  }

This is a little better, but it's still inefficient. If you're feeling brave, there is a formula to generate all Pythagorean triples.

Euclid's Formula

Briefly, Euclid's formula involves two integers, \$m > n > 0\$, that generate Pythagorean triples:

\$a = m^2 - n^2 ; b = 2mn ; c = m^2 + n^2\$

(This doesn't generate all triples; we'll get to that in a minute.)

The sum of a, b, c becomes:

\$sum = m^2 - n^2 + 2mn + m^2 + n^2 = (m - n)(m + n) + (m + n)^2 = 2m(m + n)\$

Because sum, m, and n are integers, this means that both m and (m+n) divide sum.

For minimal n = 1, m is maximally \$\sqrt{sum \over 2}\$, so that's a good upper bound to start with. And given sum and m, we have \$n = {sum \over {2m}} - m\$

/* sum = 2m(m+n) ; m > n > 0 */
public static int maxPythagTriple_Euclid(int sum) {
  // sum must be even; smallest triple has sum 12
  if ( sum % 2 != 0 || sum < 12 ) return -1;
  final int sumd2 = sum / 2; // divisible by 2
  for ( int m = (int) Math.sqrt(sumd2); m > sumd2 / m - m; m-- ) {
    if ( sum % m != 0 ) continue; // must be a divisor
    final int n = sumd2 / m - m;
    if ( n <= 0 ) continue; // rule out pathologicals
    if ( sum % (m+n) != 0 ) continue; // must be a divisor
    final int msq = m*m, nsq = n*n;
    final int a = msq - nsq, b = 2*m*n, c = msq + nsq;
    assert a * a + b * b == c * c;
    return a * b * c;
  }
  return -1;
}

// Alternative implementation, pulling n into the for-loop
public static int maxPythagTriple_Euclid(int sum) {
  if ( sum % 2 != 0 || sum < 12 ) return -1;
  final int sumd2 = sum / 2; // divisible by 2
  for ( int m = (int) Math.sqrt(sumd2), n = sumd2 / m - m;
            m > n;
            m--, n = sumd2 / m - m ) {
    if ( n <= 0 || sum % m != 0 || sum % (m+n) != 0 ) {
      continue;
    }
    final int msq = m*m, nsq = n*n;
    final int a = msq - nsq, b = 2*m*n, c = msq + nsq;
    assert a * a + b * b == c * c;
    return a * b * c;
  }
  return -1;
}

We can return at our first hit because we maximize m; the product will be largest when the terms are closest, which is the case for minimal n (and thus maximal m).

To quote myself:

  This doesn't generate all triples; we'll get to that in a minute.

Euclid's formula doesn't generate all triples, but it does generate at least all primitive triples.

An important property of Pythagorean triples is that, if \$(a,b,c)\$ is a triple, then so is \$(k*a, k*b, k*c)\$, for any integer k. Such a k is necessarily a divisor of the sum of a, b, c.

public static int maxPythagTriple_Euclid(int sum) {
  int max = -1;
  for ( int k = 1; k < sum / 2 && sum / k >= 12; k++ ) {
    if ( sum % k != 0 ) continue;

    // multiply by k^3
    int prod = maxPythagTriple_Euclid_primitive(sum / k) * (k * k * k);
    if ( prod > max ) {
      max = prod;
    }
  }
  return max;
}

Precomputing the divisors of sum may save some more steps, but I haven't looked into that.