implementation

The biggest thing that jumped out at me is your all function takes a callback instead of returning a Promise like Promise.all would do. (EDIT: it looks like the interview asked that of you, so that makes sense then. A section has been added below.)
When your handling the reject branch of each promise (in the .then call), there's no reason to do anything fancy. As soon as you encounter an error, you can immediately reject the outer promise (or in your case, callback with an Error
allPromisesChecked and allPromisesPassed gets a little verbose but as long as it works it kinda doesn't matter

This interested me so I took a shot at implementing it. Here's my code -

// Promise.all polyfill
function all(promises) {
  return new Promise(function(resolve,reject) {
    var count = promises.length
    var result = []
    var checkDone = function() { if (--count === 0) resolve(result) }
    promises.forEach(function(p, i) {
      p.then(function(x) { result[i] = x }, reject).then(checkDone)
    })
  })
}

// delay helper for creating promises that resolve after ms milliseconds
function delay(ms, value) {
  return new Promise(function(pass) {
    setTimeout(pass, ms, value)
  })
}

// resolved promises wait for one another but ensure order is kept
all([
  delay(100, 'a'),
  delay(200, 'b'),
  delay(50, 'c'),
  delay(1000, 'd')
])
.then(console.log, console.error) // [ a, b, c, d ]

// check that error rejects asap
all([
  delay(100, 'a'),
  delay(200, 'b'),
  Promise.reject(Error('bad things happened')),
  delay(50, 'c'),
  delay(1000, 'd')
])
.then(console.log, console.error) // Error: bad things happened

time

This took me about 10 minutes. If someone already has experience with Promises, I would expect someone could come up with a working solution in less than 30 minutes. If you've never seen Promises before, maybe 60 minutes?

using a callback

Re-reading the question, I see that my original answer is an actual polyfill of Promise.all, not what the interview asked of you.

Here's a dramatically simplified function that is essentially useless except for answering the interview question.

// Promise.all wannabe
// ([Promise], (bool-> void)) -> void
function all(promises, callback) {
  var count = promises.length
  promises.forEach(function(p, i) {
    p.then(
      function() { if (--count === 0) callback(true) },
      function() { callback(false) }
    )
  })
}

// delay helper for creating promises that resolve after ms milliseconds
function delay(ms, value) {
  return new Promise(function(pass) {
    setTimeout(pass, ms, value)
  })
}

// basic boilerplate to check an answer
function checkAnswer(label, promises) {
  all(promises, function(result) {
    console.log(label, result)
  })
}

// resolved promises wait for one another but ensure order is kept
checkAnswer('example1', [
  delay(100, 'a'),
  delay(200, 'b'),
  delay(50, 'c'),
  delay(1000, 'd')
]) // [ a, b, c , d ]

// check that error rejects asap
checkAnswer('example2', [
  delay(100, 'a'),
  delay(200, 'b'),
  Promise.reject(Error('bad things happened')),
  delay(50, 'c'),
  delay(1000, 'd')
]) // Error: bad things happened

remarks

So in hindsight, I do have some more critique to offer. Considering the function only has to return true or false, there's no reason to make it complex. Basically you just have to count the resolve branches until it reaches the count of promises provided as input. If a reject happens, you can immediately return false. There's no need for any other code.

back from the future (4 years later)

Functions have taught me a lot over the recent years. Small functions that do one thing are always better than big functions that do many. The design for this implementation starts with the simple idea of combining two promises into an array of two values. We'll call it and -

const and = (px, py) => // <-- two promises: "p of x" and "p of y"
  px.then(x => py.then(y => [ x, y ])) // two values: "x" and "y"

const all = (promises = []) =>
  promises.reduce
    ( (pr, px) =>
        and(pr, px) // <-- two promises: "p of r" and "p of x"
          .then(([ r, x ]) => // <-- two values: "r" and "x"
            [ ...r, x ]) // <-- result: append "x" to "r"
    , Promise.resolve([]) // <-- initial result, "p of empty"
    )

Already we're done implementing all and behaviour is the same -

all([
  delay(100, 'a'),
  delay(200, 'b'),
  delay(50, 'c'),
  delay(1000, 'd'),
])
.then(console.log, console.error)
// [ a, b, c, d ]

all([
  delay(100, 'a'),
  delay(200, 'b'),
  Promise.reject(Error('bad things happened')),
  delay(50, 'c'),
  delay(1000, 'd'),
])
.then(console.log, console.error)
// Error: bad things happened

Expand the snippet below to verify the result in your browser -

const and = (px, py) =>
  px.then(x => py.then(y => [ x, y ]))

const all = (promises = []) =>
  promises.reduce
    ( (pr, px) =>
        and(pr, px).then(([ r, x ]) => [ ...r, x ])
    , Promise.resolve([])
    )

const delay = (ms, x) =>
  new Promise(r => setTimeout(r, ms, x))

all([
  delay(100, 'a'),
  delay(200, 'b'),
  delay(50, 'c'),
  delay(1000, 'd'),
])
.then(console.log, console.error) // [ a, b, c, d ]

all([
  delay(100, 'a'),
  delay(200, 'b'),
  Promise.reject(Error('bad things happened')),
  delay(50, 'c'),
  delay(1000, 'd'),
])
.then(console.log, console.error) // Error: bad things happened

But we can do better. Putting x and y in an array [] is an extra "thing". And the operation we are using in reduce, [ ...r, x ] is also a well-known function -

const and = (px, py) =>
  px.then(x => py.then(y => [ x, y ])) // hard-coded []

const all = (promises = []) =>
  promises.reduce
    ( (pr, px) =>
        and(pr, px)
          .then(([ r, x ]) =>
            [ ...r, x ]) // <-- is known as "append"
    , Promise.resolve([])
    )

Instead of locking x and y in an array, [ x, y ], we could specify any behaviour we want, ie doSomething(x, y) -

const and = (doSomething, px, py) =>
  px.then(x => py.then(y => doSomething(x, y)))

const myFunc = (a, b) =>
  (a + b) * 100

and(myFunc, Promise.resolve(1), Promise.resolve(2))
  .then(console.log, console.error) // 300

This implementation of and is well known by another name. lift2 allows us to take an ordinary function (eg append) and use it in (ie "lift it into") the Promise context -

// complete polyfill for Promise.all

const lift2 = (f, px, py) =>
  px.then(x => py.then(y => f(x, y)))

const append = (a = [], x = null) =>
  [...a, x]

const all = (promises = []) =>
  promises.reduce
    ( (pr, px) => lift2(append, pr, px)
    , Promise.resolve([])
    )

Expand the snippet to verify the results in your browser -

const lift2 = (f, px, py) =>
  px.then(x => py.then(y => f(x, y)))

const append = (a = [], x = null) =>
  [...a, x]

const all = (promises = []) =>
  promises.reduce
    ( (pr, px) => lift2(append, pr, px)
    , Promise.resolve([])
    )

const delay = (ms, x) =>
  new Promise(r => setTimeout(r, ms, x))

all([
  delay(100, 'a'),
  delay(200, 'b'),
  delay(50, 'c'),
  delay(1000, 'd'),
])
.then(console.log, console.error) // [ a, b, c, d ]

all([
  delay(100, 'a'),
  delay(200, 'b'),
  Promise.reject(Error('bad things happened')),
  delay(50, 'c'),
  delay(1000, 'd'),
])
.then(console.log, console.error) // Error: bad things happened

why is it named lift2?

It's called lift2 because the function we lifted (append in this example) expects two arguments. In typed languages, it's common to see lift3 and lift4 variants -

const lift3 = (f, px, py, pz) => // <-- 3 promises
  px.then(x => py.then(y => pz.then(z =>
    f(x,y,z) // <-- 3 values
  )))

const lift4 = (f, pw, px, py, pz) => // <-- 4 promises
  pw.then(w => px.then(x => py.then(y => pz.then(z =>
    f(w,x,y,z) // <-- 4 values
  ))))

const p = x => // <-- helper for demo
  Promise.resolve(x)

const add = (...numbers) =>
  numbers.reduce((a, b) => a + b, 0)

lift3(add, p(1), p(2), p(3))
  .then(console.log, console.error) // 6

lift4(add, p(1), p(2), p(3), p(4))
  .then(console.log, console.error) // 10

But JavaScript is a dynamic language and so we do not need such strict implementations. We can implement liftN which accepts a variadic function -

const append = (a = [], x = null) =>
  [...a, x]

const lift2 = f =>
  (px, py) => px.then(x => py.then(y => f(x, y)))

const liftN = (f, ...promises) =>
  promises
    .reduce(lift2(append), Promise.resolve([])) // <-- !
    .then(values => f(...values))

const p = x => // <-- helper for demo
  Promise.resolve(x)

const add = (...numbers) =>
  numbers.reduce((a, b) => a + b, 0)

liftN(add, p(1))
  .then(console.log, console.error) // 1

liftN(add, p(1), p(2))
  .then(console.log, console.error) // 3

liftN(add, p(1), p(2), p(3))
  .then(console.log, console.error) // 6

liftN(add, p(1), p(2), p(3), p(4))
  .then(console.log, console.error) // 10

Notice ! above. liftN is essentially the variadic version of all. The two can be used interchangeably -

const all = (promises = []) =>
  promises.reduce(lift2(append), Promise.resolve([]))

const liftN = (f, ...promises) =>
  all(promises).then(values => f(...values))

all([ p(1), p(2), p(3), p(4) ])
  .then(nums => add(...nums))
  .then(console.log, console.error) // 10

liftN(add, p(1), p(2), p(3), p(4))
  .then(console.log, console.error) // 10

liftN
  ( console.log
  , delay(100, 'a')
  , delay(200, 'b')
  , delay(50, 'c')
  , delay(1000, 'd')
  )
  .catch(console.error) // [ a, b, c, d ]

liftN
  ( console.log
  , delay(100, 'a')
  , delay(200, 'b')
  , Promise.reject(Error('bad things happened'))
  , delay(50, 'c')
  , delay(1000, 'd')
  )
  .catch(console.error) // Error: bad things happened

Expand the snippet below to verify the results in your browser -

const append = (a = [], x = null) =>
  [...a, x]

const lift2 = f =>
  (px, py) => px.then(x => py.then(y => f(x, y)))

const all = (promises = []) =>
  promises.reduce(lift2(append), Promise.resolve([]))

const liftN = (f, ...promises) =>
  all(promises).then(values => f(...values))

const delay = (ms, x) =>
  new Promise(r => setTimeout(r, ms, x))

