#include <bits/stdc++.h>

This is distinctly non-portable.  The files in bits/ are internal to GCC, may change without warning, and and are probably inefficient.  Use the correct Standard C++ headers instead:
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>

#define Rep(i,a,n) for(int i = a; i < n; i++)
#define rep(i,n) Rep(i,0,n)

Macros are dangerous - that's why we minimise their use, and use uppercase names for them.  In this case, they serve mainly to obfuscate the code (in particular, they tend to hide mismatches between int and the type of n; they also introduce risk of repeating operations within n).

using namespace std;

This namespace is not one of the few intended to be imported wholesale.
Bringing all names in from a namespace is problematic; namespace std particularly so. See Why is “using namespace std” considered bad practice?.

string key, line, code = "", dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", decoded = "";

Prefer one declaration per line, and declare as close to first use as possible.  dict doesn't need to be mutable:
static const std::string dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static const std::size_t n = dict.length();

std::string key;
std::cin >> key;

std::cin >> key;

This won't read beyond the first whitespace.  Is that made obvious to users somehow?

char** key_matrix = new char*[n];
rep(i,n)
    key_matrix[i] = new char[n];
rep(i,n)
    rep(j,n)
        key_matrix[i][j] = dict[(i+j)%n];

You'll find it easier to use a vector rather than an array of arrays here.  That will automatically fix the memory leak you have.  However, do you really need to allocate this storage?  There's a simple arithmetical relationship between each member, and I don't see that you get any benefit from storing each table, compared to processing on the fly.

std::fstream file;
file.open("text.txt");

Instead of hard-coding the file name, why not pass it as an argument?  That would make the program much more flexible.  Even better, just read from standard input, and accept the key as argument - that's much more consistent with user expectations.

std::string code = "";
std::string line;
while(getline(file, line))
    code += line;
file.close();

There's no need to read the whole of the input before starting to write any output.  The code will scale much better if you operate on reasonable-sized chunks (even a character at a time - that's why standard I/O is buffered), and write the output as it's produced.

std::string decoded = "";
for (std::size_t i = 0;  i < code.length(); ++i) {
    if (!iswspace(code[i])) {
        rep(j,n)
            if(key_matrix[j][0] == key[i%key.length()]){
                rep(k,n)
                    if(key_matrix[j][k] == code[i]){
                        decoded += key_matrix[0][k];
                        break;
                    }
            }
    } else {
        decoded += " ";
    }
}

This whole nested loops of linear search appears very inefficient.  It also drops all characters that are not spaces and not in dict - i.e. all punctuation and lower-case letters.
(It's not clear why you're using std::iswspace() instead of std::isspace() - we deal with plain char everywhere else, so why use the wide-char function here?  In any case, we need a cast to unsigned type, as char may be signed.)
I suggest a re-think of the algorithm here.  We need to be able to convert input characters to their indices in dict - I suggest a lookup table for that (with a sentinel value to indicate "not present").  We can pre-process the key by converting each character to the corresponding index before we start.  Then just iterate over input adding the current character's index to the corresponding key value, and indexing back into dict to give the output value.
We can avoid using % when indexing into dict by populating it with two copies of the alphabet.

Improved version
#include <cctype>
#include <climits>
#include <iostream>
#include <string>
#include <vector>

static const std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

static const std::vector<int> index = []{
    std::vector<int> v(UCHAR_MAX+1, -1);
    for (auto i = 0u;  i < alphabet.length();  ++i) {
        unsigned char c = alphabet[i];
        v[c] = i;
    }
    return v;
}();

int main(int argc, char **argv)
{
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " KEY" << std::endl;
        return 1;
    }

    std::vector<int> key;
    for (char *p = argv[1];  *p;  ++p) {
        int i = index[*p];
        if (i >= 0)
            key.push_back(i);
    }

    if (key.empty()) {
        std::cerr << "Invalid key" << std::endl;
        return 1;
    }

    std::size_t keypos = 0;

    char c;
    while (std::cin >> c) {
        auto i = index[c];
        if (i < 0) {
            std::cout << c;
        } else {
            static const std::string alphabet2 = alphabet + alphabet;
            std::cout << alphabet2[i+key[keypos++]];
            if (keypos >= key.size())
                keypos = 0;
        }
    }
}

You might want instead to process chunks (perhaps lines), in which case a function like this would be more appropriate:
// decrypt using key beginning at keypos; update keypos with new position
static std::string decrypt(const std::vector<int>& key, std::size_t& keypos, std::string s)
{
    static const std::string alphabet2 = alphabet + alphabet;

    for (auto& c: s) {
        auto i = index[c];
        if (i >= 0) {
            c = alphabet2[i+key[keypos++]];
            if (keypos >= key.size())
                keypos = 0;
        }
    }

    return s;
}

This separated function also makes it easier to test functionality (I did that myself whilst writing the monolithic main() above), and it may well be a stepping-stone to creating an object-oriented version (where key and keypos would be members of the decryption object).


Coin Flip Streaks - correct streak condition

PEP 8
The Style Guide for Python Code "gives coding conventions for the Python code ... intended to improve the readability of code and make it consistent across the wide spectrum of Python code."
Since a large majority of Python projects follow PEP-8 guideline, it behooves you to follow those conventions as much as possible (except when you shouldn't, as outlined in section 2 of the document).
These conventions include:

using snake_case for variable names, instead of mixedCase.  Eg, numberOfStreaks should be named number_of_streaks.
imports should be followed by a blank line
functions should appear after import and before main code.  Eg) number_of_streaks = 0, list_of_100 = [], and streaks = 0 should appear after def toss():
the mainline code should be inside a "main-guard" (if __name__ == '__main__':) statement.

Correctness
Task

I fear you have interpreted the practice task incorrectly, or at least, implemented it wrong.
The task is to check "if there is a streak of 6 'heads' or 'tails' in 100 coin tosses, not "how many" streaks occurred.  It asks for a percentage success rate.  If you had an unfair coin, with your code you may find several dozen streaks in each experiment, and well over 10,000 streaks in the course of the 10,000 experiments, which would lead to a "percentage success rate" that exceeds 100%, which is suspect.

(Incorrect, but left in to support Heap Overflow's answer)
Math
print('Chance of streak: %s%%' % (numberOfStreaks / 10000))
Simply dividing a count by the total possible does not yield a percentage; 95 / 100 = 0.95 ... you must multiply by 100 to compute the result as a percentage.
WET -vs- DRY and locality of reference.
Your code reads (roughly):
listOf100 = []

# ...

for experiment ...:

    for flipCoin in range(100):
        listOf100.append(toss())

    ...

    listOf100 = []

You see the listOf100 = []?  WET stands for "Write Everything Twice".  In contrast, DRY stands for "Don't Repeat Yourself".  In general, with less code, the code is easier to understand and maintain.  If variables are defined near where they are used, the code is also easier to understand and maintain.
Let's DRY this code up.
# ...

for experiment ...:

    listOf100 = []
    for flipCoin in range(100):
        listOf100.append(toss())

    ...

Now, listOf100 = [] exists only once, and it exists right before it is being used.
Now, as demonstrated in the other two answers, you can replace the initialization and repeated .append() with a more concise list comprehension.
Magic Numbers
I see several numbers in the code: 10000, 100, listOf100, 1, 5, 0.  What do these numbers mean?
If you wanted to change the number of experiments from 10000 to 20000 how many changes would you have to make?  Two?
If you wanted to changed the number of tosses per experiment from 100 to 200, how many changes do you have to make?  Change a number once, and a variable name 6 times???  That seems awkward and unmaintainable.  And wrong, because there is also the comment.
Named constants go a long way to improving maintainability.
NUM_EXPERIMENTS = 10_000

...

for experiementNumber in range(NUM_EXPERIMENTS):
   ...

print('Change of streak: %s%%' % (numberOfStreaks / NUM_EXPERIMENTS))

Finally, 5 is the length of the streak.  No, wait, 6 is the length of the streak.  Uh.  It would be nice to have a STREAK_LENGTH = 6 named constant, and then the algorithm could use if streak == STREAK_LENGTH - 1:, with perhaps a comment explaining the "why".
Unused variables
The variable created in this statement:
for experimentNumber in range(10000):

is never used anywhere.  It only serves two purposes.

to make a syntactically valid for statement.
indicate this loop is executed once per experiment.

The second reason is obsoleted by changing the magic number 10000 into the named constant NUM_EXPERIMENTS.  By convention, _ is used as the throw-away variable, used only to satisfy syntactical reasons.  So this for statement could become:
for _ in range(NUM_EXPERIMENTS):

Ditto for the for flipCoin in range(100): statement; it could become (say):
    for _ in range(COIN_TOSSES_PER_EXPERIMENT):

Formatting numbers
Using the %s format code for a number is not a good habit to get into.  It may produce ok results here; you are dividing by 10,000 so likely will get a number with only 4 decimal points.  But if you were asked to perform a different number of experiments, such as 7, you could get a lot of digits after the decimal point.
Using the format code %.4f produces four digits after the decimal point, regardless of the actual number of experiments.
Improved Code
Others have answered with advanced -- or at best, tricky, and at worst, confusing -- methods of detecting the streaks including:

string concatenation and substring searching
functional programming
converting head/tail coin values into same/different values

In the spirit of the beginner tag, let's investigate a clearer way.
You are currently testing listOf100[listItem] == listOf100[listItem + 1] to check if a coin face is the same as the next.  The [listItem + 1] is the awkward part here, necessitating stopping our loop one element before the end of the list.  Let's rethink this.  Instead of comparing two coins at a time, how about examining only one coin at a time?  Simply remember the whether the streak is currently heads or tails, and ask if the current coin matches that streak:
    for coin_face in coin_tosses:
        if coin_face == current_streak_face:
            streak_length += 1

When we find a coin that doesn't match the current streak, we have to start the streak with one instance of the new face.
        else:
            current_streak_face = coin_face
            streak_length = 1

Of course, we have to initialize our state variables.  The first coin won't match any previous value, so we should start off with some value which is neither heads nor tails.
    current_streak_face = None
    streak_length = 0

Using this, we can create a simple coin streak detector function:
def contains_a_streak(coin_tosses, minimum_length):

    current_streak_face = None
    streak_length = 0

    for coin_face in coin_tosses:
        if coin_face == current_streak_face:
            streak_length += 1
        else:
            current_streak_face = coin_face
            streak_length = 1

        if streak_length >= minimum_length:
            return True

    return False

Notice that since we are initialize the streak_length to 1 when we find a different coin face, and adding 1 when we find a matching face, our streak_length counter is actually the length of the streak, and not one less.  No more 5 -vs- 6, confusion, which is a huge win for clarity.
Actually, there is nothing about this detector that is specific to coin tosses.  We could use it for dice rolls, win-loss streaks, and so on.  Just need to change some variable names ... and change the initial value from None to a different sentinel, so it could even properly detect a streak of None values at the start of a sequence of values.
def contains_a_streak(iterable, minimum_length):

    current = object()   # a unique value that can't possibly match this first
    streak_length = 0

    for value in iterable:
        if current == value:
            streak_length += 1
        else:
            current = value
            streak_length = 1

        if streak_length >= minimum_length:
            return True

    return False

Now, our code for one experiment could become:
def coin_toss_experiment(number_of_tosses, streak_length):

    tosses = []
    for _ in range(number_of_tosses):
        tosses.append(toss())

    return contains_a_streak(tosses, streak_length)

As noted elsewhere, the list initialization and repeated appending could be replaced with list comprehension:
def coin_toss_experiment(number_of_tosses, streak_length):

    tosses = [toss() for _ in range(number_of_tosses)]

    return contains_a_streak(tosses, streak_length)

(Actually, a generator expression might be even better, but since we're focusing at the beginner level, we'll just note it in passing.  When you're a bit more comfortable with Python, look up what it is and what it would do for you, and why you might want to use one.)
We need to run multiple experiments to compute the streak success rate:
def repeated_coin_toss_experiment(num_experiments, num_tosses, streak_length):
    successes = 0
    for _ in range(num_experiments):
        if coin_toss_experiment():
            successes += 1

    print(f"Chance of streak: {successes/num_experiments*100:.2f}%")

Finally, we need to run our experiment:
if __name__ == '__main__':
    repeated_coin_toss_experiment(10_000, 100, 6)

If you want to change the number of tosses, you only have to change one number.  If you want to change the number of experiments, again, you just have to change one number.  Change the streak length?  Well, you get the idea.


Detecting UI thread hanging and logging stacktrace

Great idea! That makes it possible to get information about hanging / lacking GUIs. That kind of (probably) valuable information are only available via customer feedback otherwise :). It would be interesting to know if you already use that ThreadMonitor, if you already evaluated the log files and if you got some interesting information out of it ;).