liftN
  ( console.log
  , delay(100, 'a')
  , delay(200, 'b')
  , delay(50, 'c')
  , delay(1000, 'd')
  )
  .catch(console.error) // [ a, b, c, d ]

liftN
( console.log
, delay(100, 'a')
, delay(200, 'b')
, Promise.reject(Error('bad things happened'))
, delay(50, 'c')
, delay(1000, 'd')
)
.catch(console.error) // Error: bad things happened


OO design of Reverse Polish Notation Calculator - follow-up

Do I need to write getters for fields that I didn't use? such as
  public String getInput(). I didn't write any setters for the
  non-static variables. do I need them?

It depends. If you want to expose the field to the classes's clients, then you need a getter. For instance, it makes sense to write a getter for the stack in the calculator so that operators can use it (sure, you could have design it differently and pass a stack to an operator directly). It's really about the design of your class. There's no definitive answer. I don't think that you need a getter for the input here.

The operators String is redundant. You can check if a string is in the map using map's containsKey method.

I also think that the input should be passed as an argument to the processInput method, not to the constructor. I just makes more sense to me to build one calculator for a specific sets of operators and then run it on as many different inputs as you need. I don't think that the input is the essential part of the calculator entity. It's more like something the calculator can processes, not something it consists of.

I'd also recommend to decouple the computations from the output. Each method should do one focused thing. The processInput should do exactly this: process the input and return the result (or throw an exception). Printing it is a different concern. It also makes your code more reusable: if you just return the value, you can still use the class if just need to evaluate the expression without printing it or if your need to display it differently.

The comments should not repeat the code so something like is // default hashmap initialization is even worse than no comments as it clutters the code. It just creates more noise. It's clear that a new HashMap<>(); creates a new empty map. They should rather explain why specific decisions were made. It's also a good practice to write doc comments for your classes and methods to specify it's behavior (including what kind of exceptions it throws) so that one doesn't need to read the code of the method to figure out what it does and how it (and shouldn't) be used.

I'd also suggest to create a copy of the mapInput in this public RPNCalculator(String userInput, HashMap<String, Operator> mapInput) constructor (so that the map used by the calculator doesn't change even if the mapInput is later changed by the client). Either way, you need to document this kind of decisions so that the users of your class know if it's safe to change the map passed to the constructor later in their code.


You could use a Map, from the Data.Map module to count occurrences of the numbers:

import qualified Data.Map.Strict as M

count :: [Int] -> M.Map Int Int
count xs = M.fromListWith (+) $ zip xs (repeat 1)

This way you only iterate once through the list of pairs (number, 1) and sum the 1s of each different number.

Since we don't have mutation in Haskell, you can often use a Map as a replacement for a dictionary in imperative languages (or arrays).


Why are there Console.WriteLine calls? Use a logging library instead of binding this to a specific usage.

Also, returning string.Empty; instead of throwing an exception seems a bit of a bad idea. You wouldn't know there's an issue unless you'd look at your logs.

Properties should be PascalCase: localhostNearest, etc.

Why bother with this in the constructor?

localhostNearest = string.Empty;

Why can't it be null?

Do not concatenate when working with paths:

processLocation = installationFolder + "\\osrm-routed.exe",
workingDirectory = workingFolder + @"data\"

Instead, use Path.Combine().

GenerateWebRequest() does more than what its name implies.

What is conn? Use descriptive names for variables, parameters, properties, etc.

There is a lot of repetition here:

localhostNearest = "http://localhost:5000/nearest/v1/driving/",
localhostRoute = "http://localhost:5000/route/v1/driving/",
localhostTrip = "http://localhost:5000/trip/v1/driving/",

If all URLs follow that pattern, why not work with a "template" -- e.g. $"http://localhost:5000/{type}/{version}/driving/" -- and use string interpolation or String.Format()?

Also, why are these hardcoded in your code? Shouldn't these URLs come from a .config file?


Swapping dynamically populated images on hover/touch

Some good suggestions already from @konijn, so I won't rehash any of the content from that answer.

I would consider writing this a a jQuery plugin.  This will allow you to properly namespace your code and allow you to define your own variables for re-use within this scope (i.e. to prevent need to re-query DOM with every event action.  This will also make your solution re-usable across various websites and DOM configurations.

That might look like

(function( $ ) {

    $.fn.galleryThumbSwapper = function(options) {

        // Extend our default options with those provided.
        // Note that the first argument to extend is an empty
        // object – this is to keep from overriding our "defaults" object.
        var opts = $extend({},$.fn.galleryThumbSwapper.defaults, options);

        // do our DOM selections once
        // define wrapper based on element this function was called on
        var $wrapper = $(this);

        // define main image and gallery image items
        // here we only find element within the wrapper such that
        // you could use multiple galleries on a page without
        // worry about interaction problems between galleries so
        // long as each gallery is contained within the wrapper
        var $mainImage = $wrapper.find(opts.mainImageSelector);
        var $galleryImages = $wrapper.find(opts.galleryImageSelector);

        // set click handler
        $galleryImages.on('click', swapImages);

        // define callback for click handler
        function swapImages() {
            // wrapper for triggered element
            $triggerElement = $(this);

            // get current main image info
            var currentMainSrc = $mainImage.attr('src');
            var currentMainData = $mainImage.data('gallery-image');

            // get triggered thumbnail info
            var newMainSrc = $triggerElement.data('large');
            var newMainData = $triggerElement.attr('src');

            // perform the swap
            $mainImage.attr('src', newMainSrc);
            $mainImage.data('gallery-image', newMainData);

            $triggerElement.attr('src', currentMainSrc);
            $triggerElement.data('large', currentMainData);
        }

        // return this for use in chaining
        return this;
    }

    // define default values for plug-in
    // you could also possibly add default values for the data fields here
    // so as to make these configurable
    $.fn.galleryThumbSwapper.defaults = {
        mainImageSelector = '.main-class',
        galleryImageSelector = '.product-gallery img'
    };
}( jQuery ));

// usage
$(document).ready(
    $('.product-image').galleryThumbSwapper();
);

// or, with overriding default options
$(document).ready(
    $('.product-image').galleryThumbSwapper({
        mainImageSelector = '#main_img',
        galleryImageSelector = '.thumb_img'
    });
);

A few other thoughts:

You might consider using id instead of or in addition to class for the main wrapper DOM element. i.e. product-image.  This would guarantee uniqueness, particularly if you used the jQuery plug-in approach I am suggesting.
You might consider your data attribute naming of 'large' which doesn't seem to make much sense as what you are storing in there is a URL.  I actually don't see why you can't use the same data-attribute name on the main image and the gallery images.
Seems like a bit of an odd user experience to have thumbnails potentially be changed in order based on how the user triggers these image swaps.  To me as a user, I would expect to be able to hover across the thumbs, without it impacting the order of the thumbnails.
Consider having images have their own class as well. This would address current inconsistency in having some elements be included in logic based on class while others become part of the logic based on element type.


Keep your line-length under control. Horizontal scrolling is death on readability.
strprep() is extremely inefficient, and even assuming the destination is big enough, you don't check whether allocation of your needless temporary buffer succeeds. Better to fix that:

char *strprep(const char *prefix, char *dest) {
    size_t prefix_len = strlen(prefix);
    memmove(dest + prefix_len, dest, strlen(dest) + 1);
    memcpy(dest, prefix, prefix_len);
    return dest;
}

Assuming a user-supplied Buffer contains an empty string for no reason is certainly an interesting decision. It violates the principle of least surprise though, and leads to Undefined Behavior if the assumption proves unfounded.
I won't try to decipher what your cryptic single-character variables in words() are for. Do everyone (especially yourself) a favor and invest some more into finding good names.
Using strlen() to decide whether a string is empty? That's an \$O(n)\$ call where a primitive direct check is sufficient:

if (!*dest) // dest is empty

Most optimizing compilers in hosted mode will succeed in lowering it to the above, but why write that much more and rely on it?
Actually, check for zero beforehand instead. No need to do so after failing to put it into words some other way.
Either your example code violates the contract of words(), or words is buggy. I suggest fixing words() to not assume the buffer is pre-filled with an empty string.
Consider merging multiple outputs into one request. Don't worry, due to adjacent string-literals being concatenated by the compiler, that need not result in one humungous string-literal.


Applying same formatting to multiple borders in Excel VBA?

If the question is "how do I apply the same formatting to multiple borders?" then the following is one way:

Dim the_borders As Variant
the_borders = Array(xlEdgeLeft, xlEdgeTop, xlEdgeBottom, xlEdgeRight, xlInsideVertical, xlInsideHorizontal)
    ' Or whatever xlEdge* constants you want to list

Dim idx As Long
For idx = LBound(the_borders) To UBound(the_borders)
    With Selection.Borders(the_borders(idx))     ' Process the right border
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
Next idx

The As Variant / Array combo gives you an array of the border IDs you specify, running from LBound(the_borders) to UBound(the_borders).  Then, within the loop, borders(idx) is the XlBordersIndex you can pass to Selection.Borders.


You've missed import block, so I will assume, that you are using github.com/jbrukh/bayesian as bayesian in provided snippet.

Passing slices by value

Hm. I see how you've used pointers with slices. Let me tell you a bit about the slice internals.

In Go slice values are backed by a small struct simular to this one in C:

struct Slice {
    Elem *ptr;
    int cap;
    int len;
};

cap and len fields stand for slice capacity and length. ptr holds a pointer for continuous memory of slice elements.

So, when you copy a slice by value, you actually copy it's header, not it's content:

a := []string{"Hello,", "World!"}

// Copying slice by value and changing it
b := a
b[1] = "Code Review!"

fmt.Println(a[0], a[1])

The provided snippet will output Hello, Code Review! because both a's and b's ptr point to the very same memory.

It's totally fine to pass a slice by value. Most standard library code do it like this.

To follow up here is a nice post Go Slices: usage and internals at Golang Blog about slices and arrays internals, I suggest you to take a look. It explains a lot about how they are made and why it is okay to pass them by value.

Tip: if you really need a copy of a slice use copy.

Also, don't dereference struct values like in (*filter).singleWordClassifier.

Use filter.singleWordClassifier directly.


Syntax & Styling

Instead of #defineing size to be 10, you should declare a static const.

static const size = 10;

This answer explains nicely as to why.  Good job on having this declared though, it's better than having magic numbers in your code.
You should never declare main() to return void.  There is no good reason to not declare it as int main().  See this answer for more explanation.
You should declare your main with void parameters, as such:

int main(void)

Your main() is doing too much within it.  You should abstract your code into different functions and then call it from within main().
Put the variable declarations to separate lines and initialize them to some value. From Code Complete, 2d Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

You should declare your for loops as such:

for(int i=0; i < size; ++i)

Note that this was introduced in the C99 standard.  There is no reason you should not be using this standard in your code.

Algorithm

Why do you limit yourself to finding palindromes within an int array?  It's more typical to find palindromes within a string.
Right now the time complexity for your algorithm is \$ O(n^3) \$, which is expensive.  Let's use Manacher's algorithm which can do it in \$ O(n) \$.  Here is a C implementation of the algorithm, but recognize that this has some bad practices within the code and should only be looked at to get an idea for implementing the algorithm yourself.


How can I use the State monad effectively in Haskell?

I won't be reviewing this code for efficiency, since I'm not quite so comfortable with analyzing some combination of State monad, immutable data structures, and laziness.
However, there are a few obvious changes you can make to your code.
Passing State Properly
This is what Franky was getting at with his comment, and it's a bit of a tricky bug. When you do
put $ Map.insert x (prev1 + prev2) solved

you use the solved that you get at the beginning of the function invocation. But your recursion goes from top-to-bottom, so if you're computing fib 10, solved is the empty map when you are getting the final answer. Essentially, your memo map keeps getting overwritten with maps that have less information. The fix is pretty easy.
prev1 <- fib (x - 1)
prev2 <- fib (x - 2)
solved' <- get
put $ Map.insert x (prev1 + prev2) solved'

Just get the updated state after the recursive invocations.
Naming
I think solved is ambiguous as to whether it refers to a single solution or the memo map. I would call it something like solutions, maybe sols or fibs if you feel like abbreviating. In light of the previous bug, you may wish to call the first one initialSolutions and later ones updatedSolutions or something like that (I just used solutions and solutions').
The name m is OK, but it doesn't really need to exist at all. You can just case on Map.lookup x solved directly instead of binding m and then casing on it.
The case Statement
It seems like you're trying to use the case statement to set up your memo map so that it always has a value for x. There are two things to address about this.
Indexing
If you, the programmer, are sure that x exists in the map (and in the case above you guarantee it), you could instead use the unsafe lookup Map.!. Given the option between returning an erroneous value silently (your fromMaybe 0) and crashing and burning in case of a bug, I would generally prefer the latter. So your last line would look something like gets (Map.! x).
The Last Lookup
However, doing the lookup itself is inelegant. It might make sense if there was a lot of convoluted stuff happening between, but proper indexing doesn't get checked by the type system and doing a lookup takes (not much, but some) extra time. Fortunately, you don't need to do it. Since I'm going to assume you're learning Haskell, consider how you'd approach a similar problem in an imperative language. What would you do to change this code:
if (x in solutions):
  solutions[x] = solutions[x]
else:
  prev1 = fib(x-1)
  prev2 = fib(x-2)
  solutions[x] = prev1 + prev2
return solutions[x]

There are many right answers, but one thing you can do is as follows (this particular code is nice because it avoids extra lookups):
if (x in solutions):
  return solutions[x]
else:
  prev1 = fib(x-1)
  prev2 = fib(x-2)
  solution = prev1 + prev2
  solutions[x] = solution
  return solution

Your case statement functions like the imperative if statement, except more powerful since you have guarantees on the types! So mirroring the imperative's revision, you can revise your code like so
case Map.lookup x solved of
        Just solution -> return solution
        Nothing -> do
            prev1 <- fib (x - 1)
            prev2 <- fib (x - 2)
            solutions' <- get
            let solution = prev1 + prev2
            put $ Map.insert x solutions' solved
            return solution

Now you don't need the last lookup. Notice how we also avoid the issue entirely of whether x is in solutions, because we explicitly handle the case where it is and isn't. This code doesn't have any unsafe lookups!
Addendum on Lookups
Now, even if you wanted to make your case statement only fill out the memo map instead of also returning the answers, I agree with you that you are doing unnecessary work.
Just value -> put $ Map.insert x value solved

The line above needlessly reinserts the value of x. The memo map already has x, and x is already set to value. If you wanted to otherwise keep your code the same, at least change this to
Just value -> return ()

put has type a -> State a (). It's a convention for monads to pass () as their return value if they perform an action that doesn't return anything (like how putStrLn has type String -> IO ()). You can simply return () to do nothing instead of actually modifying the memo map, which I assume you did to fix a type error.
Revised Function
Included are comments noting the revision
fib :: Int -> State DP Int
fib 0 = return 1
fib 1 = return 1
fib x = do
    -- Change to a more descriptive name
    solutions <- get
    -- Case directly on the value without intermediate variable
    case Map.lookup x solutions of
            Nothing -> do
                prev1 <- fib (x - 1)
                prev2 <- fib (x - 2)
                -- Get updated solutions
                solutions' <- get
                let solution = prev1 + prev2
                put $ Map.insert x solution solutions'
                -- Return solution directly
                return solution
            Just solution ->
                -- Return solution directly
                return solution
    -- Elide previous lookup


Optimizing insertion sort for small amounts of data

Unfortunately, you are unlikely to find a better sort than the linear insertion sort when it comes to sorting small data sets. The only sorting algorithms that might be faster are sorting algorithms specialized for a given size of input: for example, optimized sorting networks can be really fast if you need to sort a small amount of integers, but are generally slower than the insertion sort if not implemented properly or if used with other types. The following image is a graph that shows the performance of different kinds of sorting algorithms to sort small fixed-size integer arrays (the time in ms corresponds to the time needed to sort one million arrays of a given size). Distributions had a random pattern:

Some of the algorithms were specialized for fixed-size collection; most notably low_comparisons_sorter, low_moves_sorter and sorting_network_sorters. The linear insertion sort was the fastest sorting algorithm which worked for collections of any size; my best bet is that a small collection fits in the fastest cache and thus benefits from the linear access.

Now, the linear version of the insertion sort I use is slightly different: it has a check to make sure that no temporary value is created if the current element is already in place. In your algorithm, it would look like that:

template <typename Iter>
void lin_sort(Iter begin, Iter end) {
    for (auto cur = begin; cur != end; ++cur) {
        auto ins = cur - 1;
        if (*cur < *ins) {
            auto key = *cur;
            do {
                *(ins + 1) = *ins;  // move 1 to right until correct position's found
                --ins;
            } while (begin <= ins && key < *ins);
            *(ins + 1) = key;
        }
    }
}

I doubt it would change a thing, but you could also try to find the point where to insert the value in a linear fashion, then rotate the values. It may be simpler for a compiler to vectorize code that linearly compares things then linearly copies things rather than a code that mixes comparison and copy operations on-the-fly. I did not test that, so don't take it for granted.

To sum up: for small collection, it's unlikely that you will beat linear insertion sort unless you have specializations for some specific types or some specific sizes, which means more code.


Get column of a matrix python with index operator

Before improving the code it would be worth fixing the following problems.

The docstring says:

>> mat[3, :] return the 4th row

but the implementation tries to return a column:

elif isinstance(arg[0], int) and isinstance(arg[1], slice):
    return self.get_column(arg[1])

but since arg[1] is a slice object, this will fail in some way. (I can't say exactly how since you didn't show us the code for get_column.)
The indexing is inconsistent. As it says in the docstring:

>> mat[3, :] return the 4th row

but to get the first element of the fourth row, you have to write:

mat[0, 3]

because the indexes get swapped:

y, x = arg
return self.matrix[x][y]

This is contrary to the way indexing works in NumPy and so seems very likely to lead to confusion.
If you pass a tuple of length 1 then this causes an IndexError:

>>> mat[:,]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr189408.py", line 21, in __getitem__
    elif isinstance(arg[0], slice) and isinstance(arg[1], int):
IndexError: tuple index out of range

If you pass a pair of slices then this is ignored and __getitem__ returns None.

>>> mat[:,:] is None
True

In NumPy this would return the whole matrix.
The code only checks whether the argument is a slice or not, and if it is a slice, it assumes that the whole row or column is required. This is right if a bare : was passed, but misleading if some other slice was passed. In NumPy mat[0:2, 0] gets the first two element of column 0, but the code in the post returns the whole of column 0.


Place a button after an input and show it's password in plain text

You can first create the i element and add a click event handler to it dynamically while you wrap it inside the div and span and add it to the document.

As you use jQuery, I would suggest using it for creating each individual element, providing it with attributes using jQuery methods.

Here is how you could do it:

function togglePasswordVisibility($pw, on, $eye) {
    $pw.attr('type', on ? 'password' : 'text');
    $eye.toggleClass('fa-eye-slash fa-eye');
}

$("[type=password]").each(function () {
    var $pw = $(this);
    var $eye = $("").addClass("fas fa-eye-slash").click(function () {
        togglePasswordVisibility($pw, false, $eye);
        setTimeout(function() {
            togglePasswordVisibility($pw, true, $eye);
        }, 800);
    });
    $pw.parent().append(
        $("
").addClass("input-group-append").append(
            $("").addClass("password-button password-button-main").append($eye)
        )
    );
});
<link href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" rel="stylesheet"/>

<link href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" rel="stylesheet"/>

    <input type="password" id="pass-on" title="<?php echo $user->valid_password_error; ?>" class="form-control" name="txt_upass" placeholder="Enter Password" autocomplete="off" value="" oninvalid="setCustomValidity('<?php echo $user->password_error; ?>')" oninput="setCustomValidity('')" required />
    Password

    <input type="password" id="pass-verify-on" title="<?php echo $user->valid_password_error; ?>" class="form-control" name="txt_upass_ok" placeholder="Retype Password" autocomplete="off" value="" oninvalid="setCustomValidity('<?php echo $user->password_error; ?>')" oninput="setCustomValidity('')" required />
    Retype Password


You're asking for a lot of words you don't use. It might be nicer to only ask the user for relevant words. Maybe instead of user_input taking no arguments, it could take a list of descriptions like user_input(["a name", "a color", "a different color"]) and ask based on those?
I don't see why the two story generators live in the same class like that. Passing the same data to multiple generators is probably not very useful very often. The functions can just as easily take the words as arguments themselves instead. This doesn't make the idea of a MadlibsGenerator class inappropriate, but the two functions belong to different generators, and the functions' input doesn't need to be directly tied to a generator at all.
The generators also do two different things each - they both generate the stories and print them. Usually, it would be better to do those separately, in case you maybe want to do something else with the stories as well.
You don't check if the user provides valid input when selecting which generator to use. If I'm asked to pick 1 or 2 and enter 3, I'd probably expect an error message and maybe an opportunity to try again. Instead, the program just keeps going as usual, except I don't get a fun story at the end.
Some day, someone else might want to use these functions (or maybe you'll want to use them for something else). They'll probably try importing your file as a module. When they do that, the entire file is run, which right now means the entire madlibs program. That's probably not what they wanted. You can prevent that by placing the program logic inside an if __name__ == "__main__": block, so that it doesn't execute when the file is imported.
Branching on a string to figure out which generator to use is a bit ugly. Just being able to look it up in a dictionary would be nice, and might also make it easier to add new ones, since we only need to update one place rather than having to worry about keeping intro and the ifs in sync.
But if we don't want to update intro each time we come up with a new generator we still have a problem - it needs to know what to call all the different generators when telling us what our options are. We could put that in the dictionary I mentioned above, or if we're already putting stuff in our generator objects we can add a name field in there as well. The latter is probably tidier.
Taken all together, we might get something like
class MadlibsGenerator:
    def __init__(self, name, descriptions, generator):
        self.name = name
        self.descriptions = descriptions
        self.generator = generator

    def __call__(self, *args, **kwargs):
        return self.generator(*args, **kwargs)

def intro(generators):
    print("Welcome to our madlib generator!")
    print("We'll ask you for a serious of words, you'll give us the words, and "
          "we'll make a dope ass story out of it!")
    print("Let's get some info from you first.")
    print("Select the type of madlib you want. ")

    for key in generators:
        print(f"{key}. {generators[key].name}")

    while True:
        selection = input()
        if selection in generators:
            break
        else:
            print(f"No generator \"{selection}\", please try again.")

    return generators[selection]

def user_input(descriptions):
    words = []
    for description in descriptions:
        words.append(input(f"Enter {description}: "))

    return words

def generate_short_story(name, animal, color, item, food):
    return (f"There once was a person named {name}. {name} LOVED "
        f"{animal}s. They were {name}'s favorite animal.\n"
        f"One day, {name} was walking down the street wearing "
        f"{color} pants and a {color} shirt. In fact, all of "
        f"{name}'s\n"
        f"clothes were {color}! In one of {name}'s hand, "
        f"there was a bright green {item}. In the other, there was "
        f"a big {food} that {name} was waiting to eat!")

def generate_poem(adjective, noun1, noun2):
    return (f"Roses are {adjective}\n"
        f"{noun1} are blue\n"
        f"I can't start my day without {noun2}")

if __name__ == "__main__":
    generators = {
        "1": MadlibsGenerator("Short Story",
            ["a name", "an animal", "a color", "an item", "a food"],
            generate_short_story),
        "2": MadlibsGenerator("Poem",
            ["an adjective", "a plural noun", "any noun"],
            generate_poem)
    }

    generator = intro(generators)
    madlib_input = user_input(generator.descriptions)
    print(generator(*madlib_input))

Update
At this point, you might start to think: "Hang on, each of those generator functions just puts strings into another string - creating a function each time we want to do that seems clumsy". And you have a point. While f-strings are nice, there are other options available that let us specify the template in one place and later use it in another. For example, strings already have a format method. We could take advantage of that and replace the generator functions with strings like
poem_template = """
Roses are {0}
{1} are blue
I can't start my day without {2}
"""

And instead of having our generators call these functions, we can have them call .format on these strings like
class MadlibsGenerator:
    def __init__(self, name, descriptions, template):
        self.name = name
        self.descriptions = descriptions
        self.template = template.strip()

    def __call__(self, *args):
        return self.template.format(*args)

And now we can create generators like greeting_generator = MadlibsGenerator("Greeting", ["a name"], "Hi there, {0}!") if we want to. Neat!


Pointer handle - only allocates in stack

I would expect operator+ and operator- to return a new object (leaving the current one intact.

    Ptr& operator+(int i) {
        index += i;
        check_range(index);
        p+= i;
        return *this;
    }
    Ptr& operator-(int i) {
        index -= i;
        check_range(index);
        p -= i;
        return *this;
    }

If I was using normal pointers.

 T* x  = getAT();
 x + 1;           // Does not change x
 T* y = x + 1;    // Does not change x (but y has the value of x+1).

Usually you see operator+ defined in terms of operator+=

Ptr& operator+(int i) {
   Ptr result(*this);
   return result+=1;
}

The *this = *this+1; look very strange.

    Ptr& operator++() {
        *this = *this+1;
        return *this;
    }

I would have just called the operator+=

    Ptr& operator++() {
        return operator+=(1);
    }

Again don't like ++(*this);

    Ptr operator++(int) {
        Ptr<T> old{p};
        ++(*this);
        return old;
    }

I would have used:

    Ptr operator++(int) {
        Ptr<T> old{p};
        operator++();
        return old;
    }

You should strive for the strong exception guarantee (also known as transaction exception guarantee).

    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
    }

Though this code looks like it does that. It is usually called in a way that prevents it.

    index -= i;
    check_range(index);  // If this throws your object is now in the new state
                         // with index out of range. I would have tried to make sure
                         // that if an exception is thrown then the state of the object
                         // remains unchanged.

    // Change to this:

    check_range(index - i); // If it throws then the object is still
                            // in a consistent unchanged state.
    index -= 1;             // If we get here then change the state.


Best way to store the sum of all node depths?

PEP8
nodeDepths should be node_depths in snake_case.
Function naming
helper is not a helpful name for a function. If I were to guess what this does, it should maybe be called recurse_node_depths.
Instance methods
As it stands, BinaryTree does not deserve to have an __init__. It would be better-suited as a @dataclass or maybe a named tuple. That said, it probably makes more sense for node_depths to be an instance method where self replaces root.
Integer-by-reference
My first read of this code was wrong. final is only ever going to have one member. My guess is that you did this to effectively pass an integer by reference, but this is a gross hack. Instead, just return the evolving sum as an integer from your recursion, and the uppermost return will be the total that you need.
Slots
Another way to squeeze performance out of this is to initialize __slots__ for BinaryTree based on the three known members.
Recursion
Recursion is not a great idea in Python, for at least two reasons:

Given that there is no indication to the maximum depth of your input tree, you may blow the stack.
Since Python does not have tail recursion optimization, recursion is slower than some other languages.

So you should attempt to reframe this as an iterative implementation.


One of the aspects I would like to improve is efficiency i.e. in the take member function while returning the Job template type to be returned by reference instead of by value.

So what you would like is:

Job& take()   ?

the problem is that you would return a reference to local variable which is Undefined Behaviour.

Just Job take() should be fine, compiler will use NRVO optimization so that no copy will be done, copy constructor call would be elided. You could return by moving: return std::move(job);, but that can prevent elision.

One place where you will have a copy constructor called is here:

Job job = queue_.front();

To prevent it you can implement move semantics into your Job class. Then replace above with:

Job job = std::move(queue_.front());

if you will not add any of the user defined constructor/destructor/assignment operator to your Job class, then compiler will add move constructor/assignment operator on  its own - depending whether it is possible.


A collection of tasks and their CancellationTokens

Duplicate logic

if (token.IsCancellationRequested)
{
    try
    {
        token.ThrowIfCancellationRequested();
    }
    catch (OperationCanceledException)
    {
        SocketClient.UnsubscribeAll();
        Console.WriteLine("Task canceled.");
    }
}

This code is weird. You first check if a cancellation is requested, then you ask for an exception to be throw if a cancellation is requested (which you already know it is), and then you immediately catch that exception. It seems like you've conflated two ways of doing the same thing. You could instead use either:

try
{
    token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
    SocketClient.UnsubscribeAll();
    Console.WriteLine("Task canceled.");
}

OR

if (token.IsCancellationRequested)
{
    SocketClient.UnsubscribeAll();
    Console.WriteLine("Task canceled.");
}

Which approach you use depends on whether it's meaningful to throw an exception, and it doesn't seem meaningful here (though you have actually omitted the surrounding code so I can't give you a guarantee).

Throwing an exception is an expensive operation, and its main purpose is to bubble an exception up through multiple layers without requiring manual handling at every step. Since you're throwing and catching at the same layer, the cost of the expensive throw is not worth the benefit.

Based on what I see, a simple if suffices here.

Tuples

I don't like tuples (in this particular scenario, at least). They're a honeytrap.

At first sight, they look really easy by allowing you to skip creating a custom class, but then you are stuck using unreadable Item1, Item2, ... properties which have no meaning. In any reasonably sized codebase, I'd have to look up which item is stored in which slot several times during the development cycle.

I suggest replacing this with a custom class just so you can keep the property names relevant:

public class BotTask
{
    public Task Task { get; private set; }
    public CancellationTokenSource CancellationTokenSource { get; private set; }

    public BotTask (Task task, CancellationTokenSource cancellationTokenSource)
    {
        this.Task = task;
        this.CancellationTokenSource = cancellationTokenSource;
    }
}

It's a few lines extra, but it significantly improves readability in the code that uses these objects, e.g.:

// Previously

CancellationTokenSource cts = bot.Value.Item2;
cts.Cancel();

// Now

bot.Value.CancellationTokenSource.Cancel();

The increased readability and somewhat shortened line count in the usage generally outweighs the effort of writing a simple DTO class.

Contains

It seems to me that you're conflating the Dictionary.ContainsKey and String.Contains methods:

public void Stop(string botName)
{
    foreach (var bot in _bots)
    {
        if (bot.Key.Contains(botName))
        {
            // ...
        }
    }
}

If you have a list of botTasks with names Alice, Bob, Cindy and you ask to stop the both with name ind, then you should come up dry since no bot with that exact name exists. However, in your current logic, that is not the case, since "Cindy".Contains("ind") returns true!

What you presumably want is to check if the dictionary contains the key "ind" (exactly), instead of whether the dictionary contains any key which contains "ind" in part of the key. That can be achieved like so:

public void Stop(string botName)
{
    if(_bots.ContainsKey(botName))
    {
        var bot = _bots[botName];

        // ...
    }
}

Or alternatively:

public void Stop(string botName)
{
    if(_bots.TryGetValue(botName, out bot))
    {
        // ...
    }
}

Thread.Sleep

Thread.Sleep(2500);

Since you're using async in your code, it seems counterproductive to then use Thread.Sleep instead of the asynchronous ´Task.Delay´, i.e.:

await Task.Delay(2500);

This is a tiny aside, because I'll omit this delay in the next section, but it's still important to point out in case a delay was actually needed here.

Manual disposing

I think you can skip the "sleep and dispose" logic here.

It's good to see that you are managing your resources responsibly, but in this particular case the management is causing an undesirable blocking of the thread for 2.5 seconds. That's not good. Even if you use an await Task.Delay instead, I'm still not convinced that it's necessary to manually handle this.

When nothing references the cancellation token source anymore, the garbage collector will eventually pick this up and dispose of the object itself. There are cases where you don't have the luxury of waiting on the garbage collector to kick into action, but in such cases blocking the thread for 2.5 seconds would still be a bigger evil.

You can simplify the logic:

public void Stop(string botName)
{
    if(_bots.ContainsKey(botName))
    {
        var bot = _bots[botName];

        bot.Value.CancellationTokenSource.Cancel();

        _bots.TryRemove(botName, out _);
    }
}

Instead of waiting for the task to cancel itself, your code instead entrusts that the task will eventually end itself, and your code only focuses on getting its own affairs in order, i.e. removing the task from your dictionary.

Static ConcurrentDictionary

This is more of an educated guess than a guarantee.

Your static ConcurrentDictionary comes across as a red flag to me, where you're misusing statics.

It seems to me like you're intending to spawn multiple BotWrapper instances which you expect to share the same static botlist, but that's a flawed approach. It would be better if you instead pass the same BotWrapper instance around in your codebase (whether through DI containers or manually, I don't know how your architecture is set up), and then keep the botlist as a non-static property of that instance.

The benefits of managing a single instance are a minor memory improvement (since you don't need multiple instances anymore), and it allows you to scale out your codebase in case you ever need to manage two different lists of bottasks. Using statics, it's impossible to have more than one. While it may not be necessary right now to maintain different lists, never say never, and it's good practice to allow for maximum reusability down the line.

However, you didn't actually provide enough code for me to make a final decision on this. This is just an educated guess based on the code as it is presented.


Idiomatic Python suggestions:

Use argparse rather than input to set the configuration. It is easy to use, and very powerful.

General suggestions:

data and data2 are literally considered the world's worst variable names. Naming is well known to be a hard problem, but it's also a great skill to learn. Naming a thing well gives much needed information to anyone reading the script, including yourself.
Comments like "checking if the trade is pos or neg" are code smells which point to an opportunity to extract a class or function.
Your program contains many magic values, like 33. Use constants or set them as defaults for arguments to make it clear what these numbers mean.
Your program neither prints nor returns anything. In other words it can be replaced by the single line pass.
This may sound chauvinist, but use English names for things in your program. The world's developers have avoided localising programming languages for a long time, and in a programming job you are very likely going to be expected to write everything except user interfaces in English. As long as practically every function, class, package and module in the world is named in English, you are going to improve maintainability by using a single language in your programs. Disclaimer: I'm not a native English speaker.


Check if a given string matches a wildcard pattern

The code you wrote can be improved in lots of places. I'll go through it from top to bottom.
#include <stdio.h>
#include <string.h>

Perfect until now. The #include lines from the C standard library should be in alphabetic order.  I cannot say whether you did this intentionally or not since there's a 50-50 chance. :)
int compareHelper(char *s, char *regex, int star);

This function should be declared as static, since it is local to this file. To do this, replace the int compareHelper with static int compareHelper.
The compare in the function name is wrong. Typically, to compare two things, they have to be of the same or at least a compatible type. The technical type here is char *, but on a more abstract level, s is an arbitrary string while regex is a string with some constraints. Instead of compare, this function should be called match.
The type of the string parameters should be const char * instead of char * since this function does not modify the characters of these strings.
The type of the parameter star should be bool instead of int. To get this type, you have to add #include <stdbool.h> along with the other #include lines.
The name of the parameter regex is wrong. The word regex means regular expression, and this is a fixed term with a precise definition. Your patterns are not regular expressions, therefore the parameter name confuses the reader. Better call it pattern.
int compareStrings(char *s, char *r);

Again, the compare should rather be match, the parameter types should get an additional const, and the return type should be bool instead of int.
int main()
{
    printf("%d\n", compareStrings("aaaacbbb", "a*b"));
    printf("%d\n", compareStrings("aaaabccccccccb", "a*b*c"));
    return 0;
}

The empty parentheses () in the function declaration of main mean that the function can take any number of parameters. In C, this is only allowed for legacy code from 1990 and earlier. In modern code, write (void) instead to clearly say that there must be no parameters.
//aaaaacbbb
//a*b

This is the beginning of documentation, which is a good idea. To be useful for other readers, you should write in whole sentences though, for example:

// See if the string s matches the pattern p.
// In the pattern, '*' matches an arbitrarily long sequence of arbitrary characters.

int compareHelper(char *s, char *regex, int star)
{
    if (*s == '\0' && *regex == '\0')
    {
        return 1;
    } else if (*regex == '*')

After the return 1, the else is unnecessary. I would write the code like this instead:

    if (*s == '\0' && *regex == '\0') {
        return 1;
    }

    if (*regex == '*') {
        ...

This way, your code has one topic per paragraph. The empty line between the topics clearly marks a pointer where the reader may stop reading and take a deep breath, before starting to read the next paragraph.
The rest of the code looks fine, except for this line:
return compareHelper(s + 1, regex + 1, 0) | compareHelper(s + 1, regex, 1);

The operator | means a logical or, and it always evaluates both operands. This means that compareHelper is called twice, even if the left-hand side already evaluates to true. This is not necessary. To only evaluate the necessary parts of the condition, replace the | operator with ||.
All in all, the code is not too long. What makes it look verbose is that you put each { or } on its own line. You can rewrite it like this:
#include <stdbool.h>

int compareHelper(const char *s, const char *regex, bool star)
{
    if (*s == '\0' && *regex == '\0')
        return true;

    if (*regex == '*')
        return compareHelper(s, regex + 1, 1); // star is seen hence will be set to true.

    if (!star) {
        if (*s != *regex)
            return false; // star was not seen and they differ in char
        else
            return compareHelper(s + 1, regex + 1, star);
    }

    // seen a star; look for the text after the star
    while (*s && *s != *regex)
        s++;

    if (*s == '\0')
        return 0;

    return compareHelper(s + 1, regex + 1, 0) || compareHelper(s + 1, regex, 1);
}

Some people will complain that "you must always use braces in if and while statements", but that's not necessary. If you properly indent your code or let your IDE format the code automatically, the indentation properly expresses the relation of the code pieces to each other. The typical example is:
if (condition)
    goto fail;
    goto fail;

Modern compilers not only translate the source code to machine code, they also check for various possible bugs in the code. Wrong indentation like in the above snippet is one of them.
And here's a complete implementation that also matches character ranges like [A-Z]. The code looks remarkably similar to yours, which is good. If you take that code and remove the part that handles the [A-Z] part, it will be very similar to your code. Actually, taking other people's code and editing it just trying to understand it is an efficient way of thinking about why each of these lines of code is actually necessary.
While reading that code, you may notice that your code might fail for str_match("a good game", "a *game"). You should verify that the search after the star looks at every possible position in the string, not only the first time the letter g appears.


LeetCode 76: Minimum Window Substring - Python

I'm not sure if online courses even go into this, but this is the exact opposite of what good code should look like. Unless there is a dire performance requirement (which is rarer than you think) the aim is always to make your code as readable (clear/stupid/simple) as possible, so that:

Errors have fewer places to hide
It is easier to reason about what the code is doing without going into how, which in turn helps you uncover errors, and makes it easier to change.

The most important factor in readability is intent. If you can't tell what the programmer is trying to accomplish, or how they are going about it, it will be very difficult to detect bugs.
So the real focus should be on making it clear from your code what your intention is, preferably baked into the code itself (structure, variable names etc...) and failing that, add comments.
This means you first need to decide on your overall strategy, so in this case: how are you going to find this window? There are many options, here are some:

Are you going to first get all possible windows and try each of them?
Are you going to try all windows at position 0, then move to position 1 etc...?
Are you going to try all windows of smallest size, then next size etc...?

In your code, I am really not sure what you're going for. Both are also big functions with a lot of variables. So I didn't even try to figure out what it does (and it would be the same in a professional code review: if I don't understand at a glance what the code is even trying to do, it gets rejected).
I'll go with that last option to give you an idea of how I would write code which makes the intention clear. You'll note that by forcing the code to clearly show its intention you also end up having to break things into smaller parts, and use clear variable names, and all of these things help.
Ps: you don't need to define a class in python ;-)
def find_window(base_string, target):
    """
    Try all windows in ascending size order, left to right.
    """
    base_string_length = len(base_string)

    def all_chars_in_window(window):
        for c in target:
            if c not in window:
                return False
        return True

    def find_match_at_size(try_length):
        end = try_length
        start = 0
        while end <= base_string_length:
            window = base_string[start:end]
            if all_chars_in_window(window):
                return window
            start += 1
            end += 1

    try_length = len(target)
    while (try_length <= base_string_length):
        window_found = find_match_at_size(try_length)
        if window_found:
            return window_found
        try_length += 1
    return ''

base_string = "ADOBECODEBANC"
target = "ABC"
expected = "BANC"

print(find_window(base_string, target))

This took 7 minutes to write, because I only had to write simple code: each bit only has a couple of variables and does something very simple. If I had forced myself to do it the way you did with all those variables and calculations, I would have been at it much longer.
Hope this helps.


In your layout XML file, keep the checked value of all RadioButton to false.

<RadioButton
    android:id="@+id/rb_rad1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/dp_10"
    android:checked="false"
    android:text="@string/text1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/xyz" />
...

Inside onBindViewHolder() method, pass the clicked RadioButton to another method customRadioButtonOnClick where you'll check what value the passed RadioButton holds and based on that, set the checked values of that one or the other buttons to true or false as per your logic like this:

        rb_rad1.setOnClickListener {
            customRadioButtonOnClick(rb_rad1)
        }
        rb_rad2.setOnClickListener {
            customRadioButtonOnClick(rb_rad2)
        }
        rb_rad3.setOnClickListener {
            customRadioButtonOnClick(rb_rad3)
        }
        rb_rad4.setOnClickListener {
            customRadioButtonOnClick(rb_rad4)
        }

customRadioButtonOnClick

private fun customRadioButtonOnClick(radioButton: RadioButton) {
    when (radioButton) {
        rb_rad1 -> rb_rad1.isChecked = true
        rb_rad2 -> rb_rad2.isChecked = true
        rb_rad3 -> rb_rad3.isChecked = true
        rb_rad4 -> rb_rad4.isChecked = true
    }
}


Word VBA function to find a specified heading & return its text as a string

No need for a loop at all; just use Word's built-in ability to find text based on its style and other formatting.

Like so:

Public Function FindHeading(strHeadLevel As String) As String
    Dim rng As Range

    'set a range to the selection first so we can avoid
    '  the selection jumping around as we do our find
    Set rng = Selection.Range

    With rng.Find
        'set up our find criteria
        .ClearAllFuzzyOptions
        .ClearHitHighlight
        .ClearFormatting
        .Text = ""
        'search from current location back to start of document
        .Forward = False
        'and stop when we hit the start
        .Wrap = wdFindStop
        'here's the important part
        .Format = True
        .Style = strHeadLevel

        'now do our find
        If .Execute Then
            '.Parent contains the found range
            Set rng = .Parent
            'strip off trailing paragraph mark
            rng.MoveEnd unit:=wdCharacter, Count:=-1
            'grab the text of the found range
            FindHeading = rng.Text
        Else
            'we ain't got nothing
            FindHeading = "No heading found"
        End If
    End With
End Function


Wrapping tuples to be used as keys in a Dictionary

public Key(string unitID, int address, int comPort, int id)

Clearly this class represents something much more specialized than an all-purpose "key". Name the type for what it stands for!

private Tuple<string, int, int, int> _impl;

The private field should be readonly. But why don't you have this instead?

private readonly string _unitId;
private readonly int _address;
private readonly int _comPort;
private readonly int _id;

public override int GetHashCode()
{
    return _impl.GetHashCode();
}

Ideally your GetHashCode implementation should rely on immutable fields. Your _impl field isn't marked readonly, which doesn't quite communicate that intent. Using actual fields and dropping the Tuple altogether, you can come up with a more standard GetHashCode implementation.

  That way I should take advantage of the Tuple class and avoid its inconvenients.

You're not getting anything out the Tuple. Get rid of it, it's only obfuscating the class' implementation.

Also, you're not instantiating your Tuple the idiomatic way. This:

_impl = new Tuple<string, int, int, int>(unitID, address, comPort, id);

Should be written like this and leverage generic type parameter inference:

_impl = Tuple.Create(unitID, address, comPort, id);


Describe how you could use a single array to implement three stacks

Solution that I found

In this approach, any stack can grow as long as there is any free space in the array.
We sequentially allocate space to the stacks and we link new blocks to the previous block. This means any new element in a stack keeps a pointer to the previous top element of that particular stack.

In this implementation, we face a problem of unused space. For example, if a stack deletes some of its elements, the deleted elements may not necessarily appear at the end of the array. So, in that case, we would not be able to use those newly freed spaces.
To overcome this deficiency, we can maintain a free list and the whole array space would be given initially to the free list. For every insertion, we would delete an entry from the free list. In case of deletion, we would simply add the index of the free cell to the free list.

In this implementation we would be able to have flexibility in terms of variable space utilization but we would need to increase the space complexity.

 int stackSize = 300;
 int indexUsed = 0;
 int[] stackPointer = {-1,-1,-1};
 StackNode[] buffer = new StackNode[stackSize * 3];
 void push(int stackNum, int value) {
    int lastIndex = stackPointer[stackNum];
    stackPointer[stackNum] = indexUsed;
    indexUsed++;
    buffer[stackPointer[stackNum]]=new StackNode(lastIndex,value);
 }

int pop(int stackNum) {
    int value = buffer[stackPointer[stackNum]].value;
    int lastIndex = stackPointer[stackNum];
    stackPointer[stackNum] = buffer[stackPointer[stackNum]].previous;
    buffer[lastIndex] = null;
    indexUsed--;
    return value;
 }
 int peek(int stack) { return buffer[stackPointer[stack]].value; }
 boolean isEmpty(int stackNum) { return stackPointer[stackNum] == -1; }

class StackNode {
 public int previous;
 public int value;
 public StackNode(int p, int v){
    value = v;
    previous = p;
 }
}


Simple Hangman game - first Python project

this if statement is a bit silly:

    if user_tries == number_of_tries or user_list == list(secret_word):
        return True
    else:
        return False

It could easily be:

    return user_tries == number_of_tries or user_list == list(secret_word)

since that expression evaluates to True or False, just return it directly
Instead of

secret_word = word_list[random.randint(1, len(word_list))]

you can use the much more readable random.choice:

secret_word = random.choice(word_list)

your user_input routine isn't used at all.  Nuke it or use it.
You use a lot of global state.  This is generally frowned upon because it makes the code less reusable.  You should first off, try to use less global state: put function results into variables and pass them around, instead.  This makes those functions much more reusable.  If you absolute must use global state, still don't: instead make an object that stores that "global" state, and turn the functions that use it into methods on the object.


Congratulations.  That's a pretty nice first attempt.

I see only a few issues:

The problem statement shows that you will receive one number per line; your code expects one line with multiple numbers, separated by commas.
The problem statement asks you to print the numbers; your program doesn't.
When run, the test writes its prompt to $stdout.  Tests should be quiet when passing.

The issue with the prompt can be fixed with an expectation:

@life.should_receive(:puts)\
.with("List comma(',') separated numbers.  Press enter when done"

If your intent is to solve a slightly different problem, then we won't worry about the differences between what your program does and what they're asking for.  But read below the fold for a simple test and implementation, TDD Style, for the stated problem.

This problem can be solved pretty simply.  For example,

  loop do
    n = gets.chomp.to_i
    puts n
    break if n == 42
  end

What test or tests could you write that would allow you to have code this simple?  Let's see if we can get there from nothing:

class Life
  def process_input
  end
end

describe Life do

  it "should copy numbers from $stdin to $stdout" do
    life = Life.new
    life.should_receive(:gets).with(no_args).and_return('41')
    life.should_receive(:puts).with(41)
    life.process_input
  end

end

Running that, we find that the spec fails because the code never called gets.  We add the call to gets, then find that the spec fails because the code never called puts.  Adding them, we get a passing test:

class Life
  def process_input
    puts gets.to_i
  end
end

Of course, we've got no loop, so let's tell the test there should be multiple calls to gets and puts.  We'll use .ordered to tell rspec that the calls should occur in a certain order.

it "should copy numbers from $stdin to $stdout" do
  life = Life.new
  life.should_receive(:gets).ordered.with(no_args).and_return('41')
  life.should_receive(:puts).ordered.with(41)
  life.should_receive(:gets).ordered.with(no_args).and_return('42')
  life.should_receive(:puts).ordered.with(42)
  life.process_input
end

Now there needs to be a loop.  Let's add it:

def process_input
  loop do
    puts gets.to_i
  end
end

Our test neither passes nor fails.  Instead, it hangs.  That's because we didn't give it any way to get out of the loop.  Let's add the termination condition:

def process_input
  loop do
    n = gets.to_i
    puts n
    break if n == 42
  end
end

So, we can write a test that lets us have pretty simple code.  But in a few ways, this test is bothersome.  One reason is that it is too picky about the way that the I/O is done.  What if we changed the program to use print instead of puts?  It would have produce exactly the same output, but the test would fail.  Also, having the test hang when the program fails to terminate isn't very good.  We want tests that pass or fail quickly and cleanly, with no guessing.  So let's rewrite our test (and the program) using dependency injection for I/O.

Starting over, we're going to change the the Life program so that it takes and input object and an output object:

class Life

  def initialize(input = $stdin, output = $stdout)
    @input = input
    @output = output
  end

  def process_input
  end

end

And our test:

require 'stringio'

describe Life do

  it "should copy numbers from input to output" do
    input = StringIO.new("41\n")
    output = StringIO.new
    life = Life.new(input, output)
    life.process_input
    output.string.should == "41\n"
  end

end

Using StringIO instances as mock I/O objects is very handy, and lets us test the result of the I/O rather than the actions that produce the I/O.  That's nice.

Since our program doesn't process anything yet, the test fails:

  1) Life should copy numbers from $stdin to $stdout
     Failure/Error: output.string.should == "41\n"
       expected: "41\n"
            got: "" (using ==)

Let's fix that:

  def process_input
    @output.print @input.gets
  end

The test now passes.  Let's modify the test to show that it should loop:

  it "should copy numbers from $stdin to $stdout" do
    input = StringIO.new("41\n42\n")
    output = StringIO.new
    life = Life.new(input, output)
    life.process_input
    output.string.should == "41\n42\n"
  end

The test fails:

  1) Life should copy numbers from $stdin to $stdout
     Failure/Error: output.string.should == "41\n42\n"
       expected: "41\n42\n"
            got: "41\n" (using ==)

Let's add the loop:

  def process_input
    loop do
      @output.print @input.gets
    end
  end

Now it hangs again!  That's because I/O objects like StringIO and $stdin just return a nil when they run out of input.  Our program is happily printing nil over and over.  Let's make the test die nicely when the loop fails to terminate:

  it "should copy numbers from $stdin to $stdout" do
    input = StringIO.new("41\n42\n43\n")
    def input.gets
      super.tap { |s| raise "no more input" unless s }
    end
    output = StringIO.new
    life = Life.new(input, output)
    life.process_input
    output.string.should == "41\n42\n"
  end

Here we monkey patch our input objects so that when it runs out of input, it raises an error rather than just returning nil.  The result:

  1) Life should copy numbers from $stdin to $stdout
     Failure/Error: super.tap { |s| raise "no more input" unless s }
     RuntimeError:
       no more input

Great!  let's get the loop to terminate when it encounters that "42":

  def process_input
    loop do
      s = @input.gets
      @output.print s
      break if s == "42\n"
    end
  end

Now we've got a robust test that doesn't care about the details of how I/O is done, and code that is pretty simple.

There's just one more enhancement I'd make to this program, and that is to have it exit when it runs out of input.  While not strictly required by the problem statement, a program that prints blank lines endlessly upon EOF is obnoxious!  Now we need another "it" in our test:

  it "should exit on EOF" do
    input = StringIO.new("41\n<EOF>")
    def input.gets
      s = super
      case s
      when "<EOF>"
        nil
      when nil
        raise "no more input"
      else
        s
      end
    end
    output = StringIO.new
    life = Life.new(input, output)
    life.process_input
    output.string.should == "41\n"
  end

Our monkey-patched input object just got a little more interesting.  We want it to return "nil" on end of input, because that's how the loop will detect end of input in real life, but we want it to raise an exception if the code under test tries to get more input after the nil.  This test fails:

  1) Life should exit on EOF
     Failure/Error: raise "no more input"
     RuntimeError:
       no more input

So let's make the loop exit on end of input:

  def process_input
    loop do
      s = @input.gets
      @output.print s
      break if s.nil?
      break if s == "42\n"
    end
  end

Now the program meets the stated requirements, and our own requirement of not filling the output with blank lines on end-of-input.


MVC Layout - Which way to add listeners is better?

Method #1 feels like the better approach, because it doesn't require your view to expose its buttons, but the four-times ActionListener method seems odd.  Both methods have some trouble with magic numbers.

Introduce an enum for directions.  It may feel like overkill at the moment, but it'll take care of your direction-to-action mapping.  It will also help shape some of your options.

Then consider supplying Action instead of ActionListener.  This will also make it easier to enable/disable the movement buttons in case something blocks your way (like going off-field), without your view having to expose its buttons.

When you combine these two, you get something like the following:

View:
    void setAction(Direction dir, Action action);

Model:
    void move(Direction dir);
    /** Returns directions possible to move to at this moment. */
    Set<Direction> getPossibleDirections();

enum Direction { UP, RIGHT, DOWN, LEFT; }

class Controller {
  Map<Direction, MoveAction> actions;

  public void setView(View view) {
    actions = new EnumMap<>(Direction.class);
    for ( final Direction direction : Direction.values() ) {
      final MoveAction action = new MoveAction(direction, direction.toString());
      actions.put(direction, action);
      view.setAction(direction, action);
    }
  }

  void refreshState() {
    final Set<Direction> dirs = model.getPossibleDirections();
    for ( final MoveAction action : actions.values() ) {
      action.setEnabled(dirs.contains(action.direction));
    }
  }

  class MoveAction extends AbstractAction {
    final Direction direction;

    MoveAction(Direction direction, String name) {
      super(name);
      this.direction = direction;
    }

    public void actionPerformed(ActionEvent evt) {
      model.move(direction);
      refreshState(); // or have model firePropertyChange
    }
  }
}


Family and vehicles example using the strategy pattern

In "modern C++" it is unusual to see (and use) RAW pointers.

class Family
{
public:
    Vehicle *myVehicle;

Here you have a pointer to a vehicle. But there is no indication of who owns the vehicle. Does the family member own the vehicle or is a shared resource? Can a family member have no vehicle in which case what is the appropriate response to driveVehicle()? Maybe with no vehicle they default to walking?

Anyway. Don't use pointers. In terms of memory management they do not indicate who the owner of the pointed at object is; Note: it is the responsibility of the owner to delete the object. If you don't know who should delete it you have memory leaks (and there is a lot in your code).

Also by default pointers are not set to NULL. So if you do not explicitly initialize them in a constructor you have a random value (so initialize them).

What happens if myVehicle is NULL here?

void driveVehicle()
{
    myVehicle->useVehicle();
}

You should mark virtual implementations as override

void display() override  // indicates this is the implementation
                         // of a virtual function.
{
    std::cout << "I am Daughter" << std::endl;
}

Never use dynamic memory memory management when local variables will do.

Family *fam = new Father();

// This should be:

Father father;


Here are few more ways to produce your uniform lists:

def f0(a: Int, b: Int) = {
  val c = a % b
  val d = a / b
  val n = if (c == 0) d else d + 1
  (1 to n).toList map (i => if (i * b <= a) b else c)
}

def f1(a: Int, b: Int) = {
  val c  = a % b
  val d  = a / b
  val xs = List.fill(d)(b)
  if (c == 0) xs
  else        xs ::: c :: Nil
}

def f2(a: Int, b: Int) = {
  val r = a % b
  val n = a / b
  if (r == 0) List.fill(n)(b)
  else        List.tabulate(n + 1)(i => if ((i + 1) * b <= a) b else r)
}

f0 is a different/interesting way to derive your lists but to my mind is harder to parse that f1
f1 is very similar to what you have already but instead of redundantly concatenating Nil when rest == 0 we simply return the list as is
f2 is quite ugly but utilizes tabulate so I thought I'd include it

You'll notice that in each of the four functions considered so far we calculate rest = sum % nums and then branch based on the result of this calculation. While I can think of other ways to derive a value for rest they aren't as intuitive as the % operator and in the end I think we would still have a conditional statement which decided the final element of the list.

Other than adopting the small change suggested by function f1 I think your code is as concise / understandable as it can be.


Decompose a value as a sum of square numbers

let squares = [ 0.. 100 ] |> Seq.map (fun x -> x * x) |> Seq.toList

I don't think limiting the squares this way is a good idea. Instead, if you moved it inside calc, you could write it as:

let squares =
    Seq.initInfinite id
    |> Seq.map (fun x -> x * x)
    |> Seq.takeWhile (fun x -> x <= total)
    |> Seq.toList

calc is a pretty bad name: it doesn't say anything about what the function calculates.

If you limit yourself to returning always only the shortest sum, the signature of the method could be simplified quite a lot: you could get rid of attempts, accu and results. This would also somewhat simplify the implementation.

And even if you don't do that, I think that filtering out empty lists should be done inside calc, not outside.

If you simplify the signature, you could then apply memoization to make the computation much faster. Memoization will help here, because what's slowing down the computation is calculating the result for the same total over and over.

The implementation could look like this:

let rec calculateSquaresSum =
    let calculateSquaresSum' total =
        if total = 0 then
            []
        else
            let squares =
                Seq.initInfinite (fun x -> x + 1)
                |> Seq.map (fun x -> x * x)
                |> Seq.takeWhile (fun x -> x <= total)
                |> Seq.toList
                |> List.rev

            squares
            |> Seq.map (fun sq -> sq :: (calculateSquaresSum (total - sq)))
            |> Seq.minBy (fun sum -> sum.Length)

    memoize calculateSquaresSum'

This will calculate the result for values around 10.000 immediately, but 100.000 takes a few seconds, so there likely is a more efficient way to implement this.

Though if you're okay with finding just some decomposition with at most the given length, not necessarily the shortest one, having the attempts parameter makes sense and makes the computation much faster when the decomposition is possible. (E.g. calculateSquaresSum(1000000 - 1, 4) returns immediately with [998001; 1849; 100; 49], while calculateSquaresSum(100000 - 1, 3) takes few seconds to return with a negative answer.)

The code:

let rec calculateSquaresSum =
    let calculateSquaresSum' (total, attempts) =
        if total = 0 then
            Some []
        elif attempts = 0 then
            None
        else
            let squares =
                Seq.initInfinite (fun x -> x + 1)
                |> Seq.map (fun x -> x * x)
                |> Seq.takeWhile (fun x -> x <= total)
                |> Seq.toList
                |> List.rev

            squares
            |> Seq.map (fun sq ->
                match calculateSquaresSum (total - sq, attempts - 1) with
                | None -> None
                | Some tail -> Some (sq::tail))
            |> Seq.tryPick id

    memoize calculateSquaresSum'


Effective 3d array transposition with R/C++ (Rcpp)

If you can change the signature, to directly get cols, rows and slices count, you will not have to check for their validity.

Rcpp::NumericVector array_perm(const Rcpp::NumericVector& input,
                               std::size_t rows, std::size_t cols, std::size_t slices);

Otherwise, if you can change the error management, I think you'll get a speed boost. Exceptions handling come with a cost. Maybe return an empty vector? I don't know R , so I don't know possibilities.

You can also try to flattening your loops, here you have multiples options:

With the computations into output indexing

Rcpp::NumericVector array_perm(const Rcpp::NumericVector& input, std::size_t rows, std::size_t cols, std::size_t slices) {
    // Think about the error management here...
    auto output = Rcpp::NumericVector(Rcpp::no_init(10));

    auto rc = rows * cols;
    auto size = rc * slices;
    for (std::size_t i = 0; i < size; ++i) {
        output[i / rc + i % rc * slices] = input[i];
    }
    return output;
}

With the computations into intput looking

//...
    for (std::size_t i = 0; i < size; ++i) output[i] = input[i/slices + i % slices * rc];
//...

Or in reverse order

//...
    while (size--) output[size] = input[size/slices + size % slices * rc];
//...

Or a mix

//...
    while (size--)  output[size / rc + size % rc * slices] = input[size];
//...

Or even a range-based for loop

//...
    std::size_t i = 0;
    for (auto e : input) {
        output[i / rc + i % rc * slices] = e;
        ++i;
    }
//...

PS: Did you tried with another contiguous storage type? (std::vector, plain old C array, ...)

PPS: I don't have R environment, so I only tested transposition algorithms with c++

Edit:

Two other way:

//...
    for(std::size_t i = 0, j = 0; i < size; ++i, j+=rc) {
        if (size <= j) j -= size - 1;
        output[i] = input[j];
    }
//...
// or
//...
    for(std::size_t i = size, j = i-1; i--; j -= rc) {
        if (size < j)  j += size-1;
        output[i] = input[j];
    }
//...


Find an intersection point of 2 line segments

I've not written much python, so I'm not qualified to comment on your coding style, etc. However, I do a lot of graphics work, and I can tell you that this is a lot more code than you should have to write for this task. It would be silly of me to repeat it all, but check out the answers to this question on Stack Overflow. You can see that it doesn't take more than a single function of about 10-20 lines.


Logic/Code duplication, improve readability?

Not a lot of changes, but maybe a bit more legible.

a12 = entity.acceleration - other.acceleration
a21 = -a12
v12 = entity.velocity - other.velocity
v21 = -v12

result  = [ (p, v12, a12, l) for l in other.lines for p in entity.points ] +
          [ (p, v21, a21, l) for l in entity.lines for p in other.points ]

Obviously you could inline the v21 and a21 variables, but it's actually somewhat descriptive of what they represent to use those names.


I want to see if there is anything I don't need in my CSS file for my current layout

Unless your element is fixed or absolutely positioned, top: 0 is doing nothing for you (#header).  Unless your descendant elements are absolutely positioned (or you need to adjust the element's stacking order due to surrounding absolutely positioned elements), you probably don't need position: relative either.

The negative margin on #main is doing nothing for you (margin: 0 auto gives identical results).  Generally, you use negative margins to nudge things around similar to relative positioning, but where it effects the position of everything that follows as well (eg. an element with margin-top: -50px will move up 50px and so will everything below it, but an element that's relatively positioned with a top: -50px will only shift that element up and not the following elements).

vertical-align: bottom isn't doing anything for you either (#main).  The vertical-align property only works on inline or table-cell elements.

It's not really a good idea to set fixed heights on elements that will have an unknown amount of content (#main).  Scrollbars give users clues as to how much content there is on the page.  It can be confusing to the user when they scroll and scroll, but there's no more content to find.  If the content is longer than you've allowed for, it will spill out of the container or get clipped off (depending on the element's overflow setting).

If you want your footer to be at the bottom of the viewport, then yes, you need bottom: 0.


Design for container that holds multiple instances of same base class

Controllable class

can be abstract, it doesn't seem you will instantiate it
int x field shall be private, you don't use it anywhere

Party class

you declared variable of type PC with lower letters so object assignment shall be too pc = new PC ("PC", 1);
members = new ArrayList<Controllable>(); with Java 8 it is not necessary to declare list's type if you do this with variable declaration, so members = new ArrayList<>(); is enough

It is a good practice to make method arguments final, as well class fields if they are provided through constructor. It means their declared type cannot be changed.


Determining the number of days from today

Let's start with the main error that I see: You compute the timespan between the "current date" and the "due date". If the current date is today at 11am, and the due date is tomorrow at 10am then the difference
is 0 days and 23 hours, to this is reported as "today".

This is probably not what you wanted, therefore todayDate must be
set to the start of the current day. This is easily done with

let todayDate = calendar.startOfDayForDate(NSDate())

Then todayDate and calendar should be computed only once before the
loop starts, and not for each loop iteration.

There are also problems in the analysis of the computed date components:

if calendarComponents.month > 0 && calendarComponents.day > 0 { ...

What if the difference is exactly 2 (or more) month and 0 days?

} else if calendarComponents.day > 7 {

What if the difference is exactly one month and 0 days?

The first two if-conditions should therefore be

if calendarComponents.month >= 2 || (calendarComponents.month == 1 && calendarComponents.day > 0) {
    // More than a month
} else if calendarComponents.month == 1 || calendarComponents.day > 7 {
    // Between 8 days and one month
} else if ...

Other things that can be improved:

If you create a NSManagedObject subclass for your entity then
you can use the property accessors instead of valueForKey():

let fetchedResults = managedContext.executeFetchRequest(fetchRequest,
    error: &error) as! [Assignment]?

// ... later ...
let dueDate = item.dueDate

The advantage is that you don't need the cast as! NSDate anymore
and the compiler can check for correct types.

Some type annotations are not necessary, e.g.

let calendarComponents: NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay,
    fromDate: todayDate, toDate: dueDate, options: .allZeros)

can be simplified to

let calendarComponents = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay,
    fromDate: todayDate, toDate: dueDate, options: nil)

And

println("Days: " + calendarComponents.day.description + " Months: " + calendarComponents.month.description)

can be simplified with string interpolation:

println("Days: \(calendarComponents.day) Months: \(calendarComponents.month)")


How can I improve this code?

The code itself isn't particularly useful. You can print the primes up to N, but what if I wanted to sum all the primes up to N? In this model, you'd have to add a sum() member function to Prime<i> and again to Prime<1>. That doesn't make for a very reusable system. So let's go for something reusable, and in C++11 to boot.

Checking primality

Run isn't a particularly good name for a metafunction that determines if something is prime or not. Furthermore it doesn't even have to be a metafunction, it can be a constexpr function:

constexpr bool is_prime(std::size_t N)
{
    if (N < 2) return false;

    for (std::size_t i=2; i*i <= N; ++i) {
        if (N%i == 0) return false;
    }
    return true;
}

Check primality for lots of numbers

Your original example wanted all primes under 30. The standard metaprogramming mechanism for getting all numbers under 30 is:

using Nums = std::make_index_sequence<31>; // std::index_sequence<0, 1, 2, ..., 30>;

Although that gives us numbers and metaprogramming is all about types. Anything that isn't a type is usually a real nuisance to deal with, so let's write something to instead give us a list of types:

template <typename T>
struct type_is { using type = T; };

template <typename...>
struct typelist { };

namespace details {
    template <std::size_t N, typename = std::make_index_sequence<N>>
    struct make_type_index_sequence;

    template <std::size_t N, std::size_t... Is>
    struct make_type_index_sequence<N, std::index_sequence<Is...>> {
        using type = typelist<std::integral_constant<std::size_t, Is>...>;
    };
}

template <std::size_t N>
using make_type_index_sequence = typename details::make_type_index_sequence<N>::type;

// typelist<size_t_<0>, size_t_<1>, ..., size_t_<30>>, where size_t_<N> is integral_constant<size_t, N>
using Nums = make_type_index_sequence<31>;

Ok, we have a typelist. Now we just need to filter it down based on a condition. To filter, we need to be able to concatenate:

template <typename... Args>
struct concat;

template <typename... Args>
using concat_t = typename concat<Args...>::type;

template <typename... A1, typename... A2, typename... Args>
struct concat<typelist<A1...>, typelist<A2...>, Args...> {
    using type = concat_t<typelist<A1..., A2...>, Args...>;
};

template <typename TL>
struct concat<TL> {
    using type = TL;
};

After which filter comes naturally:

template <typename A, typename F>
using filter_one = std::conditional_t<F::template apply<A>::value,
                                      typelist<A>,
                                      typelist<>>;

template <typename TL, typename F>
struct filter;

template <typename... Args, typename F>
struct filter<typelist<Args...>, F> {
    using type = concat_t<filter_one<Args, F>...>;
};

template <typename TL, typename F>
using filter_t = typename filter<TL, F>::type;

Metafunction classes

Something needs to be mentioned about this construction:

F::template apply<A>::value

Here F is a "metafunction class". That is, it's a type of the form:

struct MetafunctionClass {
    template <typename... Args>
    using apply = ???
};

Metaprogramming is all about convention. If everybody doesn't agree on convention, everybody's metaprograms may as well be written in different languages. The most core convention is that the "return" of a metafunction lives in a type named type. But a fairly common one is that when you need a "metafunctor", you pass something like this. The advantage of something like this is that it's always easy to create a type, but usually not so easy to create a template template (which would be the alternative).

Specifically here, we need:

struct IsPrime {
    template <typename T>
    using apply = std::integral_constant<bool, is_prime(T::value)>;
};

with which getting all the primes under 30 is:

template <size_t N>
using PrimesUnder = filter_t<make_type_index_sequence<N>, IsPrime>;

What can I do with this?

Well, anything really. Now that I made it easy to generate the primes, anything we may want to do with them is easy too. Printing them?

template <typename... Ts, typename F>
void for_each(typelist<Ts...>, F f) {
    using expander = int[];
    expander{0,
        (void(f(type_is<Ts>{})), 0)...
    };
}

for_each(PrimesUnder<30>{}, [](auto t) {
    std::cout << "prime number: " << decltype(t)::type::value << std::endl;
});

Summing them?

template <typename TL, typename F, typename Z>
using foldl_t = ??? // exercise for the reader

struct Add {
    template <typename T, typename U>
    using apply = std::integral_constant<decltype(T::value + U::value),
                      T::value + U::value
                      >;
};

template <size_t N>
using SumOfPrimesUnder = foldl_t<PrimesUnder<N>, Add, std::integral_constant<int, 0>>;

Anything else you may need to do with your primes? You have the typelist - it's all in your hands.


Some notes:

The initialize method of a class should be its most basic and fundamental constructor, don't use it as a "helper". A tree has a name and some children, so these should be the arguments. You want to construct a Tree from a hash to make things easier for the caller? then create a helper classmethod, for example Tree::new_from_hash(hash).
Tree#visit. That's an imperative construct, I'd write first the functional ones (which can also be used imperatively if needed).
node.node_name: That repetition is a cue that node_name is redundant, name is enough.
(Subjective) I prefer to write hash literals without losing indentation space.

I'd write (I'd inherit from Struct to save some lines, not really needed):

class Tree < Struct.new(:name, :children)
  def self.new_from_hash(hash)
    name, children_hash = hash.first
    children = children_hash.map { |k, v| Tree.new_from_hash({k => v}) }
    Tree.new(name, children)
  end

  def visit_all(&block)
    yield(self)
    children.each { |c| c.visit_all(&block) }
  end
end

family_tree = Tree.new_from_hash({
  'grandpa' => {
    'dad' =>   {'child 1' => {}, 'child 2' => {}},
    'uncle' => {'child 3' => {}, 'child 4' => {}},
  },
})

family_tree.visit_all { |node| puts node.name }

Additional notes:

Include module Enumerable and implement Tree#each so you can use all enumerable methods for you trees. Note that enumerable methods assume a single-level iteration, so you'd still need custom methods (like visit_all/map_all) that perform nested operations.
If that's a learning code I'd explore this path: create a NestedEnumerable module -very similar to Enumerable- which would provide some xyz_all (or xyz_nested, whatever) methods. Like Enumerable, you would only be required to implement the "each" method (i.e. each_all).


Using Barrier to Implement Go's Wait Group

if (WaitGroupBarrier.ParticipantsRemaining > 0) {
    WaitGroupBarrier.SignalAndWait();
}

The above is a non-atomic operation. Thus if the if branch gets evaluated and there is one remaining, but finishes before SignalAndWait, then this will throw an exception.


Sorting software version list using Python 2.7 (no modules)

The best way would be to use the distutils.StrictVersion as your sort key argument.

However, as you do not want to use imports, you may choose to copy the _cmp, __eq__, __le__ and other comparison methods as applicable, from the source file linked above. You'd also modify the parse method to use str.split instead of a regex matching.

I do not think you'd have to worry about pre-releases etc.

Why I'd go with distutils is because it has been tested since a long time. Writing your own version would be prone to errors, and edge cases.


Find the common element in two int arrays

Improving EnterArray1IntoHashSet

Why do you pass a hash set to EnterArray1IntoHashSet ?
It would be better to let the method create, populate and return the hash set.

You don't need to check if an element is inside a hash set before adding it:
if the element already exists, it will be simply ignored.

The name of this function is unnecessarily tedious.
It has a nice general purpose,
and you can name it accordingly.

static HashSet<int> ToHashSet(int[] array1)
{
    HashSet<int> set = new HashSet<int>();
    foreach (int num in array1)
    {
        set.Add(num);
    }
    return set;
}

Coding style

The placement of opening braces { is inconsistent:
sometimes you put it on the next line,
sometimes on the same line.
The .NET convention is to put it on the next line.

It's also unusual to put a space between method name and the ( when calling them, for example this:

Console.WriteLine (commonElement);

Just omit the unnecessary space:

Console.WriteLine(commonElement);


Getting a value with timeout using Kotlin coroutines

Think it's pretty good and you can't think of much else. Some tiny bits I can think of:

Make discoveryService parameter.
Do not use launch without specifying CoroutineScope.