I have just a few small comments to the code:

There is no need to use a Task for the infinity loop. You can just use a Thread here.
However, when using a Task, I would start it with TaskCreationOptions.LongRunning. Otherwise, a thread from the thread pool will be used (and blocked). Thread pool threads are usually hold available for short running actions.
There is no way to get notified if an error occurs within the endless loop. To avoid that, put the endless loop in a try catch block or add a ContinueWith for the failure case to the created task.
The class allows to start the ThreadMonitor multiple times. That is actually not desired, therefore I would throw an exception when trying to call Run twice.
Honestly, I don't understand how your "DeadLockPreventionLogic" works, but it looks kind of adventurous. Probably, the StackTrace may contain some interesting information, but it is also possible that the StackTrace belongs to unproblematic logic that was coincidentally executed when the StackTrace has be caught. Additional to logging the StackTrace, it makes definitely sense to log the entry points of all use workflows.


Rspec test for Rails method to return alphabetically sorted list of tags

Your test code is merely a copy of your model code, so you're not really testing anything.

Rather, your unit test should rely on fixtures, and the expected answer should be hard-coded in the test.


Code Review:
grade > -1 && grade < 101

That's fine for integers. But you have to consider that somebody can come along behind you and modify your types sometime in the future. If I changed the type of grade to float (not an unreasonable change). Then a grade of -.05 becomes valid. I would change this to be:
grade >= 0 && grade <= 100
!cin.fail()

Checking the state of the file manually is basically never correct (its an anti-pattern). Also this case is also wrong as fail() does not check for end of file, so you could have hit end of file not read anything into grade.
A better check is:
cin.good();

But the more usual check is
cin  // If used in a boolean context (like an if) it will be converted
     // to a boolean based on the call to good.

if (cin && grade >= 0 && grade <= 100)

But even this is not usual. Usually you check the result of the read operation by placing the read into the if statement.
if (cin >> grade && grade >= 0 && grade <= 100)

Note: the operator>> returns a a reference to the stream, so this is functionally the same as the line above. But it imparts more information.
What you are saying here is: if the read works and the grade is in the range [0..100] we succeeded.
Looking at your dispatch. You have a structure that is the same every time you call.
vector<tuple<int, char>> fork {
        tuple<int, char> {90, 'A'},
        tuple<int, char> {80, 'B'},
        tuple<int, char> {70, 'C'},
        tuple<int, char> {60, 'D'},
        tuple<int, char> {0, 'E'},
};

Since this is never modified it should be marked const. Also since you really only want to build the structure once just mark it static that way you only build the structure on the first call. Also there is a convenience function called make_tuple
static const vector<tuple<int, char>> fork
{
        make_tuple(90, 'A'),
        make_tuple(80, 'B'),
        make_tuple(70, 'C'),
        make_tuple(60, 'D'),
        make_tuple(0,  'E')
};

This loop is a bit C-Like (though it works).
for (vector<tuple<int, char>>::size_type i = 0; i != fork.size(); i++)

Though I would have used some typedefs to make it more readable:
typedef std::tuple<int, char>  MarkRange;
typedef std::vector<MarkRange> MarkSet;
for (MarkSet::size_type i = 0; i != fork.size(); ++i)  // prefer pre-increment

If you were using C++03 then I would be using iterators:
for (MarkSet::const_iterator i = fork.begin(); i != fork.end(); ++i)

But since C++11 we have had range based for
for (auto const& mark : fork)

Note:
// Since C++11 prefer `using` over typedef
using MarkRange = std::tuple<int, char>;
using MarkSet   = std::vector<MarkRange>;

Using std::endl is not a good idea. Prefer "\n". The difference is that endl flushes the stream.  Flushing is usually always wrong. The streams will flush themselves at appropriate times let the code do its work.
Note: The most common complaint about C++ stream is that they are slower than C stream. This is usually down to inappropriate calls to flush that significantly degrades performance when done incorrectly (and manually is usually always incorrect).
Questions:

Is the vector of tuple an unnecessary overhead over the simple if/else?

I like it. Its called Data Driven programing (where the code uses data to define its structure). This is usually considered best practice.

Is it actually slower, or does compilation optimizes execution?

I doubt you could measure the difference.
But if it is important then you should measure it.
People will always have opinions on this; they are not relevant. The only thing that matters is data. BUT it only matters if this is important. Normally I would consider more expressive readable code more important. This code is readable and easy to update (I could even put the data into a config file that is modified seprately).

In this case it probably doesn't matter because the grade set is small, but is this approach considered a good/correct practice if we were to have a bigger set?

Even in bigger list this seems like a better idea.


Program for finding longest run of zeros from a list of 100 random integers which are either 0 or 1

Generating a random list

Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and return it. This way, you will be able to call my_list a second time without having l being 200 items long. It will make the code easier to test.

Also note that l as a variable name is a poor choice as certain fonts make it hard to distinguish from 1.

You also use the "empty list + for loop + append" pattern which can be converted to a more efficient list-comprehension:

def random_list(length=100):
    return [random.randint(0, 1) for _ in range(length)]

Note that, as suggested by @jpmc26 in the comments, and starting with Python 3.6, you can simplify further using random.choices:

def random_list(length=100):
    return random.choices((0, 1), k=length)

Finding the longest sequence

Your manual counting is not that bad, but usually counting a number of element can be done using either sum or len depending on the iterable at play. And finding the longest count can be delegated to max. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.

itertools.groupby will happily do the grouping for you. But you won't be able to use len on the resulting groups, so you can add 1 for each element in said group.

Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct max that the longest count is 0 in such cases:

def largest_row_of_zero(iterable):
    return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)

Testing code

Instead of putting the testing code at the top-level of the file, you should take the habit of using an if __name__ == '__main__': guard:

if __name__ == '__main__':
    l = random_list()
    print(l, largest_row_of_zero(l))


Merge multiple pandas dataframe along with np.where to process values

keyword arguments
I had to check the documentation to find out what the 1 means in df1.drop('new_id', 1). More clear would be df1.drop('new_id', axis=1), or even better: df1.drop(columns=["type_", "new_id"])
Don't overwrite raw data
You add columns and values to df1, which makes finding problems harder.
With a bit of reshuffling, and using df.join instead of pd.merge, you can make your intent a bit more clear
df6= df1.join(
    df2.assign(level="l1").set_index(["id", "level"]),
    how="outer",
    on=["id", "level"],
).join(
    df3.assign(level="l2").set_index(["id", "level"]),
    how="outer",
    on=["id", "level"],
    lsuffix="_",
)

np.where
If you're looking for null, you can use fillna or combine_first. To replace 'l2' with 'l3', you can use Series.replace.
df7 = df6.assign(
    id=df6["new_id"].fillna(df6["id"]).astype(int),
    type=df6["type_"].fillna(df6["type"]),
    level=df6["level"].replace("l2", "l3")
).drop(columns=["type_", "new_id"])

I don't know whether this approach will be faster, but to me, what happens here is a lot more clear.


Expect all values in an array to be greater than 30

Array::some can be used to reverse the test logic and return earlier.


Chi Square Independence Test for Two Pandas DF columns

I would try to use existing pandas features where possible to keep this code minimal - this aids readability and reduces the possibility of bugs being introduced in complicated loop structures.

import pandas
from scipy.stats import chi2_contingency

def chisq_of_df_cols(df, c1, c2):
    groupsizes = df.groupby([c1, c2]).size()
    ctsum = groupsizes.unstack(c1)
    # fillna(0) is necessary to remove any NAs which will cause exceptions
    return(chi2_contingency(ctsum.fillna(0)))

test_df = pandas.DataFrame([[0, 1], [1, 0], [0, 2], [0, 1], [0, 2]], columns=['var1', 'var2'])
chisq_of_df_cols(test_df, 'var1', 'var2')


There's a few ways you could improve your CheckAndConvert class and functions.

Design Suggestions

Fluency - It's not a requirement by any means but fluency helps readability. CheckAndConvert.CheckInt is almost a sentence, perhaps something shorter Parse.Int or Parse.Bool.
Naming Simplicity - On the lines of the previous suggestion, your class/function names imply that it's doing more than simply parsing a given value. You're checking if the parse succeeds but then returning a default value if it fails. The user of this function needs not to know about the check part at all. And the word check is repeated (class and function name). Programmers don't typically like redundancy.
Naming Accuracy - CheckInt and CheckDouble they check each other if their primary data type TryParse fails. In the case of CheckDouble I don't think it's ever going to be true for the second if-statement. In the case of CheckInt since int.TryParse can fail on decimals that you want to be integers I would just always use double.TryParse with a cast. (Remember: Cast truncates and Convert.ToInt32 rounds).

I would be surprised if any of the above suggestions other than maybe the removal of int.TryParse would actually improve performance but it would still make for some cleaner simpler code.

Performance

If you've narrowed down that the parsing of values into their respective properties is the time consumer research alternative ways to parse numbers (they're ugly but claim they're faster) additionally this might be helpful for possibly speeding up your SetValue calls (be warned it's a long read).

Link Information

The parse numbers link decribes parsing the string yourself as .Parse uses CultureInfo and stuff that can slows it down.
The SetValue link describes research into using delegates for method calls in reflection and shows some promising performance boosts that I've used myself.


In addition to the remarks given by Blindman67, I'd like to suggest the following:

Passing options:

The first few lines of your function are some kind of configuration block:

let currentPage = currentPageInput, // input
    range       = 5,  // amount of links displayed
    totalPages  = 20, // determined by amount of items, hardcoded for readability
    start       = 1;  // default

Now, when the number of pages changes, you need to touch your code and modify the totalPages initialization.

So you will probably want to introduce function arguments with default values:

function doPaging(currentPageInput, start = 1, totalPages = 20, range = 5) {
  ...
}

// Example:
doPaging(3, 1, 4); // ["0", "1", "2", "[3]", "4"]

Unfortunately, if you e.g. desire to change just the number of total pages, this argument order still requires you to specify all arguments preceding the totalPages argument.

Therefore, you might want to consider using default parameters in combination with destructuring assignment:

function doPaging(currentPageInput, {start = 1, totalPages = 20, range = 5} = {}) {
  ...
}

// Example:
doPaging(3, {totalPages: 4}); // ["0", "1", "2", "[3]", "4"]

Separating logic and view:

Your current implementation returns an array of strings destined for immediate output. This comes with a few drawbacks:

If you want to change the markup of an active page index, you need to modify your code and replace the brackets [${i}] with something else.
If you want to output a usable pagination, e.g. a list of anchor tags, you need additional code to map each page index string to its URL. This would probably require you to map each index string back to a number first.

So how about just returning the paging range as an array of numbers? Later on, within your HTML template, you can then print page == currentPage ? `[${page}]` : `${page}` or - in case you print HTML - simply select a different CSS class for the current page.

Handling corner cases:

In case you choose a range of 5, but the total number of pages is set to just 4, a call to doPaging(4) will return ["0", "1", "2", "3", "[4]"] including an undesired "0" at the beginning. A robust implementation should probably reduce the range according to the available total number of pages.

Fixing issues:

Since we now allow user defined start values, we need to fix issues arising from start values that are not 1 caused by the hard coded "force start at 1" within your code.

Putting it all together:

Choosing simpler and more consistent variable names as well as renaming the nondescript doPaging to getPagingRange, we get an easier to read and understand implementation.

Replacing the loop with Array.from yields more descriptive code.

Adding a single comment describing the function's behavior instead of many individual inline comments helps the reader to better understand the purpose and usage of the function.

/**
 * Return an integer range within [min, min + total) of given length centered
 * around the current page number.
 */
function getPagingRange(current, {min = 1, total = 20, length = 5} = {}) {
  if (length > total) length = total;

  let start = current - Math.floor(length / 2);
  start = Math.max(start, min);
  start = Math.min(start, min + total - length);

  return Array.from({length: length}, (el, i) => start + i);
}

// Examples:
console.log(getPagingRange(20)); // [16, 17, 18, 19, 20]
console.log(getPagingRange(3, {total: 4, length: 3})); // [2, 3, 4]
console.log(getPagingRange(3, {min: 0, total: 4, length: 3})); // [1, 2, 3]


The code is good. The only comment I have is that the data and its representation are highly coupled so it may be good idea to invest some time in separating them. But it will make sense only if this application will grow and evolve. Now it is very neat and good looking.


Reduce repetitive code in Lotto simulator

First, you need just one Scanner.

Second, you could store the number choose by the user in an array.

Third, you could iterate the array to find the number there, instead of doing a lot of if and else if.

Forth, the user always wins. This looks like a bug. The while(true) ensures that the numbers are choosen in a way that eventually all the choosen numbers will be drawn. More, nothing stops the user from choosing a number more than once.

Fifth, the wait(100) will fail. You should use Thread.sleep(100) instead. EDIT, oops, I thought you were using Object.wait. It currently works, but Thread.sleep is better.


Extending CGPoint to conform to Hashable

I can see no advantage of computing the hash value from Int(self.x) and Int(self.y). As you already noticed, truncating the floating point
numbers to integers loses information and therefore causes
hash collisions.
CGFloat is (like all Swift number point types) Hashable, and its
hashValue is just the integer with the same memory representation
(as one can see from the implementation). So all possible CGFloat values have different hash values, which makes x.hashValue, y.hashValue a much better basis for computing a hash value for CGPoint than
Int(self.x) and Int(self.y).
It remains the question how to compute the hash value of the point
from the hash values of its coordinates. Of course there can be no
"best hash" which works for all data sets. But in order to get
at least an idea which might be better or worse, I used the
following simple test:
var hv = Set<Int>()
var count = 0
for i in -200 ..< 200 {
    for j in -200 ..< 200 {
        count += 1
        let p = CGPoint(x: CGFloat(i)/20, y: CGFloat(j)/20)
        hv.insert(p.hashValue)
    }
}

print(count, hv.count)

It computes the hash values of 160,000 points where both
x and y range from -20 to 19.9 in steps of 0.1, and counts
how many different hash values we get.
The referenced hash function from here,
translated to Swift 3, is
public var hashValue: Int {
    return (self.x.hashValue << MemoryLayout<CGFloat>.size) ^ self.y.hashValue
}
// # of points: 160000 hash values:  79976

Your hash function is definitely worse (but we already know why):
public var hashValue: Int {
    var hash = 23
    hash = hash &* 31 &+ Int(self.x)
    return hash &* 31 &+ Int(self.y)
}
// # of points: 160000 hash values:  1249

Using hashValue instead of Int() improves it considerably:
public var hashValue: Int {
    var hash = 23
    hash = hash &* 31 &+ self.x.hashValue
    return hash &* 31 &+ self.y.hashValue
}
// # of points: 160000 hash values:  68827

But this is still not really satisfying.
The Boost library has a hash_combine()
function for exactly this purpose, and its implementation
has one generic variant
template <typename SizeT>
inline void hash_combine_impl(SizeT& seed, SizeT value)
{
    seed ^= value + 0x9e3779b9 + (seed<<6) + (seed>>2);
}

as well as specializations for uint32_t and uint64_t.
Translated to Swift this would be:
func hash_combine(seed: inout UInt, value: UInt) {
    let tmp = value &+ 0x9e3779b9 &+ (seed << 6) &+ (seed >> 2)
    seed ^= tmp
}

It is crucial here to use unsigned integers, otherwise
the right shift seed >> 2 would preserve the sign bit.
The Swift hashValue is a signed integer, however, therefore
we have to convert accordingly:
public var hashValue: Int {
    var seed = UInt(0)
    hash_combine(seed: &seed, value: UInt(bitPattern: x.hashValue))
    hash_combine(seed: &seed, value: UInt(bitPattern: y.hashValue))
    return Int(bitPattern: seed)
}
// # of points: 160000 hash values:  159958

As one can see, this hash function has only 42 collisions, and is
far better than the previous ones (for this data set). It is also relatively simple to compute, and can easily be adapted
for types with more properties.
If that is not good enough then you can try other "hash combine" methods,
for example the the 32-bit or
64-bit specializations from the Boost library (depending on the
size of Int on your platform) and check if that works better.
Another one is
here,
and there are probably much more.
Finally you asked:

Or, would the best approach not even be to extend CGPoint at all and to just use a custom Swift container struct or an NSObject subclass?

It depends. If the tuple represents a "point in space" then using (and
extending) CGPoint seems fine to me. If the tuple represents something
else (and you just chose CGPoint because it happens to have two
properties) then I would prefer to define a custom struct which
clearly shows its purpose. A subclass of NSObject would be a
reference type and should only be chosen if you need reference
semantics. Otherwise value types are preferable.

Update: As of Swift 4.1, the compiler can synthesize the
conformance to Equatable/Hashable if all of its members are Equatable/Hashable, see SE-0185 Synthesizing Equatable and Hashable conformance.
Example:
struct Point : Hashable {
    let x: CGFloat
    let y: CGFloat
}

The actual hash function is an implementation detail, but in my test
it worked excellently: The above test code produced no collisions at all
for the 160,000 points.


This is not a review but an expanded comment.

Brute force is bad. Do some math first.

Consider a non-decreasing number of length \$n\$ formed by  exactly \$k\$ given digits. It has exactly \$k - 1\$ transitions from a digit to a larger one, and there are exactly \$n - 1\$ places where the transition may happen, so there are \$\binom{n-1}{k-1}\$ such numbers. The \$\binom{10}{k}\$ ways to pick \$k\$ digits give a subtotal of \$\binom{n-1}{k-1}\binom{10}{k}\$, and a grand total is \$\sum_{k=1}^{10}\binom{n-1}{k-1}\binom{10}{k}\$.

So the problem nails down to efficient calculation of binomial coefficients, which in this case is fairly straightforward, since you never need more than 10 factors.


Copying and pasting one inputs value into other input with the same name

Why not at least save the intermediate to avoid rerunning that:

$(document).on('click', '.--copy', function () {
    var obj = $(this).closest('div').find('input');
    var input_name = obj.attr('name').split('-')[0];
    $('input[name^=' + input_name + ']').val(obj.val());
});


What can I do better in this ViewModel Creator?

Var

Use var for method-scope declarations when the right-hand side of the declaration makes the type obvious. This gives you the convenience during refactoring of being able to change the type in just one place.

e.g.

IViewModel<T> iVmInterf = (IViewModel<T>)Activator.CreateInstance<T>();

should be

var iVmInterf = (IViewModel<T>)Activator.CreateInstance<T>();

Naming

You should not include hints about the type of a variable in its name, unless the variable only makes sense with that name. Additionally you should not abbreviate names, abbreviating names makes your code harder to read for no positive benefit.

e.g.

IViewModel<T> iVmInterf

should be

IViewModel<T> viewModel

and

private IProductViewModel interf;

should be

private IProductViewModel viewModel;

Design

Why does ProductViewModel contain an instance variable of type IProductViewModel when it itself implements ProductViewModel? It doesn't appear to be used anywhere and it doesn't make obvious sense why a view model would need a reference to another view model of the same type.

IViewModel<T> takes an instance of itself for T, which I do not agree with from a design perspective. It doesn't make as much sense to say "A view model for product view models" than it does to say "A view model for products". As such I'd recommend making T refer to the model type the view model is for.

Secondly, IViewModel's one method seems entirely useless. Imagine the scenario in which you want to call GetViewModel. Every time you call that method, you will be doing so with an instance of that viewmodel. It's a wasted call, you already have that data.

With that in mind, your factory method becomes one line:

public T BuildViewModel<T>() where T : class, new()
{
    return Activator.CreateInstance<T>();
}


Make password/hash verification algorithm more efficient

Starting with the code in my answer to your related question, we can factor out the source of the words being guessed and encapsulate it all in functions:

def get_users_to_crack(file_name):
    users = {}
    with open(file_name) as file:
        for line in file:
            username, hashed_password, *_ = line.split(':')
            users[username] = hashed_password
    return users

def crack(users, words):
    cracked_users = {}
    for password in words:
        if not users:
            print("Cracked all passwords")
            return cracked_users, {}
        for username, hashed_password in users.items():
            if crypt.crypt(password, hashed_password) == hashed_password:
                print(f'La contraseña del usuario {username} es {password}')
                cracked_users[username] = password
                del users[username]
    return cracked_users, users

Now we just need a supplier of words. This can be either from a file, similar to your other question:

def dictionary_attack(file_name):
    with open(file_name) as file:
        for line in file:
            word = line.rstrip('\n').capitalize()
            if 4 <= len(word) <= 8:
                yield word

Or you build it yourself, according to the scheme you supplied here:

from string import ascii_lowercase as a_z, ascii_uppercase as A_Z, digits
from itertools import product

def get_chars(length):
    """Produces the allowed chars according to the scheme given
       [a-zA-Z][a-z]*(0-5)[a-z0-9]*2"""
    assert length > 2
    return [a_z + A_Z] + [a_z] * (length - 3) + [a_z + digits] * 2

def brute_force(min_length, max_length, get_chars):
    for length in range(min_length, max_length + 1):
        for word in product(*get_chars(length)):
            yield "".join(word)

You can then combine them into one nice tool:

if __name__ == "__main__":
    users = get_users_to_crack("shadow3")
    n = len(users)

    users_cracked_1, users = crack(users, dictionary_attack('out68.lst'))
    print(f"Cracked {len(users_cracked_1)} out of {n} users passwords using a dictionary attack")

    users_cracked_2, users = crack(users, brute_force(4, 8, get_chars))
    print(f"Cracked {len(users_cracked_2)} out of {n} users passwords using brute force")

    if users:
        print(f"{len(users)} users passwords not cracked")


Is this a valid implementation of a 'future'?

What's your inheritance relationship between A and B? If A is the parent of B, it's bad design if A needs to do ANYTHING with B in the constructor/destructor because B will not be valid until after A's construction.

If you require RAII design, look at lazy resource acquisition to avoid re-acquisition going up the constructor chain (vector).

Why do you want a smart pointer to a pointer. Smart pointers help you when there is no clear custodian of an instance (or shared primitive type), and you want to destroy an instance only when there are no more users of it. The way you are using the smart pointer means that only a memory location of a pointer is freed, not the memory of a type instance. Plus when you construct this class, the pointer held by the 'value_ptr' is random, which is bad.

I'm not sure where you're going with this 'future' class and how it solves your inter-dependance between A and B.

If A and B need a similar member, make them inherit from the same parent class. If you want to hide this 'shared' member or you want a pure-virtual interface, simply declare the interface as well as defining some sort of linking parent.

If A and B need access to the same instance of something, use a singleton that is inherited from a shared parent.

If you do need a shared instance, and you need to free any resources (IE files) held by the singleton, it's better to write an explicit free function. That way you will easily see where it's being cleaned up.

If you mean you want to avoid initializing a resource that's defined in a parent class, until your child class A or B does, perhaps look at making an explicit, polymorph function.

Hope that helps.


Spring Boot methods to add and remove relationships

You may extract the action part as a method parameter (I am using BiConsumer in this case).

@Override
public void performActionOnRecords(Long personRecordId, AssociationDTO associationDTO, BiConsumer<PersonRecord,Document> action) {
    PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
    if (personRecord == null)
        return;

    for (Long documentId : associationDTO.getDocumentsId())
        documentRepository
                .findById(documentId)
                .ifPresent(document -> action.accept(personRecord,document));

    personRecordRepository.save(personRecord);
}

and call the methods as

performActionOnRecords(personId, associationDTO, (personRecord, document) -> personRecord.getDocuments().add(document)); // To add document

and,

performActionOnRecords(personId, associationDTO, (personRecord, document) -> personRecord.getDocuments().remove(document)); // To remove document


Comparing strings with contents of columns

The obvious approach here would be to use a map or unordered_map to convert from a column name to a pointer (or reference) to the actual column. This will typically reduce the line count by about 2:1. More importantly, however, it makes most of that simple initialization, and the code that executes at run time is about 3 lines or so. An implementation would look something like this:

struct PaymentTransaction {
    int id;
    int gas_station_id;
    int nozzle_id;
    // more members here
public:
    void setAttributes(sqlite3_statement const *);
};
void PaymentTransaction::setAttributes(sqlite3_statement const *statement) {
    for (int i = 0; i < statement->sqlite3_column_count(); i++) {
        std::string name = sqlite3_column_name(statement, i);

        static const std::map<std::string, int &> int_members{
            { "id", id},
            {"gas_station_id", gas_station_id},
            {"nozzle_id", nozzle_id}
            // ...
        };

        auto pos = int_members.find(name);
        if (pos != int_members.end()) {
            pos->second = sqlite3_column_int(statement, i);
        }
    }
    // Possibly similar code for members of other types
}

Note that this requires a separate map for each type of column (integer vs. floating point vs. string) but can have a single map for all the columns of one type.

You could separate the map from the function, and make the function a template to avoid duplicating that code (but this may be more trouble than it's worth, depending on how many types you need to deal with--all you've shown are ints, but I don't know how accurately that reflects you real use.


Searching for a sum of any series in array

Both the original and your revision have the same problem.  They reset sum/res to zero on every iteration and then recalculate it.  To avoid this, store the sums in an array.

int[] sums = new int[a.length + 1];
sums[0] = 0;
for (int i = 0; i < a.length; i++) {
    sums[i + 1] = sums[i] + a[i];
}

This takes \$\mathcal{O}(n)\$ time to calculate.

For any i, sums[i] is the sum of the first i elements of the array.

Since we know that all values are positive, adding a value always increases the sum.  And removing a value decreases it.  So how do we use that?  Consider

int left = 0;
int right = 0;
while (right < sums.length) {
    int sum = sums[right] - sums[left];
    if (sum == target) {
        return true;
    }

    if (sum > target) {
        // if the sum is too big, reduce it by dropping a value from it
        left++;
    } else {
        // if the sum is too small, increase it by adding a value to it
        right++;
    }
}

I changed the name of num to target as being more descriptive of what it represents.

This uses the sums stored in our array to calculate the sum from left + 1 to right in the original array.

On each iteration of the loop, we either return or increment one of the indexes.  The worst case is where the sum of the elements before the last is too small but the last element itself is equal to or larger than the target.  In that case, we increment right sums.length times and we increment left sums.length times.  That's \$2n + 2\$ total, which is \$\mathcal{O}(n)\$.

This takes \$\mathcal{O}(n)\$ space as well.  If you need constant space, you can skip the first part and track the sum as an integer.  See here.

If you can't see the deleted answer from mtj, it basically says to do something like

int left = 0;
int right = 0;
int sum = 0;
while (right < a.length) {
    if (sum > target) {
        // if the sum is too big, reduce it by dropping a value from it
        sum -= a[left];
        left++;
    } else {
        // if the sum is too small, increase it by adding a value to it
        sum += a[right];
        right++;
    }

    if (sum == target) {
        return true;
    }
}

return false;

Assumes that target and all the values in a are positive.

You can see a solution to a similar problem here as well.


The query you showed is not running as-is, where's this CFID alias coming from?

As SQL Server supports Standard SQL's Analytical Functions you might rewrite MAX/Subquery using RANK (or ROW_NUMBER):

SELECT ...
FROM
  ( SELECT CDM.CompanyId,
           any additonal columns you need,
           RANK() OVER (PARTITION BY CDM.CompanyId
                        ORDER BY CDM.[Date] DESC) AS rnk
        FROM [{schema}].[CompanyData] CDM
            INNER JOIN #Locations T
                ON T.LocationId = CDM.CompanyId
  ) TM
WHERE rnk = 1


Java 8 streams

Aside from the typos pointed out by @SuperBiasedMan, you can use Java 8's stream-based processing as an alternative for generating your Map result.

private static final int UPPER_LIMIT = 100;
private static final String[] KEYS = new String[]{ "00 - 09", /* ... */ "Unknown" };

private static int categorize(int year) {
    return Math.min(year, UPPER_LIMIT) / 10;
}

Map<String, Long> results = persons.stream()
                    .map(Person::getDob)
                    .filter(Objects::nonNull)
                    .map(ThisClass::getDiffYears)
                    .map(ThisClass::categorize)
                    .collect(Collectors.groupingBy(ageCategory -> KEYS[ageCategory],
                                Collectors.counting()));

Define the UPPER_LIMIT of your age categorization and the desired category names.
From a Stream of your Person objects, map() to their birthdays by calling Person::getDob as method reference.
filter() null birthdays by using Objects::nonNull.
map() birthdays to ages by calling your getDiffYears(Date) method. Note that if it is not a static method, the method reference then becomes this::getDiffYears.
map() ages to the age category by calling categorize(int) to get the desired array indices for KEYS. If you have not realized yet, ThisClass is just a placeholder for the actual class name.
collect() the age categories into the desired Map result groupingBy() our categorization and counting() the elements per category.

Other advice

Your method should return a Map instead of HashMap so that callers of this method only need to deal with the interface, and not the implementation.
You may want to consider how to handle for null inputs to getDiffYear(Date). Should it return a negative value?
You can also experiment with deriving the category names in a programmatic manner, instead of using literal Strings.
You can even think about making your age categorization depend on a configurable upper limit (100) and band (10). For example, how easy will it be to treat the upper limit as 101 (UPPER_LIMIT = 101) and a band of 11 years per category (hint: take a closer look at the suggested code...)?


As you probably expect, there's not much that's crazy about your code. It's pretty straight-forward. There's just a little bit that belies your C and Java background. ^_^

There's no need for a mutable guess in read_guess.
There's no need for an input variable at all. This also removes the need for an explicit type as it can be inferred from the return type.
For a very performance oriented approach, move the string allocation outside of the loop. In the off chance that someone keeps entering invalid numbers, there's no reason to allocate a new string each time.
Don't end the expect string with punctuation as a colon is automatically added.
Add spaces around binary operators
Generally, I'd indicate that min and max are CONSTANTs, but doing so may be overkill here, as it would be verbose (const MIN: i32 = 1).

extern crate rand;

use std::io;
use std::io::prelude::*;
use std::cmp::Ordering;
use rand::Rng;

fn read_i32() -> i32 {
    let mut input = String::new();

    loop {
        input.clear();
        io::stdin().read_line(&mut input).expect("Failed to read line");
        match input.trim().parse() {
            Ok(n) => return n,
            Err(_) => println!("Please input a number."),
        };
    }
}

fn read_guess(min: i32, max: i32) -> i32 {
    loop {
        let guess = read_i32();
        if guess < min {
            println!("Please input a number that is at least {}.", min);
        } else if guess > max {
            println!("Please input a number that is no larger than {}.", max);
        } else {
            return guess;
        }
    }
}

fn main() {
    println!("Guess the number!");
    let (min, max) = (1, 10);
    let secret_number = rand::thread_rng().gen_range(min, max + 1);
    loop {
        println!("Please input your guess, between {} and {}.", min, max);
        let guess = read_guess(min, max);
        match guess.cmp(&secret_number) {
            Ordering::Less    => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal   => {
                println!("You win!");
                break;
            },
        };
    }
}

For fun, here's an alternate read_i32 that didn't end up looking much better:

fn read_i32() -> i32 {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let line = line.expect("Failed to read line");
        match line.trim().parse() {
            Ok(n) => return n,
            Err(_) => println!("Please input a number."),
        }
    }
    unreachable!("Ran out of standard input");
}

  Since everything is immutable unless specified otherwise, what is the purpose of a constant?

A constant can exist outside of a function, while let statements must occur inside of one. Additionally, a const is likely to be inlined at compile time, while a static can have its address taken. More info is in the book.

  Can you briefly explain when and why I should use the unreachable macro?

You should use unreachable when the code is unreachable, but the compiler cannot statically verify that. In my example, the compiler cannot know that standard input will provide data forever or return an Err which will cause a panic.

Actually, thinking about it further, your original code will go into an infinite loop when /dev/null is connected to standard in: cargo run </dev/null. The version I have will panic and print a marginally helpful error message. Maybe my version is useful after all...


Here are my thoughts ( I'm using a tablet and so cannot test my suggestions). You are already turning off screen updating and calculations which is good.

Avoid using Select where possible - there are plenty of examples of this.
The Insert in your code is probably a very slow process because Excel does a lot of work. Why not simply copy the entire data in the columns you want and then paste four times onto another sheet? No need for the Insert or the 1,000 copy & pastes.
Testing each row for the person's name to see if a worksheet exists and then copying just that row can also be changed. Why not sort the data by name, then run down the data keeping track of start row of current name and looking to see when the name changes? Then you copy the data from the start row up to the row before the current one. That way you could do just one copy & paste per name into the named worksheet.


Initializing an Android activity by reading a CSV file with image IDs, names, and descriptions

People from Android have a really comprehensive documentation about it at https://developer.android.com/guide/topics/data/data-storage.

Short answer: yes, there are better ways: SharedPreferences for simple data; Local database (SQLite) for complex data. Both of them can be persistent.


Find the correct path through a 5 x 5 grid (coderbyte 'Correct path')

Unnecessary Import

numpy is not required for this challenge.  You are using none of its special capabilities.  The following:

arry = np.array([[0]*5 for i in range(5)])

could easily and simply be replaced with

arry = [[0] * 5 for _ in range(5)]

Notice the throw-away _ variable being used for the unused loop comprehension variable.  If you don't use it, don't name it.

StopIteration

It is rarely necessary to use try: ... except: ... to catch the StopIteration exception.  You just need to use a loop structure.

    move_combinations = itertools.product(_map.keys(), repeat=q_count)

    while True:
        arry = np.array([[0]*5 for i in range(5)])
        arry[0][0] = 1  # start at 0, 0

        current_x = 0
        current_y = 0

        try:
            moves = next(move_combinations)
        except StopIteration:
            return None

        ...

could be written much more simply as:

    for move in itertools.product(_map.keys(), repeat=q_count):

        arry = [[0] * 5 for _ in range(5)]
        arry[0][0] = 1  # start at 0, 0

        current_x = 0
        current_y = 0

        ...

    return None

Variable Names

_map is an odd local variable name.  A single leading underscore is used to signify private/protected object members.  Local variables are never visible in an outer scope, so do not need to be flagged as "private".  A trailing underscore is usually used to avoid name collisions, in which case the variable should be named map_.  But confusion may be better avoided by naming the variable not with its type but with its role; this dictionary mapping contains directions, so it may be better named directions.

arry is also a poor name.  visited would be a better choice.

True / False

You are storing 0 and 1 in your arry matrix, and then testing for the truthiness of arry[current_x][current_y].  It would be clearer to store False and True in these.

visited = [[False] * 5 for _ in range(5)]

...

    ...
    elif visited[current_x][current_y]:
        break
    else:
        visited[current_x][current_y] = True

Unnecessary Slicing

Neither s.replace(...) nor s[::].replace(...) will modify the original s contents.  There is no need to use slicing to create a copy prior to the replace operation:

        ss = s.replace("?", "{}").format(*moves)

(And as Carcigenicate mentioned, move it out of the loop)

Magic Numbers

The code is littered with 4's and 5's.  What if you want to change this to work with a 5x6 or 4x7 grid?  You need to correctly change a lot of numbers.  Perhaps you should pass in the size of the grid, instead of using hard-coded values:

def calcpath(s, rows=5, columns=5):

    start = (0, 0)
    end = (columns - 1, rows - 1)

    ...

       visited = [[False] * columns for _ in range(rows)]
       current_x, current_y = start

       ...

           if current_x < 0 or current_x >= columns:
               break
           ...

       if (current_x, current_y) == end:
           ...

    ...

Optimizations

There should be several obvious checks you can make.  For the 5x5 grid case:

len(s) must be even
len(s) must be >= 8
len(s) must be < 25

Moreover, the directed counts of the left-right and up-down moves will produce a reduced search space.

With s = "???rrurdr?":

>>> print(*(sum(c == dir for c in s) for dir in "lrud?"))
0 4 1 1 4

There are 0 lefts, 4 rights, so we need to move +0 right to yield a net +4 right; there is 1 up and 1 down, so we need to move +4 down to yield a net +4 down.  We have 4 moves up for grabs, so they all need to be downs.  There is no point checking for combinations including up, left and right moves!

You can expand the logic of this for other cases: "drdr??rrddd?" has a net 4 right, 5 down, so the additional moves must include 1 up.  Then, it could add either a left/right pair, or an up/down pair, so you only need to check permutations of "ulr" and "uud", for a total of 12 possibilities, instead of your \$4^3\$ search space.


I'm not sure how you got the original list-within-a-list input, but have you looked into Java Streams? Here's a tutorial that may help.

It looks like you're taking in a LinkedList, turning it into a string to manually delete the [[ and ]], splitting on comma, then adding each item to a new list.

Why not do something like the following:

private static List<String> splitListOfString(LinkedList<String> list) {
    List<String> myList = new LinkedList<>();
    list.stream().forEach(item -> myList.add(item));
    return myList;
}

In the above code, you're leaving the elements in the list (instead of converting to string), retrieving each item, then adding to your output list. It may need to be modified slightly to match your input.


Automated Tweet of new inbound Enquiries in PHP7 (Laravel 5.2)

Code intent

The main problem with your code is that it does not give any reasons as to why it performs the way it does which makes understanding, reviewing or upgrading it difficult.

$event->body->id

What is a body id on the event? is it always present? I'm assuming its an int but I guess it could contain letters? Does $event_id adequately describe it?

Enquiry::find(...)

Ok here I don't know the return signature of ::find() I assume it finds N instances of Enquiry based on most framework behaviour, does it return an array or a object container? can I call it $enqueries?

Next is the reject() function which I assume is like array_filter based on the name I guess it works in the inverse, checks that return true will be rejected? I have vague prior knowledge on this thanks to mind share of the chosen framework but if I had no knowledge I would assume it's your own function which would mean I need to read the implementation

Next we've got a nameless function that performs: !$enquiry->shouldTweet() there's no type hinting so I don't know if reject() is expecting a boolean at this point in time I'll have to read all of the function, my main question is what is an $enquiry and what does it mean when it does not "shouldTweet()".

By chance you've used a boolean operator on the return so I can now confirm a boolean return feeding back to reject() can we remove all doubt with a type hint?

Can we array_filter on $enqueries instead of reject()? Then we can talk about shouldTweet() without using !.

Let's assume based on your implementation details thus far that there are multiple enquiry objects that are being filtered on whether they should tweet.

Is canTweet() usable here? shouldTweet() implies there might be mitigating circumstances to whether we can or cannot tweet.

The last call you have is a custom map() function, a map function will typically convert child array elements into a different child array element but your operation next suggests it does not aim to do that, I think it aims to create a side effect, that's more suitable for array_walk than array_map.

The semantics is important because the inbuilt functions tell you what happens in the loop without having to read the loop, particularly helpful when a loop is a non trivial amount of lines long.

I'm assuming that sendToTwitter() returns NULL because I've seen no evidence of its use, it is returned to the mapping operation but the result of that is now lost in the fluent object as far as we're concerned from this call point, a type hint could have hinted at the truth.

Code Reuse

The other problem your code has is that the anonymous functions which by themselves cannot be reused, if we upgrade them to full functions we give the reader some context through the function name and we are then able to call the code from multiple different locations.

The function name should help tell future maintainers how much scope the function should be responsible for and telegraph what the function is supposed to do in context.

Strong binding to your chosen framework

Your code is strongly bound to your framework which means it will be harder to extract out of the framework in the future and potentially brittle every time the framework upgrades or any of its components upgrade.

It's tempting to think Laravel will last forever but we're definitely due a new paradigm switch in the PHP world, if you're not sure ask Drupal 6/7 developers about the dangers of framework dependent code.

Fluent interface is needlessly obscuring

Laravel's fluent interface coming out of Enquery::find() makes it unnecessarily difficult to figure out what reject and map are operating on and its unclear where the result of map are in that object, is there a way to extract them? If so I guess they are an array of nulls now? I can't tell from this call point.

The main problem with the fluent interface is that it's robbed you of the opportunity to name the result of your intermediate operation, a name which shows code intention is worth way more than your implementation code in code review and code maintenance.

Overly generic method name

The method name handle will probably not stay adequate if you start tweeting anything else in your system or add any other methods to tweet.

Handle what? Why? When? What operation is done when something is "handled"? Maybe we can call it tweet_enquiry or a name that suggests that we tweet the enquiry based on NewEnquiryEvent you will know this answer better than I do, translate what you know about the context into your code.

Below I've created some code that telegraphs to the reader certain information that I've made assumptions about all through reading the code

<?php

namespace App\Listeners\Enquiry;

use App\Events\NewEnquiryEvent;
use App\Exceptions\DebuggableException;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\Stores\Enquiry;

class Tweet
{
    /**
     * On enquiry event send a enquiry tweet if enquiry should do.
     *
     * @parm Enquiry
     *   The enquiry object.
     */
    public function tweet_enquiry_on_event(NewEnquiryEvent $event) : void
    {
        $event_id = (int) $event->body->id;
        $enqueries = (array) Enquiry::find($event_id);
        $enqueries_that_should_tweet = array_filter($enqueries, 'enquiry_should_tweet');
        array_walk($enqueries_that_should_tweet, 'enquiry_send_to_twitter');
    }
}

// These functions are probably best off near the enquiry object.

/**
 * Should an enquiry object be able to tweet?
 *
 * @param Enquiry
 *   The enquiry object.
 *
 * @return bool
 *   Whether an enquiry should be able to tweet.
 */
function enquiry_should_tweet(Enquiry $enquiry) : bool
{
    $enquiry_should_tweet = $enquiry->shouldTweet();
    return $enquiry_should_tweet;
}

/**
 * Send the enquiry to twitter.
 *
 * @parm Enquiry
 *   The enquiry object.
 */
function enquiry_send_to_twitter(Enquiry $enquiry) : void
{
    $enquiry->sendToTwitter();
}


Finding Matches and writing results to file C#

Some things to speed this process up

subid is only used if it contains a certain string. Use a hashset or dictionary where each lookup is O(1) instead of O(n) ; which is in this case O(166K) in worst case
EDIT: StreamReader and File.ReadLines actually behave the same
Start using using for handling input/output; it makes sure that object are garbage collected one it's out of scope. Using declares a scope for these.
Personally I put all configuration on top
You could also use StreamWriter to write the file, which is just a handle (same principle as the StreamReader, but then for writing)

With only minimal adjustments, this should be significantly faster.

Improved code

public static void Main(string[] args)
{
    // file paths
    string path = "Z:\\subid.txt";      //166k file
    string RxPath = "Z:\\matched.txt";  //Destination file
    string folderPath = "Z:\\rawfiles"; //folder location (contains 1000 text files)

    char splitter = '\u0001';

    // subid is ONLY used to check if it contains something. Make it a hashset
    HashSet<string> subid = new HashSet<string>(File.ReadAllLines(path));
    List<string> RxClaims = new List<string>();

    string[] lineObject;
    int count = 0;

    foreach (string file in Directory.EnumerateFiles(folderPath))
    {
        Console.WriteLine("Processing " + file);

        // use a streamreader to go through files!
        using (StreamReader reader = new StreamReader(file))
        {
            string line = reader.ReadLine();
            lineObject = line.Split(splitter);

            //Check if that value is equal to any of the numbers in the 166k, if so store in the list to print out later
            if (subid.Contains(lineObject[14]))
            {
                count++;
                RxClaims.Add(line);
            }
        }
    }

    File.WriteAllLines(RxPath, RxClaims);
    Console.WriteLine("Done, Number of Claims" + count);

    Console.ReadLine();
}


This sort of reminds me of how React implements Flux, where there's a huge switch list, and it becomes very unwieldy fast. Another developer created the Reflux library using the same concept in your alternative, a huge action map. So you're getting there. Let's just tweak your approach a bit.

First is you can use the noop approach, so you avoid the if and the function is always a function. It's pretty functional programming, but it streamlines your code, avoiding branching, unnecessary assignments and all that stuff.

Next, functionObj could be named better, like registeredFunctions. Also create an interface for you to add easily, as well as check for duplicates to prevent collision, or just register multiple ones under the same name.

Next is to allow your callers to define multiple args by not limiting the args. Here, we pass in arguments using apply. That way, the callers can provide any number of args they want and the receiving functions can still receive them. Of course, we slice off the first argument, which is your string of functions. You can assign any value as context for your registered function, but I prefer functions like these to have a context of null. Context becomes confusing when calling functions dynamically, and without a set convention.

var noop = function(){}
var registeredFunctions = {/* map of functions */}

function process(){
  var args = Array.prototype.slice.call(arguments, 1);
  functionString.split(";").forEach(function(functionName){
    (registeredFunctions[functionName] || noop).apply(null, args);
  });
}

An alternative would be to keep the huge switch, but instead of putting the actual code inside it, you call a function. There, you have a new scope. You just need to pass in everything you need into the function.

var args = Array.prototype.slice.call(arguments, 1);
switch(something){
  case 1:
  case 2:
    doSomething.apply(null, args);
    break;
  case 3:
    doSomethingElse.apply(null, args);
  default:
    doSomethingDefault.apply(null, args);
}


Representing a queue as a procedure with local state

You did not provide implementations of the queue operations using this representation. In SICP this usually refers to syntactic sugar to make working with a data structure less awkward, e.g.
(define (queue-insert! q item)
    ((q 'insert!) item) )

Also I would prefer different operation names, e.g.
append! instead of insert!
front instead of front-ptr
...


The eternal dilemma: bar.foo() or foo(bar)?

I think that the first variant can look nice, too, if you change the way you format the code and you always use the function as the last argument:

log(map(tablify(map(view, function(text) {
  return align(text)
}), 20), function(row) {
  return row.join(" ")
}).join("\n"))

Edit: Or if you really like indent:

log(map(tablify(map(view,
                    function(text) { return align(text) }
                ),
                20
        ),
        function(row) { return row.join(" ") }
    ).join("\n")
)


Find the closest number in a sorted list to a given target number

Conventions

The Style guide to follow in Python is PEP8. If you do so, your code blends right into the python community and it is immediately easier to follow. On that regard you'll see that the functions name's don't follow the recommended style.

getClosestValue

Should actually be:

get_closest_value

The relevant quote from PEP8 for this case

  Use the function naming rules: lowercase with words separated by
  underscores as necessary to improve readability.

Still in this topic, all the parenthesis used in the ifs are redundant and break the style.

if (target >= arr[n - 1]):

Should be turned into:

if target >= arr[n - 1]:

Although i suspect that this may be a habit brought from other languages.

Edge cases

You contemplated the case where the value is the highest or above, which gives you a quick way out:

# edge case
if (target >= arr[n - 1]):
    return arr[n - 1]

However there is no corresponding edge case for when the value is the lowest or below. I believe you merely forgot it.

#edge case - first or below all
if target <= arr[0]:
    return arr[0]

Logic

Now both edge cases are covered, so the while can be simplified to only have the navigation to the corresponding item if there is one.

while (left < right):
    mid = (left + right) // 2 # find the mid
    if arr[mid] == target:
        return arr[mid]

    if target < arr[mid]:
        right = mid
    else:
        left = mid + 1

After this last while if there isn't an exact match, calculate the nearest to the one you ended on, and return it:

if target < arr[mid]:
    return find_closest(arr[mid - 1], arr[mid], target)
else:
    return find_closest(arr[mid], arr[mid + 1], target)

Note that i don't need to check if mid - 1 or mid + 1 is a valid index, because if it wasn't it would mean that the value was below or above all elements, and those cases were already covered in the beginning of the function.
This is not only simpler but also more efficient since it only checks for the closest on the very end and not at each iteration.

Taking @bipll suggestion you can restructure the while a bit. Considering you are only getting if arr[mid] == target at the very last iteration you can first check for < or >. This avoids making one extra check that will fail most of the times:

while left < right:
    mid = (left + right) // 2  # find the mid
    if target < arr[mid]:
        right = mid
    elif target > arr[mid]:
        left = mid + 1
    else:
        return arr[mid]

When i have a simple condition with a return on both cases i rather write them inline since its easy to read and a bit more concise:

def find_closest(val1, val2, target):
    return val2 if target - val1 >= val2 - target else val1

But don't go over the top on this. It can easily be harder to read depending on the complexity of the condition.

Full Modified Version

For you to get a better picture of all the changes i mentioned, i'll leave you with the full modified version:

def get_closest_value(arr, target):
    n = len(arr)
    left = 0
    right = n - 1
    mid = 0

    # edge case - last or above all
    if target >= arr[n - 1]:
        return arr[n - 1]
    # edge case - first or below all
    if target <= arr[0]:
        return arr[0]
    # BSearch solution: Time & Space: Log(N)

    while left < right:
        mid = (left + right) // 2  # find the mid
        if target < arr[mid]:
            right = mid
        elif target > arr[mid]:
            left = mid + 1
        else:
            return arr[mid]

    if target < arr[mid]:
        return find_closest(arr[mid - 1], arr[mid], target)
    else:
        return find_closest(arr[mid], arr[mid + 1], target)

# findClosest
# We find the closest by taking the difference
# between the target and both values. It assumes
# that val2 is greater than val1 and target lies
# between these two.
def find_closest(val1, val2, target):
    return val2 if target - val1 >= val2 - target else val1


Determining triangle type from three integer inputs

You could encapsulate the conditions in a PotentialTriangle class. Note that the fields are of type long to avoid overflow when calculating whether triangle inequality is violated.

public class PotentialTriangle {
    private final long a, b, c;

    public PotentialTriangle(int sideA, int sideB, int sideC) {
        a = sideA;
        b = sideB;
        c = sideC;
    }

    public boolean isAnySideTooShort() {
        return a <= 0 || b <= 0 || c <= 0;
    }

    public boolean violatesTriangleInequality() {
        return a > b + c || b > a + c || c > a + b;
    }

    public boolean areSidesEqual() {
        return a == b && b == c;
    }

    public boolean areAtLeastTwoSidesEqual() {
        return a == b || b == c || c == a;
    }
}

This would vastly simplify your enum selection code, which I would put directly into the enum:

public enum TriangleType {
    ISOSCELES,
    EQUILATERAL,
    SCALENE;

    public static TriangleType ofPotentialTriangle(PotentialTriangle triangle) {
        throwIf(triangle.isAnySideTooShort(),
                "Length of sides cannot be equal to or less than zero");
        throwIf(triangle.violatesTriangleInequality(),
                "Sum of any two sides must be larger than the remaining side");

        if (triangle.areSidesEqual()) {
            return EQUILATERAL;
        }
        if (triangle.areAtLeastTwoSidesEqual()) {
            return ISOSCELES;
        }
        return SCALENE;
    }

    private static void throwIf(boolean condition, String message) {
        if (condition) {
            throw new IllegalArgumentException(message);
        }
    }
}


You have some of the right idea, but it looks like you're writing in Lisp. ;-)

There's no need to surround a single parameter in parentheses to pass it to a function, you mostly get this right so I think this one instance was just a slip up.

factors n = filter (\i -> n `mod` i == 0) [1..(isqrt(n))]
--                                                  ^ ^

Function application has the highest precedence of any operator in Haskell, so these parentheses are unnecessary.

factors n = filter (\i -> n `mod` i == 0) [1..(isqrt n)]
--                                            ^       ^

is_prime n = (factors n) == [1]
--           ^         ^

Common Haskell style often prefers function composition to function application.

isqrt n = floor . sqrt . fromIntegral $ n

Are you familiar with function composition from mathematics? It's the same thing here, f . g $ x is equivalent to f (g x), but it puts the emphasis of the code on the composition of functions and not the manipulation of values. This is a different mindset from what you're going to be used to coming from an imperative language, but it is integral to developing the Haskell "house style" and really effectively leveraging combinators and function composition.

Haskellers also love writing functions pointfree. This means leaving off the arguments that are being passed to your function where possible. Check out the Haskell Wiki on pointfree style for some motivation and examples.

isqrt = floor . sqrt . fromIntegral

All top-level definitions should be annotated with a type signature in Haskell. There are myriad reasons for always doing this, including acting as documentation, providing necessary information to the compiler on occasions, serving as a check against your own understanding of what your function is doing, &c.

factors :: Int -> [Int]
is_prime :: Int -> Bool
main :: IO ()

Common Haskell style is to use camelCase instead of snake_case, so isPrime instead of is_prime.

Wherever possible, Haskellers usually prefer case analysis to equality testing. If you rewrite factors to exclude testing 1 (which is a tautological case anyway, why bother evaluating it?) you can check if the list returned by factors is null with null, which enables more function composition goodness.

factors :: Int -> [Int]
factors n = filter (\i -> n `mod` i == 0) [2..isqrt n]

isPrime :: Int -> Bool
isPrime = null . factors

Here's the whole thing with my style adjustments.

isqrt :: Int -> Int
isqrt = floor . sqrt . fromIntegral

factors :: Int -> [Int]
factors n = filter (\i -> n `mod` i == 0) [2..isqrt n]

isPrime :: Int -> Bool
isPrime = null . factors

main :: IO ()
main = print . sum . filter isPrime $ [2..2000000]

Line breaks are important too. Doesn't it look much less cramped?

A comprehensively correct version of isPrime using guards to defend the honor of the negative numbers.

isPrime :: Int -> Bool
isPrime n | n < 2     = False
          | otherwise = null . factors $ n


Is this a good structure for my website?

Looking at your switch statement from an SEO point of view, I'd have to say: it's awful (sorry).
One of the first things to look at, when you're interested in SEO, is mod_rewrite. Search engines don't like urls that say nothing:

http://www.my-site.com/1
http://www.my-site.com/2
http://www.my-site.com/3
http://www.my-site.com/3

Doesn't say anything, whereas

http://www.my-site.com/home
http://www.my-site.com/services
http://www.my-site.com/gallery
http://www.my-site.com/contact

If anything, contains a sort-of meaningful keyword in the url from the off. Not only to crawlers love that, so do people browsing your site, for that matter.
Naturally, you have to keep this up, take the services page for example. I'm assuming that this is the page where you list what you do/offer, then all sub-nav urls should look like:

http://www.my-site.com/services/custom/cms
http://www.my-site.com/services/portfolio

And so on...
As to what Topener suggested: require_once 'pages/'.$_GET['page'].'.php'; is a terrible, terrible idea. Using data from the network, data the client can change to determine what files should be loaded is a huuuuge security hole!

From a CodeReview viewpoint:
A switch is all well and good, but it won't be long untill you find yourself scrolling up and down through your code, because the switch-case has grown so large. You'll have to invent hacky ways of dealing with form validation, and other types of client requests (pagination, ajax, file uploads, ...) in a manageable, safe and maintainable way.
A switch can be useful to shorten a lot of if-elseif-elseif-else branches, but not for something as crucial as to determine what page you have to present the client with. Most modern sites would go with a framework that implements the MVC pattern (Symfony2, ZendFW, Yii, ...)
As AD7Six said in his comment: if all you're after is a simple routing solution, there are micro-fw's, too, that might be a better fit for your problem. Even so, most frameworks are more or less modular, and with a dependency manager like composer, you can use the routing module(s) from any framework.

Your functions are also in violation of the PSR standards as defined by PHP-Fig (look for them on github). Classes (objects) start with an upper-case, functions/methods don't. Try to adhere to what little standards/conventions you have

Lastly, this just looks wrong to me:

switch($foo)
{
    default: homePage(); break;
    case 1: ...
}

The defaut case is the fallback case. To me, logic dictates that the default/fallback procedure is the last resort, and it should therefore be written as the last case label. Maybe that's just me, and my (sometimes over eager) tendency to use case fallthroughs:

switch ($foo)
{
    case 1:
    case 2:
        bothDoTheSame();
        break;
   case 3:
       threeSpecific();
   case 4:
       threeAndFour();
       break;
   default: defaultCase();//no break required
}


Your jQuery could be somewhat more efficient if you minimize $(...) element look-ups by storing them as variables or chaining them.

Also, I think you will see some benefit to replacing some jQuery constructs with their pure JS alternatives ($.each -> for, etc..)

Check out this set of jsPerf tests from this StackOverflow answer.

<script>
var fullcelllist = $(),
    lastVal ="",
    $celllistOption = $("#celllist option");

// ...

$("#filtercell").keyup(function() {
    var $this = $(this),
        $thisVal = $this.val();

// ...


When statement

You could replace:

if (userGuess > goal) computerSays("less !")
else if (userGuess < goal) computerSays("more !")

and

computerSays("Congratulation ! You found in $nbAttempts attemps.")

with:

when {
    userGuess > goal -> computerSays("less !")
    userGuess < goal -> computerSays("more !")
    userGuess == goal -> computerSays("Congratulation ! You found in $nbAttempts attemps.")
}

Extension functions

You could write computerSays as:

fun String.outputAsComputer() {
    println("Computer : " + this)
}

then to output Computer: ABC you could just write:

"ABC".outputAsComputer()

Although there are good arguments for and against this, it is more a chance to get used to extension functions


Create plain object from URLSearchParams

Since ES6 there is a cleaner solution with Object.fromEntries:
const url = 'https://tempuri.org/?token=secret&test=true';
const params = new URL(url).searchParams;
Object.fromEntries(params);

It will output an object like this:
{ token: 'secret', test: 'true' }

See browser compatibility of Object.fromEntries on MDN. Basically all browsers and Node.js 12+ except Samsung Internet, Opera Android, and Internet Explorer. Time to say goodbye to the old browsers :)


Some PEP8(which is a Style Guide for Python Code) comments regarding your coding style and formatting:

1. Spacing

Between methods, you should have two blank lines.

def questionOne():
    ....

def questionTwo():
    ....

2. Naming conventions

In PEP8 it's recommended to:

  Use the function naming rules: lowercase with words separated by
  underscores as necessary to improve readability.

That said, questionNumber would become question_number

I've seen many people using also camelCase for variables, so that's rather a matter of preference.

The same rule applies for your methods:

questionOne() -> question_one()

Put a space after each comma (,). It really helps when going through your code.

So this:

print("\nSo far ",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions\n")

Might be rewritten as:

print("\nSo far ", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
      questionNumber, "Questions\n")

3. Other comments

Instead of right = right + 1 you can use an augmented assignment: right += 1.

More, instead of doing this:

print()
print("So far",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
print()

You can do:

print("\nSo far",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions\n")

I don't like how you formatted the above print() but I'll come back to it later on.

Let's see what we've got so far using the modifications I mentioned so far:

import time

wrong = 0
right = 0
question_number = 0
name = str(input("Please Enter your name: "))

def questions():
    def question_one():
        global right, wrong, question_number
        print("What is the population of New Zealand?")
        print("Is it A:6.7m B:3.2m C:5.1m or D:4.5m")
        ans = str(input())
        if ans == "D" or ans == "d" or ans == '4.5' or ans == '4':
            print("You got it right!")
            right += 1
        else:
            print("You got it wrong!")
            wrong += 1
        question_number += 1

    question_one()
    time.sleep(2)
    print("\nSo far", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
          question_number, "Questions\n")
    time.sleep(4)

    def question_two():
        global right, wrong, question_number
        print("What year did the first european set foot on New Zealand (Abel Tasman)")
        print("Is it A:1830 B:1543 C:1642 or D:1765")
        ans = str(input())
        if ans == "C" or ans == "c" or ans == '1642' or ans == '3':
            print("You got it right!")
            right += 1
        else:
            print("You got it wrong!")
            wrong += 1
        question_number += 1

    question_two()
    time.sleep(2)
    print("\nSo far ", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
          question_number, "Questions\n")
    time.sleep(4)

    def question_three():
        global right, wrong, question_number
        print("How many Kiwi are there left in New Zealand (Approx)")
        print("Is it A:2000 B:600 C:70,000 or D:100000")
        ans = str(input())
        if ans == "D" or ans == "d" or ans == '100000' or ans == '4':
            print("You got it right!")
            right += 1
        else:
            print("You got it wrong!")
            wrong += 1
        question_number += 1

    question_three()
    time.sleep(2)
    print("\nSo far ", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
          question_number, "Questions\n")
    time.sleep(4)

    def question_four():
        global right, wrong, question_number
        print("How many new babys where born in New Zealand in 2015")
        print("Is it A:61,000 B:208,000 C:98,000 or D:18,000")
        ans = str(input())
        if ans == "D" or ans == "d" or ans == '100000' or ans == '4':
            print("You got it right!")
            right += 1
        else:
            print("You got it wrong!")
            wrong += 1
        question_number += 1

    question_four()

questions()

Digging deeper:

Globals

Try to avoid using globals as much as possible. Global variables should be avoided because they inhibit code reuse. The reason they are bad is that they allow functions to have hidden (as in "non-obvious" and "undeclared") and thus hard to understand side effects. Also, this can lead to Spaghetti code.

Duplicate code

As you can see, your functions are pretty much the same, so you can use this and try making a single method. More, we can get rid of that ugly usage of inner methods. It's just not necessary in this case.

What I'd do is:

Create three lists: one containing questions, one answers and another one which contains the correct answers.
Then create a simple method, and basically do what you've done, but in a shorter / nicer way.

Let's see what we have:

list_of_questions = ['What is the population of New Zealand ?',
                     'What year did the first european set foot on New Zealand (Abel Tasman) ?',
                     'How many Kiwi are there left in New Zealand (Approx) ?',
                     'How many new babys where born in New Zealand in 2015 ?']

lists_of_answers = [['A:1830', 'B:1543', 'C:1642', 'D:1765'],
                    ['A:1830', 'B:1543', 'C:1642', 'D:1765'],
                    ['A:2000', 'B:600',  'C:70,000', 'D:100000'],
                    ['A:61,000', 'B:208,000', 'C:98,000', 'D:18,000']]

list_of_correct_answers = [['D', 'd', '4.5', '4'],
                           ['C', 'c', '1642', '3'],
                           ['D', 'd', '100000', '4'],
                           ['D', 'd', '100000', '4']]

def questions():
    wrong = 0
    right = 0

    for each_question, each_answer, each_correct_answer in zip(list_of_questions, lists_of_answers, list_of_correct_answers):
        print(each_question + '\n' + ' '.join(each_answer))
        get_answer = raw_input()

        if get_answer in each_correct_answer:
            print('Your answer is correct!\n')
            right += 1
        else:
            print('That is not the answer I had in mind!\n')
            wrong += 1
        print('So far, you answered correctly to {0} questions and incorrectly to {1}. Good luck!'.format(right, wrong))

if __name__ == '__main__':
    questions()

You can observe that I also added if __name__ == '__main__':. The reason I did this is that you can also import your code as a module in another script and then run the main function if and when your program decides.

Next steps:

Please try to be consistent when writing code.
Avoid printing to many things. And if you do so, try to review your grammar.


A more efficient enqueue algorithm in Java

It seems like what you are trying to accomplish here is to make your Queue class immutable. That in itself is good, but there are a couple of issues with your approach:

Creating a new class for this is not needed. There already exists classes for that. Use Collections.unmodifiableList to create one.
Your class does not implement the List interface (or the Queue interface for that matter). I guess there is a way to access the embedded List<T> such as getList hidden among "some constructors and helper functions", but if all that does is to return this.body; then your entire list is still accessible and modifiable.
The List<T> body field could be, and should be, declared final.

Instead of your entire Queue class, you might want to use this static method:

public static <E> List<E> addToList(List<E> oldList, E newElement) {
    List<E> temp = new ArrayList<E>(oldList);
    temp.add(newElement);
    return Collections.unmodifiableList(temp);
}

I should add however, that there is a difference between an unmodifiable list and what I understood about your approach. An unmodifiable list in Java does not allow any change to the list at all, such as list.set(index, obj).


Do you like this kind of helper, which creates short lived helper objects through a delegate?

it gives my code the same quality of feeling independent of resource allocation as when using constructor injection

But it's not. With constructor injection, the caller can easily use another implementation or create the resource with different parameters. With your helper method, that is gone. And you can use constructor injection with short lived resources: inject a factory for that resource (that could be a simple Func<Resource> delegate or an interface) instead of the resource itself.

All in all, your helper method might be useful to avoid repeating common code, but not much else. And even with that, it doesn't help much.


Simulating coin flips and plotting a histogram

I had some smaller points to make on several aspects of your code but I won't mention them since the whole thing can be written more idiomatic and simple style without using any recursion or mutation.

Note the use of Seq.sumBy and Array.countBy to cut down on a lot of the work:

let random = System.Random()

let heads () = random.Next(0, 2) = 1

let calculateHeads n =
    { 1 .. n } |> Seq.sumBy (fun _ -> if heads () then 1 else 0)

let getFrequencies n m =
    let counts =
        Array.init m (fun _ -> calculateHeads n)
        |> Array.countBy id
        |> Map
    Array.init (n + 1) (fun i -> counts.TryFind i |> Option.defaultValue 0)

let displayCoin frequency =
    for c in frequency do
        printfn "%d%s -- (%d)" c (String.replicate (c / 10) "*") c

let frequency = getFrequencies 32 1000
displayCoin frequency

I also made random a module level value instead of passing it around everywhere. The downside of this is you can't test individual functions deterministically.

If you're not already doing so, you should send code to F# interactive in your IDE to get a much faster feedback cycle for trying out ideas and exploring data.


Your solution is missing critical feedback, or alternatively, instead of feedback, fallback.

If the node is added successfully then the method should report back that success. Alternatively, it should fail, and report that fail. A simple bool return value should suffice.

If you choose to use a fallback, instead of feedback, then you should consider how the system should behave if the 'insert after' item is not found... insert at the beginning of the list? Append at the end? Whatever fallback you choose, you should implement and document it correctly.

Leaving the system as it is, though, is not a good option.

For loop blocks where there is no code in the block (a for loop with all the logic in the loop clauses), I recommend instead that you use a while loop....

Node* p = list.head;
while (p && p->data != pos) {
    p = p->next;
}
if (p) {
    ....
    return true;
}
return false;

As for whether there's a better way/algorithm, well, for a LinkedList, like you have, then no. The scan to locate the insert-point is needed.

Finally, you should only create the new Node{value} if you actually locate the insert point. There is no need to create the new node unless you are actually going to insert it.


Avoiding the use of ordinal() in an already-deployed enum

A negative parameter value or a parameter value >= values.length passed to fromDB() will throw an IndexOutOfBoundsException, which is less meaningful than the original IllegalArgumentException since the IndexOutOfBoundsException is complaining about an implementation detail rather than about bad input.

To avoid the IndexOutOfBoundsException, use a Map<Integer, STATUS> instead of an array.

However, if there are only a few defined values as in the question, a Map is probably not needed either.  fromDB() can simply iterate over values() and return the match when found, otherwise throw IllegalArgumentException.  Add the Map when performance profiling indicates fromDB() is a bottleneck.

Also, consider changing STATUS to Status, to follow standard naming conventions.


You can try this:
import time, sys
# This program will prompt you to state your age and then will proceed to
# calculate how long till __ age

# Introduction
print("Hello. ")

# Defining Functions
def main():
    while True:
        try:
            myAge = int(input("Please enter your age: "))
        except ValueError:
            print("I'm sorry, please enter your age as a numeric value.")
            continue
        break

    def secondV():
        while True:
            try:
                global desiredAge
                desiredAge = int(input())
                print(f"Do you wish to be {desiredAge}?")
                choose()
            except ValueError:
                print("Please enter a numeric value.")
                continue
            break

    def desiredFuture():
        while True:
            try:
                global desiredAge
                desiredAge = int(input())
                while True:
                    if desiredAge < myAge:
                        print("Silly, time does not move backwards. Learn how to embrace the future, not fear it.")
                        print('Please input an age you wish to be in the FUTURE now...')
                        desiredFuture()
                        break
                    if desiredAge == myAge:
                        print(f"You are already {desiredAge}")
                        break
                    else:
                        print(f"Do you wish to be {desiredAge}?")
                        choose()
                        break
            except ValueError:
                print("Please enter a numeric value.")
                continue
            break

    def choose():
        global yourWish
        yourWish = input()
        while yourWish.lower() == ("yes" or "y"):
            print("Okay... calculating...")
            time.sleep(1)
            print()
            print(f"To be {desiredAge} you would have to wait {desiredAge - myAge} years.")
            print()
            reDo()
            break
        else:
            print("Erm... please input your desired age now:")
            secondV()

    def reDo():
        print('Would you like to try again?')
        runBack = input()
        while True:
            if runBack.lower() in {'y', 'yes'}:
                print()
                main()
            else:
                print("Okay... Goodbye!")
                sys.exit("goodbye")
                break

    print(f"You are {myAge}.")
    print("What is your desired age? ")
    desiredFuture()
    choose()
    print()

main()

Use f strings instead of + it's more convenient.
And in the try except, you can just do break at the end, not put it in else. And it doesn't exit, so you can import sys and use sys.exit()
And do import time at the first line.