Converting 'list of Foo' into 'lists of Foo properties'

That method is immense, and is surely impossible to easily read and maintain. Once you break it into smaller methods you will be able to work with it ("just like those acorns, one at a time").
This will also help avoid repetitions of code.

I propose creating a class to hold all that data, and merely instantiate a Left and a Right objects of that class. Then move the loading of data into the class as well.

Then the foreach is limited to 3 lines plus all the ifs:

public class WildGooseChaser
{
    class Foo { public int Frob; public int Frib; }
    class Bar { public Foo Left; public Foo Right; }

    private InternalData Left;
    private InternalData Right;

    class InternalData
    {
        public int[] Frobs;
        public int[] Fribs;
        // ... 27 more lines of similar.

        public InternalData(int dataLength) {
            Frobs = new int[dataLength];
            Fribs = new int[dataLength];
            //... you get the idea
        }

        public void LoadBar(int index, Bar bar) {
            Frobs[index] = bar.Left.Frob;
            Fribs[index] = bar.Left.Frib;
            //...27 more lines of similar
        }
    }

    public void ProcessBars(Bar[] bars) {
        Left = new InternalData(bars.Length);
        Right = new InternalData(bars.Length);

        int counter = 0;
        foreach (Bar bar in bars) {
            Left.LoadBar(counter, bar);
            Right.LoadBar(counter, bar);

            if (bar.Left.Frob == MAGICNUM_A) {
                Left.Fribs[counter] = MAGICNUM_B;
            }

            if (bar.Right.Frob == MAGICNUM_C) {
                Left.Fribs[counter] = MAGICNUM_D;
            }

            counter++;
        }
    }
}

If you receive an array, you can use for instead of foreach.
So you can either get rid of the counter variable, or receive an IEnumerable<Bar> instead.


Selecting mail messages that meet one of four search criteria

First of all, the indentation is next to inexisting. The code is badly formatted. Are you scared of tabs? There's no excuse for a wall of unformatted SQL. There are online tools to fix it for you!

You should have all keywords in capitals. Why is that? Well, it's an old convention that comes from times where there was no syntax highlighting. Nowadays, they are everywhere! Heck, even I made one! But still, capitals help to read it.

And as such, your Mail table should be all in lowercase.

You are extremelly inconsistent with your backticks. Either you use it or you don't use it! Don't mix both, please!

And now, to remove repetition.

All messages are within an interval of 48 hours.
All have admin_status = 1
admin_id is always the same
sent_to only changes if subject like 'RE:%'
mail_reply_status is always 0
user_id is never 0
core_event_inactive shows twice with the value of 0

With this information, I've made this:

SELECT * FROM mail WHERE admin_status = 1
    AND admin_id = 4
    AND user_id = 0
    AND mail_reply_status = 0
    AND admin_inbox_date > DATE_SUB(CURDATE(), INTERVAL 48 HOUR)
    AND ( sent_to = 0 XOR ( sent_to = 4  AND subject LIKE 'RE:%' ) )

Since the LIKE is a really heavy check, we put it at the very last. Since SQL supports short-circut evaluation, this positioning may result in faster queries. The slowest checks are the last ones.

It was really hard to follow if everything is 200% correct, but I hope I've nailed it. Please, comment if you see something innacurate.


Singleton

I wouldn't call your Database class a singleton wrapper, as you can have multiple instances of it (not of the PDOObject field, but of the Database class).

See here and here for actual singleton pattern.

I don't think that your approach is necessarily bad though.

Is this overkill?

I think that you are a bit dishonest in your example. Your not actually using BindParam in your code, and you would still have to catch the exception that is thrown. So instead of saving multiple lines per query as you suggest, you are actually only saving one, which isn't that much.

But doing it this way does provide you the ability to easily add functionality to executing a query, or change how you execute queries all together. I think that this is a big advantage and a good case for having this class.

Returning in the constructor

  return self::$PDOObject;

Why are you returning the PDO instance in the constructor? This seems a little odd.

Style

I say this a lot, but good style actually is important and leads to easier to read code.

remove all unnecessary newlines. You have a lot of newlines, which makes your code hard to read
be consistent with your curly brackets and indentation (always indent the same amount, always have curly brackets close at the same indentation as the opening statement).
also be consistent with spaces (try{ -> try {)
comments: //handle exception isn't a useful comment, especially if it is handled by just throwing the exception :)


Looking to shorten method of parsing arguments in BASH

Use the ${variable?error message} syntax to error on empty arguments.  Use shift to remove parsed arguments from the positional parameters, so that the next unseen argument is always $1.  If there are any arguments left at the end, there were too many.

When a message isn't enough, you can use trap … EXIT to call a function on error.  Remember to remove the trap after parsing and at the very start of your handler function.

This version isn't any shorter than yours but it's more generic.  You can add parameters or rearrange their order without altering the numbers in the existing logic.  The error-handling is in one place instead of two.

show_help() {
 trap - EXIT # omitting this can lead to an infinite loop
 exec $0 -h
 exit
}

trap show_help EXIT
error_usage="Usage: $0 input-file [-o output-file]"
input=${1?$error_usage} && shift
[[ $1 = -o ]] && output=${2?$error_usage} && shift 2
[[ -n $1 ]] && echo $error_usage && exit 0
trap - EXIT

echo "input=$input output=$output"

Rather than invoking ourselves to display help, I'd just put the help logic in the show_help function.


Checking winning conditions in Tic-Tac-Toe

What does all winning conditions in Tic Tac Toe have in common? They are all straight lines!

The idea of having one method that can be called multiple times is a good one, to do that we need to input the starting position, and how much we should change x and y with every time.

We also need a way to stop the loop, we can either stop when we notice that we will go out of bounds, or we can stop after a specific number of checks. In this implementation, I chose to hard-code 3 as the limit for how many tiles to check.

public static bool AllFieldsTheSame(int startX, int startY, char[][] board, int dx, int dy)
{
    char firstField = board[startY][startX]
    if (firstField == ' ')
    {
        return false;
    }

    for (var i = 0; i < 3; i++)
    {
        int y = startY + dy * i;
        int x = startX + dx * i;
        if (board[y][x] != firstField)
        {
            return false;
        }
    }

    return true;
}

Then this method can be called repeatedly as follows:

public static bool SomeoneWins(char[][] board)
{
    // Check columns
    for (var x = 0; x < board.Length; x++)
    {
        if (AllFieldsTheSame(x, 0, board, 0, 1))
            return true;
    }

    // Check rows
    for (var y = 0; y < board.Length; y++)
        if (AllFieldsTheSame(0, y, board, 1, 0))
            return true;

    // Check diagonals
    if (AllFieldsTheSame(0, 0, board, 1, 1))
        return true;

    if (AllFieldsTheSame(2, 0, board, -1, 1))
        return true;
}

However, I suspect you are also interested in who wins, in which case you could have both AllFieldsTheSame and SomeoneWins return a char instead of a bool.

And by the way, I'd prefer to use an enum for the possible values of each tile. A char can have the value of Q, but I don't believe you want to place a Q tile in your game. Using an enum reduces the eliminates any possible risk of invalid characters.


Is there a better way to get the index of a minimum?

perhaps the function which.min() would do the trick?

which.min(ar.mle$aic)

it won't shorten your code all that much:

ar.mle$aic[which.min(ar.mle$aic)]


Chris, you have misunderstood the text quoted about the caller supplying all of the arguments. Your original prototype was okay. I imagine the text you read meant that if a function declares parameters a, b and c, then the caller must supply arguments (ie values of some sort) for all of those parameters. If there are 3 it must supply 3,, and of the correct types.

Given the prototype you imposed upon yourself, your implementation was not bad, but you should learn to use the standard library functions.  Your loops for copying characters are better implemented using memcpy.

Also when you declare a variable, if you can it is often better to assign a value to it immediately, not on the next line. In C, this doesn't really matter, but in C++ doing this (assigning, or constructing immediately) is more efficient.

Here is my version of your function with its original prototype.  Note that instead of exiting on malloc failure, I print a message and return NULL. The caller must handle the failure.  Note also that allocated memory must be freed.  In a simple program like this, it is not important, as it will be freed on exit from the program. But remember that you have to do it normally.

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

static char *
enhconcat (const char *str1, const char *str2)
{
    size_t len1 = strlen(str1);
    size_t len2 = strlen(str2);

    char *concatstr = malloc(len1 + len2 + 1);
    if (!concatstr) {
        perror("malloc");
        return NULL;
    }
    memcpy(concatstr, str1, len1);
    memcpy(concatstr + len1, str2, len2);
    concatstr[len1+len2] = '\0';
    return concatstr;
}

int main (void)
{
     const char *part1 = "Cuius est solum, ";
     const char *part2 = "eius est usque ad coelum et ad inferos.";

     char *cat = enhconcat(part1, part2);
     if (cat != NULL) {
         printf ("%s\n", cat);
         free(cat);
     }
     return EXIT_SUCCESS;
}


Form validation - security and input specification

I take it you're trying to protect yourself from XSS attacks, injection and general mallicious input. You're well on your way (but do have a look here, there are some interesting links at the bottom).

That said, I'd say your validation needs work on a couple of (crucial) points:

Don't be too strict: /^[A-Za-z '-]+$/i for a name doesn't allow "pièrre joão", but it clearly is a name. Just match all unicode chars, and drop the i flag, or change [A-Za-z] to [a-z]. I'd suggest you using this code: $name = trim($name); preg_match('/^[\w \'-]+$/u', $name). read about the u modifier here
Be consistent: You're applying 2 patterns to $name: /^[A-Za-z '-]+$/i and /^[A-Za-z]+\s[A-Za-z]+$/ This means that, the second time dashes and accents aren't allowed. That's not good, not good at all. If needs must, explode the $name on ' ' (a space), and apply the first pattern to each name individualy. Or work on the regex some more.
/^[A-Za-z][A-Za-z0-9_.-]{4,15}$/: This doesn't allow a 4 char long username, but requers the username to be at least 5 chars long: [a-z] matches 1 char, [a-z0-9_.-]{4,15} followed by at least 4, at most 15 chars. Now that's not bad, but it's not what you want.
Validate the right things: near the end, you do some checks on the password, but you're using the $username variable... typo?
Don't limit the length of a password: strlen($username) > 32? Why? If the client wants to use a longer (and possibly stronger) password, let them do so...
If you're going to do some checks on the password, at least to make sure that they're using chars, numbers and symbols. Not just "somealllowercasepass", but "S0m3@llw@kkyp@55"

Like I said above, you're missing out on some things, too:

No where are you calling strip_tags to ensure any markup is being removed from input
The password validation isn't applied to the correct variable, and should be improved, too
Your error messages are waay too specific. That's a bad idea! If I had bad intentions, and tried to fill in the form, each time trying some XSS trickery, and you give me feedback as in: "username mustn't contain chars like <, >, /, \, #, %", I can move on and try to exploit the next input field, and make sure I fill in a valid username, until I find a field where you let your guard down...
Keep your error messages general: "Not all input was correct/the expected format/met the requirements". That should be enough. But as DmitriZaitsev says: be careful not to alienate/offend the end-users, or your queste for safety might backfire (and leave you with no data to protect). A simple way of validating the email address and not restricting the username is to use the email address as username. If google and SO do it, why can't you?


Avoiding using strings when using Spring.Net by incorporating instantiation in class

Not sure if that is just the case in your example but it's rather uncommon in C# to prefix classes with cls or class. In fact the only commonly used type identifier as part of the type name is usually the I prefix for interfaces.
Method names in C# are usually PascalCase naming convention. camelCase is used for local variables.
Not entirely sure about the whole structure of your code but to me it looks like you should be able to easily move the code into a separate helper class like this:

public static class SpringHelper
{
    public static T GetNewPresenter<T>()
    {
        IApplicationContext ctx = ContextRegistry.GetContext();
        return (T)ctx.GetObject(typeof(T).Name.ToCamelCase());
    }
}

You would call it like this then:

SpringHelper.GetNewPresenter<ClsPresenter>();

If all your presenters have a base class your could also add a where clause to restrict the types.

This would at least remove the dependency out of the presenter class.


Multiplication of any two matrices using lists and for in loop

I have basically two comments:

Naming.
Use functions to follow the single responsibility principle.

Naming

Python has an official style-guide, PEP8. Some of its recommendations are:

Using lower_case for variables and functions, PascalCase for classes and ALL_CAPS for global constants.
To limit your line length to 80 (or at the most 120) characters

Your names which you use to iterate through the rows and columns are not clear at all. Why vc and vr (I guess the c and r stand for column and row, but what does the v stand for?)? Instead I would use rows and columns for the number of rows and columns and use i and j to iterate over them, because that is the convention used in mathematics when describing matrices.

Single responsibility principle

As for your actual code, you basically have four major responsibilities:

Asking the user for input
Creating a matrix
Calculating the matrix product
Printing a matrix scheme

I would make this into four functions:

def ask_user(message):
    while True:
        try:
            return int(input(message))
        except TypeError:
            pass

This function will ask the user the message until he inputs something that can be cast to an int.

def matrix_from_user():
    rows = ask_user("Number of rows?: ")
    columns = ask_user("Number of columns?: ")
    matrix = [[0] * columns for _ in range(rows)]
    for i in range(rows):
        for j in range(columns):
            matrix[i][j] = ask_user("M{}{}: ".format(i+1, j+1))
    return matrix

Here I used str.format to make the construction of the string easier.

def matrix_mul(matrix1, matrix2):
    rows, columns = len(matrix1), len(matrix2[0])
    matrix = [[0] * columns for _ in range(rows)]
    for i in range(rows):
        for j in range(columns):
            matrix[i][j] = sum(matrix1[i][k] * matrix2[k][j]
                               for k in range(len(matrix2)))
    return matrix

This is a straightforward implementation of the formula \$(AB)_{ij} = \sum_{k=1}^m A_{ik} B_{kj}\$ for two matrices \$A\$ and \$B\$. It uses the built-in sum function that takes an iterable to sum. This iterable is a generator comprehension here.

def matrix_print(matrix):
    print('\nElements of matrix:')
    rows, columns = len(matrix), len(matrix[0])
    for i in range(rows):
        row = ' '.join('M{}{}'.format(i + 1, j + 1) for j in range(columns))
        print('|', row, '|')

Here I used str.join to easily join an iterable of strings with a given delimiter (' ' here).

Your main program becomes then simply:

if __name__ == "__main__":
    matrix1 = matrix_from_user()
    matrix_print(matrix1)
    matrix2 = matrix_from_user()

    product = matrix_mul(matrix1, matrix2)

    print('Matrix1: ', matrix1)
    print('Matrix2: ', matrix2)
    print('Result of Matrix Multiplication:', product)

This code I put under an if __name__ == "__main__": guard which allows you to import this script from another script without this part of the code being run (so you get access to the functions).


function to append "a" or "an" to the front of a number as appropriate

Rather than having many return statements I would keep the logic that determines whether it should be 'a' or 'an' together.  I think it is actually easier to understand reading the ANDs and ORs than spread out if and else statements.

I prefer not to create temporary variables that are not used for anything - so I wouldn't create $verA and $verAn.  I do however create a variable for $numComma.  By having this we avoid calling number_format more than is necessary.

This is how it looks my way:

function prefixAAnToNumber($num)
{
    $prefixAn = array(8, 11, 18, '8', '11', '18');
    $numComma = number_format($num);

    if (in_array($num, $prefixAn) ||
    (strlen($num) > 1 &&
     (substr($numComma, 0, 1) == '8' ||
      (in_array(substr($numComma, 0, 2), $prefixAn) &&
       substr($numComma, 2, 1) == ','))))
    {
        return 'an ' . $numComma;
    }

    return 'a ' . $numComma;
}


Checking the balanced parenthesis as asked in interview

Returning mixed types.

return string.indexOf(stack.pop()) + 1;
return true;

This is a dangerous design for the interface, as it requires strict type checks in the calling code to distinguish between the error case (non-zero integer) and the success case (true boolean).

Stick to a single data type for the return value at all cost. This would have been quite easy in this case, as every error case yields a non-zero integer. So just returning 0 to signal error free execution would have been acceptable.

Not fulfilling the requirements

  if there are no unmatched closing brackets, output the 1-based index of the first unmatched opening bracket.

Said ahead, the "fix" suggested by @BrunaCosta doesn't work either.

The only way to reconstruct this information, is to record it when creating the stack. You can't identify the position correctly afterwards.

This shows that you lack understanding of what data you need to compute in order to solve the problem.

Proper testing

console.log(hashBalancedParanthesis('('));

This is by no means a unit test. A test is characterized by either failing or succeeding in a replicable way. Simply sending the output to console does neither, even less so when the expected value is only denoted as a comment in your code, making it impossible to run the tests automatically.

If you don't want to use a full testing framework, the least you could have done would have been to use the builtin assert() function to assert that each of your test cases either succeeds, or your test suite fails.

Your tests should not have been placed in the main file either. Even less so, when that means that they run on every inclusion of your library. And less again when they cause log spam without any good reason at that.

As pointed out by @BrunaCosta, your unit tests are also flawed in another way, as they don't test any non-trivial case.

Separation of concern

function hashBalancedParanthesis(string);

Your approach of separating the actual algorithm from the input/output handling was almost correct.

Except that you forgot to implement the latter part. You are neither capturing any input, nor are you creating any output. Except for the log spam resulting from placing your strange test cases into main file.

Providing a user interface of any sort is usually considered part of these challenges, even if it's just a console application which reads from stdin and outputs to stdout. Or in the case of JavaScript best a small HTML application.

Your comments are a lie

// False

The value False will never appear on the console.

Whenever you comment something - and you should if something isn't self-explanatory - you must take care to update the comments as well. A comment which is out of sync with the commented code is far worse than not having a comment at all.


Timer Tick Event only to execute at specific time

Here is another alternative...

private void tmrMain_Tick(object sender, EventArgs e)
{
    if (ShouldRunNow())
        PerformClick();
}

private void PerformClick()
{
    if (pnlAssembly.Visible)
        cmdShed.PerformClick();

    else if (pnlShed.Visible)
        cmdServices.PerformClick();

    else if (pnlWeb.Visible)
        cmdAssembly.PerformClick();
}

private bool ShouldRunNow()
{
    TimeSpan startTime = new TimeSpan(8, 0, 0);
    TimeSpan endTime = new TimeSpan(18, 0, 0);
    DateTime now = DateTime.Now;

    // Only run Saturday and Sunday
    if (now.DayOfWeek != DayOfWeek.Saturday && now.DayOfWeek != DayOfWeek.Sunday)
        return false;

    // Only run between the specified times.
    if (endTime == startTime )
        return true;

    if (endTime < startTime)
        return now.TimeOfDay <= endTime || now.TimeOfDay >= startTime;

    return now.TimeOfDay >= startTime && now.TimeOfDay <= endTime;
}

Couple notes:
I think this is what ANeves meant by "would also consider extracting to a method the logic of whether or not to do the actions" but not sure so I decided to show it.  By putting the entire decision tree in a method you have self documenting code (the "if (ShouldRunNow())" describes what you are trying to do without needing comments).

Eliminating "else" statements makes your code more readable (IMHO)

I personnally think using brackets when there is only one statement makes your code less readable as well.  Of course, this is my own opinion and I even have people at my workplace that disagree with this.  I will let the readers decide :)

Since the ShouldRunNow method is private then it doesn't hurt to not pass in the parameters.  And putting them directly in the method will make them easier to find.  This is not a big deal either way but just another alternative.

Update
Changed code based on feedback in comments


Compute the number of ways a given amount (cents) can be changed

I don't see any correctness issues, but it could be more idiomatic.

    if coin_index in memoized_sol:
        if rem_cents in memoized_sol[coin_index]:
            return memoized_sol[coin_index][rem_cents]
    else:
        memoized_sol[coin_index] = {}

Check out first defaultdict, and then functools.lru_cache for ways to simplify the memoisation - although note that lru_cache has a subtlety in that it doesn't like list as an argument type.

    if rem_cents == 0:
        return 1

    if coin_index >= len(coin_vals):
        return 0

IMO these should have gone before the memoisation code, because they are non-memoised special cases. But I freely admit that this is mainly a matter of opinion. The only real difference effected would be to avoid initialising memoized_sol[len(coin_vals)].

    i = 0
    count = 0
    while i*coin_val <= rem_cents:
        count = count + compute_coin_change_count\
            ( rem_cents - i*coin_val, coin_vals, coin_index+1, memoized_sol )
        i = i + 1

Using sum and range this could be simplified to

count = sum(compute_coin_change_count(
        surplus, coin_vals, coin_index + 1, memoized_sol)
    for surplus in range(rem_cents, -1, -coin_vals[coin_index]))

(I'm not quite sure what the most Pythonesque indentation would be - I wouldn't normally follow PEP8 on maximum line lengths).

I would also be tempted to use sublists and eliminate the need for coin_index, but that depends on how you're handling memoisation.

Putting it all together, I get

from functools import lru_cache

def get_coin_change_count(cents, coin_vals):
    @lru_cache(None)
    def inner(remaining, idx):
        if remaining == 0:
            return 1

        if idx == len(coin_vals):
            return 0

        return sum(inner(surplus, idx + 1)
                   for surplus in range(remaining, -1, -coin_vals[idx]))
    return inner(cents, 0)

print(get_coin_change_count(37, [10, 1, 5, 25]))

and here the indentation does pass PEP8, in part because of shorter names. Note that using an inner function allows memoisation with lru_cache and allows the short name inner because its scope is restricted enough that this is sufficiently expressive.


Singleton metaclass for each argument set compatible with Pickle

The point of having to define either neither or both of __init__ and __reduce_ex__ is to set _args.
However you can just set _args in __call__ and then use the one you've set in your __reduce_ex__.
Note: untested
class ArgumentSingleton(type):
    __INSTANCES = {}

    def __new__(cls, name, bases, class_dict):
        def __reduce_ex__(self, protocol):
            return partial(type(self), *self.__args, **self.__kwargs), ()

        def __init__(self, *args, **kwargs):
            pass

        class_dict.setdefault('__init__', __init__)
        class_dict.setdefault('__reduce_ex__', __reduce_ex__)
        return super().__new__(cls, name, bases, class_dict)

    def __call__(cls, *args, **kwargs):
        key = (cls, args, frozendict(kwargs))
        if None is (self := cls.__INSTANCES.get(key)):
            self = cls.__INSTANCES[key] = super().__call__(cls, *args, **kwargs)
            self.__args, self.__kwargs = key[1:]
        return self

Now we should be able to see we can just stop defining a metaclass by;

changing __call__ to __new__, and
defining a default __reduce_ex__ on the base class.

from frozendict import frozendict
from functools import partial

class Singleton:
    __INSTANCES = {}

    def __new__(cls, *args, **kwargs):
        key = (cls, args, frozendict(kwargs))
        if None is (self := cls.__INSTANCES.get(key)):
            self = cls.__INSTANCES[key] = super().__new__(cls)
            self.__args, self.__kwargs = key[1:]
        return self

    def __reduce_ex__(self, protocol: int):
        return partial(type(self), *self.__args, **self.__kwargs), ()

class A(Singleton):
    pass

# passes all your tests and the following one
a = A("hi")
b = pickle.loads(pickle.dumps(a))
assert a is b


Entity Framework with multiple connections open?

Just a quick note about the way exceptions are handled:

catch (Exception ex)
{
    throw new Exception("buildUpdatedAnswerDetailRecord Error Occured: " + ex.Message.ToString());
}

You're shooting yourself in the foot: you're receiving a potentially very meaningful and helpful exception, with a very detailed stack trace, then you're grabbing its message and throwing everything else away (including the stack trace), and throwing a meaningless System.Exception.

At the very least, you should be putting ex as the new exception's InnerException, so as to retain all the details about the exception that was thrown. See this answer for more details about why throwing System.Exception is bad.


at line if (lhs[a:c] == rhs[b:d]): parentheses are redundant
you don't need to return whole list, you can return only iterator (remove results variable, change line results.append((u, v, w, t)) into yield u, v, w, t). After it you can always use this as list if needed (list(get_additions(a, b))) but usually you need only iterator.
your variable i change from <1 - szr .. szl). You can use for i in xrange(1 - szr, szl): to do this
at your description i can read about conditions u + a + v == w + b + t and len(lhs) >= len(rhs). You can write it in your code as assert
at your description variables a, b means something else than in your code. It's not good idea. Your also use various conventions of variable naming (e.g. szr as size of right list and b as begining index of right list). You should define variables in the same way.
personally i often remove variables like szr because len() of list is quite fast. It's your choice (you get less local variables but more len() calls).
you always cut b[3:len(b)] into b[3:] and b[0:3] into b[:3]

After these changes your code could looks like

def get_additions(a, b):
    assert len(a) >= len(b)
    for i in xrange(1 - len(b), len(a)):
        a_left = max(0, i)
        b_left = max(0, -i)
        a_right = min(i + len(b), len(a))
        b_right = min(len(b), len(a) - i)

        if a[a_left:a_right] == b[b_left:b_right]:
            u = b[:b_left]
            v = b[b_right:]
            w = a[:a_left]
            t = a[a_right:]
            assert u + a + v == w + b + t
            yield u, v, w, t

if __name__ == "__main__":
    a = [1, 2, 5, 7, 6, 9, 1, 3, 1, 2, 6, 6, 3, 1, 2, 6, 1, 3]
    b = [3, 1, 2]
    for u, v, w, t in get_additions(a, b):
        print "u = %s, v = %s\nw = %s, t = %s\n" % (u, v, w, t)


Generate an ID number for each new row of text that is pasted into the worksheet

Creating an Unique ID Without Loops

The problem with incrementing the next ID based on the last cell in a column is you will have to sort the data to ensure that it is in ID order.  This really can take away from the user experience.    A better approach would be to use the WorksheetFunction.Max() to find the current max ID.

"I am very bad at loops"

You should start by watching these videos:

Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)
Excel VBA Introduction Part 15 - Do Until and Do While Loops
Excel VBA Introduction Part 15a - Find and FindNext
Excel VBA Introduction Part 16 - For Next Loops
Excel VBA Introduction Part 17 - For Each Loops

Notice that the first video teaches you how to define ranges.  Well,  If you are having problems with loops in Excel then chances are you are having problems defining the range to loop over.

The best advice that I can give you when you are having problems with a coding pattern is to practice it.  Printout a worksheet with several different types of loops and every morning choose a couple of the patterns and type them up several times until you can recite them from memory.  Another great way to practice is to start answering questions on Stackoverflow.com.  This will challenge you with unique situations that you would not normally see.  Your answers will get progressively better or time as you respond to the comments from other users.

Miscellaneous

TextBox1, TextBox2 TextBox3 ... ugh!!  In the time it takes you to the write comments to describe what each one does, you could have just gave them meaningful names.  I generally preface all my textboxes with txt like this txtShipFrom, txtShipTo, txtShipDate but simply using shipFrom, shipTo, shipDate also works.

Sheets("Arkiv") is used 6 times.  Using With  Sheets("Arkiv") will not only make you code easier to read, modify, and debug but is also more efficient (the compiler only has to resolve the reference 1 time).

Refactored code:

Sub AddNewShippingRow_Click()
    Dim inputs As Variant
    Dim ID As Long
    Dim nextRow As Range

    ID = getNextShippingID
    Set nextRow = getNextShippingRow

    inputs = Array(ID, shipFrom.Text, shipTo.Text, shipDate.Text, NP.Text, desc.Text, gramEx.Text, tareWeight.Text, Weight.Text, dims.Text)

    nextRow.Resize(UBound(inputs) + 1).Value = inputs
End Sub

Function getNextShippingRow() As Range
    With Sheets("Arkiv")
        Set getNextShippingRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1)
    End With
End Function

Function getNextShippingID() As Long
    With Sheets("Arkiv")
        getNextShippingID = WorksheetFunction.Max(.Range("A1", .Cells(.Rows.Count, 1).End(xlUp))) + 1
    End With
End Function

In my refactored code I simplified the main subroutine by using helper functions to perform some of the tasks.  The fewer tasks that a subroutine performs the easier it is to read, modify and debug.

For instance say that you wanted to change the way you create your ID's because we are using a helper function we can modify and test that function without have to run the larger block of code.

Here I modify and tested 4 different versions getNextShippingID() without having to make any changes to the main routine.  Of course, I would have to change the datatype of the main routines ID variable but that is not to after I completed my testing.

Function getNextShippingID() As Double
    getNextShippingID = CLng(Date) & (Timer * 100)
End Function

Function getNextShippingID() As Double
    Const StartDate As Date = #1/1/2019#
    getNextShippingID = CLng(Date - StartDate) & (Timer * 100)
End Function

Function getNextShippingID() As Double
    getNextShippingID = Format(Now, "ddmmyyhhmmssnn")
End Function

Function getNextShippingID() As String
    Dim s As String
    s = CreateObject("Scriptlet.TypeLib").GUID
    getNextShippingID = Mid(s, 2, Len(s) - 4)
End Function


Capture worksheet formulas in VBA format

First design problem is that you're outputting to the immediate pane, which isn't meant to hold data like this - it will only ever display up to 255 lines, which means as soon as your range has more than 250-some rows, your code stops being useful.

First code problem is that Option Explicit is missing, and you have undeclared variables:

MyQuestion (which is really an answer, since it's a vbMsgBoxResult) isn't declared.
CurrentRow isn't declared.

Then you have declared variables that aren't used anywhere:

MyRow isn't used.

You're not validating rng, so if the InputBox gets cancelled, you get a run-time error 424 "Object Required" and jump OuttaHere - which isn't too bad, except for the fact that getting valid user input is a concern in its own right, and really belongs in its own dedicated function.

    Set rng = SelectRangeToCapture
    If rng Is Nothing Then Exit Sub

'@Description "Prompts for a Range. Returns Nothing if no selection is made."
Private Function SelectRangeToCapture() As Range
    On Error Resume Next
    Set SelectRangeToCapture = Application.InputBox("Select range to capture", ": )", Type:=8)
    Err.Clear
    On Error GoTo 0
End Function

It doesn't feel right that you need to check MyQuestion for every single iteration of that loop - the value is the same every time, you're wasting cycles here. MyQuestion should be named fillToLastRow and be a Boolean:

fillToLastRow = MsgBox(...) = vbYes

And then the LastRow assignment can be a simple IIf function result:

LastRow = IIf(fillToLastRow, "LastRow", CStr(currentRow))

Note the explicit type conversion for currentRow, from Long to String.

The generated code needs to be indented and properly spaced. Lack of whitespace between operators and operands can easily turn into compile errors, because of how VBA interprets type hints - not necessarily here in this code, but lack of whitespace turning & concatenation operator into a & type hint on a variable or literal value is a quite recurrent, easily avoided question on Stack Overflow.

The LastRow logic assumes column A contains data: the reference column should be based on rng instead.

I'm also a bit puzzled about why you would want to use R1C1 notation in the formulas, but maybe it's just because I never needed to use it in 15 years.

Why not go all the way, reference the VBIDE type library and actually output your generated code to an actual procedure, in an actual module? That way you wouldn't be limited to 255 lines. Although.. I wonder if that's a good idea, given VBA won't even compile a procedure that's more than 10,000 lines, or a module with more than 65,535 lines - in other words, rng.Count needs to be capped and validated, otherwise you either lose data, or generate code that can't even compile.

In general I don't like VBA code that requires frequent modifications. Code should be written to resist change - yours embraces change with arms wide open, pretty much as part of its own specification, including instructions-in-comments.

Speaking of comments... Comments should say why, not what. These comments say nothing that the code doesn't already say:

'error handling
On Error GoTo OuttaHere

'select range
Set rng = Application.InputBox("Select range to capture", ": )", Type:=8)

'set worksheet string
ws = "Activesheet"

One last note about naming: OuttaHere isn't normally a label you'd find in professionally-written code. CleanExit would be more appropriate. MyXxxxx identifiers are annoying, too: such names don't convey much information, other than a vague data type that belongs to something (or someone?). Take the time to name things, meaningfully.

MyRange holds an assignment instruction, not a Range.
MyFormula holds the Excel formula in the current cell.
MyString holds a VBA instruction.

And so on.


f-strings

Beginning with Python 3.6, there is a friendlier way of formatting strings. Instead of using "format string" % (tuple_of_args) where the argument and the format codes are separated by significant distance, the arguments are embedded in the string itself, surrounded by {}'s.  The string itself is prefixed with an f.

For example, instead of:

    print("\n***   Round: %d   ***\n" %(self.round))

you can write:

    print(f"\n***   Round: {self.round}   ***\n")

Enumerations

This code doesn't convey a lot of meaning by itself.  It needs to be described by your 7 comment lines.

    decisionArray = [[False, True, True], [True, False, True], [True, True, False]]

Some of the problem stems from indices having semantic meaning.  For example, 1 is Magic.  But 1 is also Spell.  Confusing.

Let's make what is happening a lot clearer.  Let's define enumerations for our weapons and shields:

from enum import Enum

Weapon = Enum("Weapon", "Sword, Spell, Fire")
Shield = Enum("Shield", "Armour, Magic, Water")

Now we have Weapon.Sword, Weapon.Spell, and Weapon.Fire, which conveniently have values 1, 2 and 3 respectively.  We also have Shield.Armour, Shield.Magic and Shield.Water, also with values 1, 2, and 3.

When we have our player select their choice of weapon, we use to store it as the number 0, 1 or 2:

    self.weapon = choice - 1

but now we can store an actual enumeration object, like Weapon.Fire directly.  Conveniently, passing the value 1, 2, or 3 to Weapon(...) will return the corresponding enumeration object:

    self.weapon = Weapon(choice)

Similarly, we can store our shield choice as a Shield enumeration object:

    self.shield = Shield(choice)

The AI is similar, but instead of randint, we can use choice and select a random Weapon and random Shield:

    self.weapon = random.choice(list(Weapon))
    self.shield = random.choice(list(Shield))

But how about that decisionArray?  First of all, that is a lousy name.  What does "decision array" mean?  A Shield will block one (or perhaps more) Weapon attacks.  Let's add a .blocks attribute to our Shield objects:

Shield.Armour.blocks = { Weapon.Sword }
Shield.Magic.blocks = { Weapon.Spell }
Shield.Water.blocks = { Weapon.Fire }

(I'm using a set(), so more that one Weapon can be added.  For example, Shield.Magic could block both { Weapon.Spell, Weapon.Fire } ... after all, it's MAGIC!  Feel free to experiment.)

What would the takeTurn method now look like?

def takeTurn(self, player, opponent):

    if player.weapon not in opponent.shield.blocks:
        # apply damage
    else:
        # damage was blocked

That's pretty straight forward; no table required.  If the weapon is not in the set of things the shield blocks, we apply damage.

PEP-8

PEP 8 is a Style Guide for Python.  It describes things all Python programs should conform to, such as:

variables and function names should be snake_case not mixedCase.

Updated Code

import random
from enum import Enum

Weapon = Enum("Weapon", "Sword, Spell, Fire")
Shield = Enum("Shield", "Armour, Magic, Water")

Shield.Armour.blocks = { Weapon.Sword }
Shield.Magic.blocks = { Weapon.Spell }
Shield.Water.blocks = { Weapon.Fire }

class Player:
    def __init__(self, name):
        self.name = name
        self.health = 100
        self.weapon = None
        self.shield = None

    def damage(self):
        points = random.randint(10, 35)
        self.health -= points

    def select_weapon(self):
        weapons = [f"{weapon.value}-{weapon.name}" for weapon in Weapon]
        weapons = ", ".join(weapons[:-1]) + " or " + weapons[-1]
        choice = int(input(f"Choose your weapon {weapons}:  "))
        self.weapon = Weapon(choice)

    def select_shield(self):
        shields = [f"{shield.value}-{shield.name}" for shield in Shield]
        shields = ", ".join(shields[:-1]) + " or " + shields[-1]
        choice = int(input(f"Choose your shield {shields}:  "))
        self.shield = Shield(choice)

class AiPlayer(Player):

    def select_weapon(self):
        self.weapon = random.choice(list(Weapon))

    def select_shield(self):
        self.shield = random.choice(list(Shield))

class Game:
    def __init__(self):
        self.game_over = False
        self.round = 0

    def new_round(self):
        self.round += 1
        print(f"\n***   Round: {self.round}   ***\n")

    # Check if either or both Players is below zero health
    def check_win(self, player, opponent):
        if player.health < 1 and opponent.health > 0:
            self.game_over = True
            print("You Lose")
        elif opponent.health < 1 and player.health > 0:
            self.game_over = True
            print("You Win")
        elif player.health < 1 and ai.health < 1:
            self.game_over = True
            print("*** Draw ***")

    def display_result(self, player, opponent):
            print(f"{player.name} used a {player.weapon.name}, {opponent.name} used a {opponent.shield.name} Shield\n")
            print(f"{player.name} caused damage to {opponent.name}\n")

    def take_turn(self, player, opponent):

        if player.weapon not in opponent.shield.blocks:
            opponent.damage()
            current_game.display_result(player, opponent)
        else:
            print(f"{player.name} used a {player.weapon.name}, {opponent.name} used a {opponent.shield.name} Shield\n")
            print(f"{opponent.name} blocked {player.name}'s attack - No Damage")

# Setup Game Objects
current_game = Game()
human = Player("Mark")
ai = AiPlayer("Computer")

players = [human, ai]

# Main Game Loop
while not current_game.game_over:
    for player in players:
        player.select_weapon()
        player.select_shield()
    current_game.new_round()
    current_game.take_turn(human, ai)
    current_game.take_turn(ai, human)
    print(f"{human.name}'s health = {human.health}")
    print(f"{ai.name}'s health = {ai.health}")
    current_game.check_win(human, ai)

Notice in this code, if you added additional weapons and/or shields, nothing need be changed other than the Enum(...) declarations and the .blocks = {} lines.  The code itself creates the "1-Armour, 2-Magic or 3-Water" type choice strings, and will properly work with more than 3 choices.


Thread safe log class which creates log files according to the current date when entry was added

static readonly object _syncObject = new object();

You should always add a scope identifier because it increases readability.

var todaysLogFilePath = Path.Combine(ConfigManager.GetAppSetting("logPath"),
                                        ("Log" + DateTime.Now.ToString("yyyy-MMMM-dd") + ".txt"));
Log(logMessage, todaysLogFilePath);

Each time the Write() method is called you are

reading from the config to get the logging path
construct a new filepath

I know why you are doing this, but it could be done in a better way. You could add a field

private static DateTime currentDate = DateTime.Now.Date;

so it is initialized at startup.

Next you could add a field

private string logFilePath;

and a method ComposeLogFilePath(DateTime) like so

private static string ComposeLogFilePath(DateTime date)
{
    return Path.Combine(ConfigManager.GetAppSetting("logPath"),
                             ("Log" + date.ToString("yyyy-MMMM-dd") + ".txt"));
}

which you then call from this constructor

static Logger()
{
    logFilePath = ComposeLogFilePath(currentDate);
}

By adding a method which checks if a change in the date has happened and if a new logFilePath needs to be composed like so

private static void CheckLogFileAndCreateIfNeeded()
{
    if (currentDate >= DateTime.Now.Date) { return; }

    currentDate = DateTime.Now.Date;
    logFilePath = ComposeLogFilePath(currentDate);
}

The method name is not the best, maybe you or some answerer will come up with a better one.

So each time the Write() method is called you call this method like so

public static void Write(string logMessage)
{
    try
    {
        CheckLogFileAndCreateIfNeeded();

        Log(logMessage, logFilePath);
    }
    catch (IOException e)
    {
        //log somewhere else if required
    }
}

which leads to the next point: Usually a Logger will log something so better change the names Write()-> Log() and Log() -> Write().

static void Log(string logMessage, string logFilePath)
{
    lock (_syncObject)
    {
        File.AppendAllText(logFilePath,
                    string.Format("{0} {1} {2}",
                    DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), logMessage));
    }
}

Here you should store DateTime.Now inside a variable to have the calls ToLongTimeString() and ToLongTimeString() using the same DateTime like so

static void Log(string logMessage, string logFilePath)
{
    lock (_syncObject)
    {
        DateTime date = DateTime.Now;
        File.AppendAllText(logFilePath,
                    string.Format("{0} {1} {2}",
                    date.ToLongTimeString(), date.ToLongDateString(), logMessage));
    }
}

Threadsafety is no issue here because of the lock but you could do this in a much better way by having a ConcurrentQueue in which you store the formatted message to log.

Then add a method to query the queue which ideally should spawn a thread to do the work. If there is already a thread running, you can just return from this method. If there is no thread running, start it and return.

By using a ConcurrentQueue you could get rid of the lock and you wouldn't need for each message to open the file.


Given a list of words, find the most common initial character and other statistics

Here are things I see:

Old Headers

#include<iostream.h>

iostream.h should be replaced with the modern day iostream. You can also consider replacing string.h with cstring. When you do this, you have to prefix all functions/classes from the standard library with std::. using namespace std; may seem shorter, but it is best avoided.

Indentation

int main()
{
int i,n,len=0,sum=0,j,max,min,c=0,c2=0,k=0;

You don't seem to have any sort of indentation set up in your main function. Pick some length, such as 4 spaces or a tab, and use it consistently. Indentation makes code easier to read.

Waaaaaaay too many variables in one place

int i,n,len=0,sum=0,j,max,min,c=0,c2=0,k=0;
int maxo=0,len1,maxi=0,c1=0,len2,counter=0,maxo1=0,len3;

This honestly looks horrible at first glance. Declaring variables at the beginning of a function is not something C++ requires. I suggest you move all of these variables close to where they are used, and use initialization instead of separate declaration and definition. For example:

len=strlen(list[i]);

Can be replaced with:

std::size_t len=strlen(list[i]);

Usage of C Style Multidimensional Arrays

char list[100][100] = { 0 };

C style multidimensional arrays are error prone, don't know their own size, and can easily decay to pointers. As such, they are best avoided. Consider using a std::arrays of std::strings, which are more versatile and less error prone.

Usage of C Style Strings

char vow[] = "AEIOUaeiou";

If you are using C++, then why are you using C style strings? Switch over to the much better std::string.

NEVER use gets

gets(list[i]);

This Stack Overflow answer tells you all you need to know. When you start using std::string, then use getline to read in a string.

Don't use endl unless you want to flush the output

... << endl;

Most people don't know when starting C++ that endl unnecessarily flushes the output. Switch over to \n.

Don't use strlen as a loop condition

for (j = 0; j < strlen(vow); j++)

Unless your compiler knows to optimize this out, strlen might be called every iteration in this code. To avoid this, put the length in its own variable.

Better Variable Names

Variable names such as i and c should only be reserved for loop indices. Use better variable names that clarify your intent.

fflush(stdin)

fflush(stdin)

https://stackoverflow.com/a/18170435/6525260. Don't play with undefined behavior.

getchar

In C++, a better way to wait for a character is:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');


It isn't a good solution and there are several reasons.

1.: Your values are less precise than what the double data type allows for. For example,

1.0 / Math.Pow(2, 12)

computes to 0.000244140625, while your lookup value is just 0.000244141. Depending on the following calculations, this can make quite a big difference.

2.: Your array is public and mutable. While the array reference is readonly (so you can't assign a new array to the reference), the array itself is not. For example

RegionSizes[2] = 5;

compiles and runs without any problems. You (or every other dev) can override values in the array as he desires. Better use an immutable collection, like ReadOnlyCollection<double>, to prevent your cached values from manipulation during runtime. (If this is a little fun-project with you as the only dev this might not become a problem; in bigger projects with >1 dev this type of oversight can lead to hard-to-track bugs.)

3.: Experience tells that assumptions like

  I won't be computing this value for N > 15

do not always hold true. To be sure, a more flexible approach (like calculating every value once it's first needed, then store it and use it when needed again) would allow for more flexibility. Of course, without any information about what you intend to do in your program it's hard to tell if this is relevant.

4.: I strongly suspect you are doing premature optimizations (because you mention neither actual performance problems, nor any measurements indicating that floting-point operations are the cause for such problems). Donald Knuth said

  The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.

and I have nothing to add. From my experience, in >95% of all software projects you don't need to worry about the performance of >95% of your code. So when making an optimization, you should follow these steps:

Set a realistic measurable performance goal. This is important, you can optimize code forever, so you have to have some definition of 'good enough' and stop once your code is good enough.
Measure if there is an actual performance problem (by comparing actual performance to your definition of 'good enough').
Identify the parts of your code that cause the performance problem; that involves measuring again. For example measure how much time the program spends in each method, then measure how much time the operations in the slow methods take. Do this until you know for sure what makes your program run slow.
Optimize the code that you found out to be slow in step 3 and measure again, to make sure your optimizations are making your code run faster (it's suprising how many 'optimizations' actually make things worse).
Go back to 2.

Yes, I know, optimizing code is fun - but you can quickly get lost and spend hundreds of hours optimizing code that never needed any optimization.


Did anybody encounter such a use case before, and found a better way to solve it?

There's the IEnumerable pattern:

public interface IValidation
{
    bool IsValid(object obj);
}

public interface IValidation<T> : IValidation
{
    bool IsValid(T t);
}

public abstract class BaseValidation<T> : IValidation<T>
{
    public bool IsValid(object obj)
    {
        return IsValid((T)obj);
    }

    public abstract bool IsValid(T t);
}

Whether it's better or not is debatable, but it should at least be familiar to anyone who has to maintain your code.


I think that implementations of TeamRole should not know how to do things.

Based on the name part: ...Role it should only know if a certain user can perform a certain action on a particular resource.

I'm expecting the TeamRole to have a method like:

public interface TeamRole {
    boolean canDelete(Entry entry);
}

And then change the TeamMember:

public class TeamMember implements TeamRole {
    // need the user to be a part of the class here
    AbstractUser user;
    public TeamMember(AbstractUser user) {
        this.user = user;
    }

    @Override
    public boolean canDelete(Entry entry) {
        if (entry == null) return false;
        return user.getUid().equals(entry.getCreator().getUid());
    }
}

You can have an alternative with a static method in TeamMember, so you can avoid the instantiation of the class, and just pass the user (requester) as a parameter:

public interface TeamRole {
    // Java 8+
    static boolean canDelete(AbstractUser requester, Entry entry);
}

So your service method will become:

public static ResponseEntity<Team> deleteEntry(AbstractUser requester, Team team, Entry e) {
    TeamRole role = team.findPermissionsForUser(requester);
    if (role == null)
         return new ResponseEntity("no role found...", HttpStatus.INTERNAL_SERVER_ERROR);

    if (role.canDelete(entry)) {
        try {
            team.delete(e);
            return new ResponseEntity(team, HttpStatus.OK);
        } catch (Exception error) {
            // here you have an actual error to report to
            // the user, as something that should be done
            // failed.
            return new ResponseEntity(error.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    // So you can say to the user that nothing is wrong
    // with the request there is just a permission
    // issue here.
    return new ResponseEntity("user cannot delete entity", HttpStatus.METHOD_NOT_ALLOWED);
}

Profiling users is always an hard job, and each implementation should deal with the system requirements.

A good design should try to separate as much as possible the authorization part of the logic from the business part.

Authorization, like authentication and accounting should be aspect that can be changed in you system without adding any issue on the business logic.

Please have a look at Spring Security.

I don't mean you should use it, but I think could be a good inspiration on how things could be done cleaner.

Now a couple of things I noticed on your code.

The deleteEnytry method of TeamRole return a boolean, but this is always true!

So why returning such a value?

In this case just put void as the return value.

Have void as a return value from command method is considered a best practice. Of course is not mandatory and don't cover all the case, it is just usual that a coomand should not return something.

In your EntryService you have a NullPointerException:

public class EntryService {
    public static ResponseEntity<Team> deleteEntry(AbstractUser requester, Team team, Entry e) {
        try {
            // NullPointer here!
            team.findPermissionsForUser(requester)
                .deleteEntry(requester, team, e);
            return new ResponseEntity(team, HttpStatus.OK);
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
            return new ResponseEntity(e1.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

the team.findPermissionsForUser(requester) didn't return always a value, as it returns just the value found in the Map, that is an actual TeamRole or null if no entry was found in the map.

And as you catch just the IllegalAccessException you will got an error that could be complicated to debug.


Optimize 950k+ lookups in pandas dataframe

You can use DataFrame#merge.
df = transactions.merge(users, on="email")


Create path to file under 64-bit %programfiles% from 32-bit process

In the end, I made a slight simplification and ended up with:

System.Environment.ExpandEnvironmentVariables("%systemdrive%\Program Files\...")


Calculate average of array of objects per key value using reduce

Here is possibly an even more functional programming style solution, which makes use of a temporary ES6 Map object. This has the advantage over a plain object: you can turn it into an array of pairs, and chain on that to get the final result:

var data = [
    {tv: 1, radio:5, fridge:4},
    {tv: 2, radio:2, fridge:null},
    {tv: 3, radio:6, fridge:5}
];

var avg = Array.from(data.reduce(
        (acc, obj) => Object.keys(obj).reduce(
            (acc, key) => typeof obj[key] == "number"
                ? acc.set(key, (acc.get(key) || []).concat(obj[key]))
                : acc,
        acc),
    new Map()),
        ([name, values]) =>
            ({ name, average: values.reduce( (a,b) => a+b ) / values.length })
    );

console.log(avg);

Instead of immediately summing up the values, this code first collects the different values into an array per property, in a Map, then it calculates the averages from those arrays, turning it into the desired target structure.

Alternative output structure

Personally I find it more logical to produce output that has the same structure as the input objects, so I provide this very similar alternative. Only the final map is replaced by a reduce:

var data = [
    {tv: 1, radio:5, fridge:4},
    {tv: 2, radio:2, fridge:null},
    {tv: 3, radio:6, fridge:5}
];

var avg = Array.from(data.reduce(
        (acc, obj) => Object.keys(obj).reduce(
            (acc, key) => typeof obj[key] == "number"
                ? acc.set(key, (acc.get(key) || []).concat(obj[key]))
                : acc,
        acc),
    new Map())).reduce(
        (acc, [name, values]) =>
            Object.assign(acc, { [name]: values.reduce( (a,b) => a+b ) / values.length }),
        {}
    );

console.log(avg);

Performance improvement

As you asked in comments about performance, I tried to improve on it, without giving up on functional programming.

I took my first code version (which will be more performant than the second), and changed the first half of the algorithm: the numbers are now summed up immediately, keeping a count next to it. For this I introduced an immediately invoked (arrow) function:

var data = [
    {tv: 1, radio:5, fridge:4},
    {tv: 2, radio:2, fridge:null},
    {tv: 3, radio:6, fridge:5}
];

var avg = Array.from(data.reduce(
        (acc, obj) => Object.keys(obj).reduce(
            (acc, key) => typeof obj[key] == "number"
                ? acc.set(key, ( // immediately invoked function:
                        ([sum, count]) => [sum+obj[key], count+1]
                    )(acc.get(key) || [0, 0])) // pass previous value
                : acc,
        acc),
    new Map()),
        ([name, [sum, count]]) => ({ name, average: sum/count })
    );

console.log(avg);

This stays within the functional programming rules, but I expect better performance than the first two versions I posted.


Just a few random comments:

Both elemAt and maximumBy give hints that you're expecting to operate on non-empty structures. Maybe give Data.List.NonEmpty a try.
A few places could be more clear with more pattern matching. E.g. max (k1, v1) k2 v2 instead of max acc k v. Or (maxDelta, splitter) = maximumBy …
map snd is more conventional than snd . unzip. I suspect it would be more efficient too but I might be wrong.
In several places you're traversing the same list multiple times. In general, it's better to avoid this as it's likely to force the spine of the (potentially large) list in memory. You might be able to merge these multiple traversals into one (e.g. using the foldl package). More likely, you should simply use vector.
In giniDelta you could use Data.List.partition to construct left and right.
Apply top-down ordering in your where-clauses. E.g. in train, majority should come first as it is the declaration that is referenced from the main function body.

EDIT: All in all I think readability is actually pretty good!


Welcome on Code Review

Generalities

Includes

You don't need #include <stdlib.h> in linkedlist.h, so remove it and instead, just add it in linkedlist.c  right after #include linkedlist.h.

Name collisions

I'll discuss no more this subject after but be aware that names like node, list, size or clear for example, are very usual and subject to collisions. Consider using more robust names, maybe with a prefix.

Usable interface

Since the user look at your header file to know how to use your functions, a good habit is to to name the arguments, that's make the interface more explicit. Furthermore, adding documentation as comments about your interface help them to use it correctly.

Use the const keyword

Read this and this to know when et how.

Assertions and error-checking

You could use assertions to check preconditions, postconditions and invariants. It make your code more explicit and you avoid possibly broke you code when modifying.

How to use assertions in C
How and When to Use C's assert() Macro
Why should I use asserts? (for C++ but still applicable)

struct node

[typedef] struct [tag] { ... } [alias];

Personally, I try to avoid to use sames ''struct tag'' and ''typedef name'' if I have to typedef a struct. It's completely a matter of taste, since "modern" compilers (for more than 20 years)  can handle this easily, but so, user know when he work with the tag or the alias.

But there are many others "conventions":

Some prefer "untagged aliased struct" (if there are no self-referencing members).
Where others says to never typedef a struct.
...

Consistency

No matter where you place asterisk for pointers, try to be consistent through your code:

void* data;
    ^ LEFT-ALIGNED
struct node *next;
            ^ RIGHT-ALIGNED

(here is another talk on this endless debate)

So IMHO, this is cleaner:

typedef struct node node_t;
typedef node_t* node_ptr;

struct node {
    void* data;
    node_ptr next;
    node_ptr prev;
};

struct List

Consistency

The first letter of the struct node is lowercase, while the first of the struct List is uppercase.

Variables declaration

Try to don't declare several variables on the same line, it will avoid you many problems.

typedef struct list list_t;
typedef list_t* list_ptr;

struct list {
    node_ptr head;
    node_ptr tail;
};

init_list(), push_back(), push_front()

There's no need to cast the return type of malloc from void* since it's implicitly converted to any pointer type.
You can also omit the struct  as you aliases it.
Optionally, you could make more concise using calloc and rid of the manual initialization of next and prev (with few costs).
Since you have a free_list function, consider renaming init_list to  alloc_list
For push_* function, you should use sizeof *list->head  instead of using the type. It's easier to maintain. (e.g. if you modify the node type latter, the change here is automatic)
For push_* function, you could return an int, an enum or a bool (via <stdbool.h>)  to indicate the success of the insert (since the malloc can fail) or a pointer to the new created node (and so NULL in case of fail). No matter how but you should always handle errors when using malloc

pop_back(), pop_front()

I find multiples assignments on same line less readable, but that's my opinion.
For info: On some not-wide-used platforms (PalmOS, 3BSD, and other non ANSI-C compatibles), you should check for NULL before freeing to avoid crashes.

clear()

You could rewrite the cleaning algorithm to be more efficient since you discard return values.

free_list()

Simply use clear before freeing, to avoid code duplication.


As a quick first note ( I will add more later when I have time), I assume the first lines;

   if (running) {
            return;
   }
   running = true;

are attempting to ensure that this code will only be running once at a time... You would have to use a lock to ensure this as currently a race condition could cause;

1.) A thread checks running is false

2.) A second thread checks this before the first sets it to true

3.) Both threads continue

This is probably not what you want to happen....

Regarding your question about the InterruptedException, you should NOT just swallow it. I suggest reading the following article which covers the reasoning behind this: http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

You also seem to swallow Exceptions else where in the code (Once the base Exception class and not a subclass). This is a very bad habbit and you should consider which exceptions could happen and what that would imply for your code, then deal with them explicitly.


class dl_error : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;
};

Given the purpose of this class, it seems logical to have it get the most recent error automatically. Especially since there is a gotcha involved, where dlerror() will return NULL if called a second time (so if some coder checks dlerror() to print or log the error message, and then does dl_error{::dlerror()}… boom). Plus it just makes it so much easier to use: throw dl_error{}; is just so much more ergonomic than throw dl_error{::dlerror()};.
Also, given that this class is already in namespace dl, it seems superfluous to have a prefix. dl::error is much nicer than dl::dl_error.
class serpath

Eh, I mean, is it really that much more painful to type out search_path (or search_path_info, given that it’s actually a path and some (in theory) flags)?
If you’re doing a thin wrapper around a C library, then it’s okay to recreate the C library’s shitty names. But that doesn’t look like what you’re doing, so why not use human-readable names? For someone whose first language isn’t English, the following is damn-near illegible:
auto const paths = dl::serinfo{dlhandle};

auto const path = paths.serpath(paths.cnt() - 1);

Compare that to:
auto const paths = dl::get_search_paths_for(dlhandle);

auto const path = paths[paths.size() - 1];

Every semi-competent C++ programmer will understand what size() and operator[] mean, and the function name is pretty much self-documenting. Meanwhile, ser isn’t even short for search (“serch” path?), and cnt just sounds rude.
Coders shouldn’t need to keep a translation guide open at hand to be able to read code, stopping every two lines to translate dl_serinfopathxyzagiuasgtha to something human-legible. 90% of the verbiage in good C++ code disappears into auto and the like anyway (and the fact that you need way fewer function calls than in C code), so take advantage of that and spell things out clearly.
class serpath {
    // ... [snip] ...

    std::string_view name_;

This is extremely unwise. I get that you’re trying to avoid unnecessary allocations, and you assume that the string name_ references will be owned by a serinfo object which will outlive the serpath object. But there’s nothing in the interface of either class that suggests that, let alone requires it. What’s to stop someone from doing:
auto get_particular_library_search_path(void* dlhandle)
{
    auto const info = dl::serinfo{dlhandle};

    for (auto i = 0u; i < info.cnt(); ++i)
    {
        auto const sp = info.serpath(i);

        if (satisfies_some_condition(sp))
            return sp;
    }

    throw std::runtime_error{"not found"};
}

If you’re going to keep this interface, then it might be wise to use a shared_ptr rather than a unique_ptr in serinfo, and pass a copy of that to every serpath you create. Copying shared_ptr is cheap (it’s actually destroying shared pointers that is fairly costly, but not really that much). That way, even if the original serinfo is destroyed, the serpaths won’t dangle.
Alternately, perhaps, you could make serpath non-copyable and non-movable, then create an array of them at construction time, and return references to them. Or, even simpler, just return a reference to the Dl_serpath struct directly. Because why not? All you’re doing with serpath is converting the char* to a string_view… and you don’t really gain all that much by that. (In fact, you lose info, because it’s very likely the user might want to use the returned path(s) with some system call or other, but you can’t use string_view because it isn’t NUL-terminated. You’d need to convert the string_view to a string to do pretty much anything useful with it anyway.)
Frankly, I’d just use a string (or possibly a std::filesystem::path!) in serpath, and all of this risk and hassle vanishes. Yeah, sure, you’re paying for the cost of a string allocation… but compared to all the costs involved in the allocation for serinfo, all those system calls, and so on… meh. The safety and ease of use is so much more worth it compared to avoiding a single, likely small allocation on what is certainly never going to be a hot path.
class serpath {

    // ... [snip] ...

    std::string_view name_;
    unsigned int flags_;

    // ... [snip] ...

public:
    std::string_view name() const { return name_; }
    unsigned int flags() const { return flags_; }

Are getters really necessary? Why couldn’t you just do:
class serpath
{
    friend class serinfo;

    explicit serpath(::Dl_serpath path)
        : name(path.dls_name)
        , flags(path.dls_flags)
    {}

public:
    std::string name; // perhaps better: std::filesystem::path path;
    unsigned int flags;
};

There doesn’t seem to be any gain from using getter functions for this simple return-value struct.
class serinfo

The thing that strikes me most about this class is that it’s actually a container of serpaths. All of the gymnastics you do in the constructor is really just to get that array of Dl_serpath, then dole it out safely. In theory, the class could be this:
class serinfo
{
    std::vector<serpath> _paths; // assuming serpath uses string, not string_view

public:

    explicit serinfo(void* dlhandle)
    {
        // everything the same as your current constructor, except `bytes` is
        // a local variable

        // then:

        _paths.reserve(bytes->dls_cnt);
        for (auto i = 0u; i < bytes->dls_cnt; ++i)
            _paths.push_back(serpath{bytes->dls_serpath[i]});
    }

    auto size() const noexcept { return _paths.size(); }

    // same for all the other useful const vector functions:
    // begin, end, operator[], etc.
};

I’m not suggesting it should be like this; there’s no point in allocating the Dl_serinfo structure, then just duplicating that allocation in the vector to copy all the data over. I’m just illustrating that it could be like this to make the point that serinfo is basically an immutable container of serpaths… so its interface should reflect that.
If you did implement a container interface, you could do stuff like:
// printing all the search paths
for (auto const& [path, _] : dl::get_search_paths_for(dlhandle))
    std::cout << path << '\n';

Note that you don’t need the entire container interface. All you need are const versions of begin(), end(), size(), and maybe empty(). If you wanted, you could add operator[] for convenience, but that’s pretty much it.
bytes = std::make_unique<std::byte[]>(size.dls_size);

This might work… if alignof(::Dl_serinfo) >= __STDCPP_DEFAULT_NEW_ALIGNMENT__.
See, std::malloc() always allocates with alignment alignof(std::max_align_t). Presumably ::Dl_serinfo doesn’t have any special alignment requirements (you don’t need to use std::aligned_alloc() to allocate it), so std::malloc() will never allocate under-aligned memory for ::Dl_serinfo, though it may allocate over-aligned memory, but that’s not a problem (other than a tiny amount of wasted memory, I suppose).
But new uses __STDCPP_DEFAULT_NEW_ALIGNMENT__… which may be more or less than alignof(std::max_align_t). If you did new ::Dl_serinfo directly, there would be no problem; if alignof(::Dl_serinfo) > __STDCPP_DEFAULT_NEW_ALIGNMENT__, then new would automatically fix the alignment for you.
But you’re doing new std::byte[sizeof(::Dl_serinfo)] (basically). You’re not allocating a ::Dl_serinfo, you’re allocating bytes (which have an alignment of 1, though new will naturally use __STDCPP_DEFAULT_NEW_ALIGNMENT__). So you need to be sure that the memory is properly aligned.
You could just use a static assert like:
static_assert(__STDCPP_DEFAULT_NEW_ALIGNMENT__ >= alignof(::Dl_serinfo));

That will just kill the compilation if there is a danger of alignment problems.
A better solution is to make sure the alignment is correct:
// in constructor:
constexpr auto alignment = std::align_val_t{alignof(::Dl_serinfo)};

bytes.reset(new (alignment) std::byte[size.dls_size]);
// note: can't use make_unique(), but doesn’t really matter

All the calls to ::dlinfo() look like this:
if (::dlinfo(/*...*/)) {
    throw dl_error(::dlerror());
}

For starters, I think you should make the error class more ergonomic:
if (::dlinfo(/*...*/)) {
    throw error{};
}

But also, simply converting the result of the ::dlinfo() call to bool doesn’t really give the best sense of what is actually going on here. I have no way of knowing whether maybe ::dlinfo() actually returns bool or something, or who knows what else, or what it means. You should generally not add redundant != or == to conditions… but the guideline is actually more subtle; it says adding redundant tests is unwise when there are only two meaningful values (like a valid pointer value and nullptr). With integers, there are often several meaningful values. It would be more clear to explain that you’re explicitly testing for “not zero” like this:
if (::dlinfo(/*...*/) != 0) {
    throw error{};
}

When I read that, even without looking up the ::dlinfo() API, I immediately understand, okay, this function returns zero on success.
One final thing: I’m not a fan of constructors that do more than just construct objects. serinfo’s constructor is more than just a constructor of serinfo objects. It’s actually doing a series of queries first, and then using the results to construct the object. That’s a violation of the single-responsibility principle.
Besides, you’re “doing a thing”… not “making a thing”. You’re “getting the search paths for a shared object”… you’re not “making a serinfo object”. The latter only happens as a side-effect of the former, but it’s not really the serinfo object you want… it’s the paths.
“Doing a thing” usually means you want a function, not a constructor. I think that’s especially important when you’re doing a thing that might fail, because then you can give the user the option of avoiding exceptions in cases where they can’t afford them. In other words, you could do:
class serinfo
{
private:
    explicit serinfo(std::unique_ptr<std::byte[]> data) :
        _data{std::move(data)}
    {}

    std::unique_ptr<std::byte[]> _data;

    friend auto get_search_paths_for(handle h) -> expected<serinfo>;

    // ... [snip] ...
};

// using something similar to the proposed std::expected:
auto get_search_paths_for(handle h) -> expected<serinfo>
{
    auto size = ::Dl_serinfo{};

    if (::dlinfo(h, RTLD_DI_SERINFOSIZE, &size) != 0)
        return make_unexpected(dl_error{});

    auto buffer = std::unique_ptr<std::byte[]>{};
    try
    {
        auto p = new (std::align_val_t{alignof(::Dl_serinfo)}) std::byte[size.dls_size];

        buffer.reset(p);
    }
    catch (...)
    {
        return make_unexpected(std::current_exception());
    }

    if (::dlinfo(h, RTLD_DI_SERINFOSIZE, buffer.get()) != 0)
        return make_unexpected(dl_error{});

    if (::dlinfo(h, RTLD_DI_SERINFO, buffer.get()) != 0)
        return make_unexpected(dl_error{});

    return serinfo{std::move(buffer)};
}

With usage like:
// I absolutely cannot tolerate an exception here:
if (auto const search_paths = dl::get_search_paths_for(dlhandle); search_paths)
{
    // do something with *search_paths
}
else
{
    // report error somehow
}

// Exceptions are okay here:
auto const search_paths = *dl::get_search_paths_for(dlhandle);
// if there was an error, it will be automatically rethrown

Once you do this, you open the door to allowing no-fail default-constructed serinfo objects, which internally just have a null pointer, but externally present as an empty list of search paths. And once you have that, you can trivially implement no-fail moving and swapping, which are very handy in general. Plus, being able to default construct things is handy in a lot of ways (like reading stuff from streams, for example).
Even if you don’t use something like expected<T> and just throw exceptions from the function, I think it’s still a better interface than doing all the work in the constructor on top of actually constructing the object.


Code to make elements fit within their container while keeping their aspect ratio

Although you posted your code it would help if you told us what you want help with?

This is possible to do using CSS. I've seen multiple solitions, here is the first one I found on Google: http://www.mademyday.de/css-height-equals-width-with-pure-css.html


Foo - Control | Naming conventions update

The code within the functions seems clear and simple to me, so my answer mostly focus on the naming conventions:

Why call your variables m..., v..., c... when you could call them "model", "view", "controller"? This would make your code immediately clearer to anyone who reads it.
The functions under "CIn" are also prefixed with "c", which is redundant. Since COut is a controller, it is obvious, that its functions are controller functions so they could simply be called "tryIt", "block", etc.
Strictly speaking, in MVC, the role of a controller is to handle user input and (optionally) to output data. There is not one controller for input and another one for output, both should be handled by the same controller. It might make sense however to wrap output operations in a separate class. In Kohana for instance there's a "Response" object. This is pretty much what you've done with COut, except that you shouldn't call it a controller since that's not really what it is. You could call it "Response" or "Output" for example. "HtmlResponse" might be a good choice too as that would allow you to also have "JsonResponse", "XmlResponse", etc.


Your code is completely safe and free of undefined behavior.

You have used const wherever it is useful and good style.

That's great. :)

One little source of confusion, though. The list of device names contains 9 entries, but the code compares something with an 8. This 8 is confusing since the last valid index in an array is just an implementation detail. (In other programming languages like Lua or Pascal, it could be different.) Contrary, the number of devices is more interesting to any reader. Therefore, readers expect to read that number. Whatever number you write in the code, make sure it's an interesting number.

Therefore, it's better to use the idiomatic code below:

size_t size = sizeof device_names / sizeof device_names[0];
if (device_index < size) {
    return device_names[device_index];
}
return "";

This code doesn't give any clue about the actual number of devices, which makes the code more robust when a device name is added to the list.


Find differences between two spreadsheets

There are some issues with your code:

1) Try to avoid unqualified references, this means always specify the worksheet, when referencing a cell.

2) Try to avoid formatting a lot of single cells, rather format them all at once at the end. Formatting slows down Excel a lot!

3) When handeling a great deal of Ranges, Integer can be insufficient, use Long instead.

Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet)

  Dim ws1row As Long, ws2row As Long, ws1col As Long, ws2col As Long
  Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String
  Dim report As Workbook, difference As Long
  Dim row As Long, col As Long
  Dim unionRng as Range

  Set report = Workbooks.Add

  With ws1.UsedRange
    ws1row = .Rows.Count
    ws1col = .Columns.Count
  End With

  With ws2.UsedRange
    ws2row = .Rows.Count
    ws2col = .Columns.Count
  End With

  maxrow = ws1row
  maxcol = ws1col
  If maxrow < ws2row Then maxrow = ws2row
  If maxcol < ws2col Then maxcol = ws2col

  difference = 0

  With report.Sheets(1)
    For col = 1 To maxcol
      For row = 1 To maxrow
        colval1 = ""
        colval2 = ""
        colval1 = ws1.Cells(row, col).Formula
        colval2 = ws2.Cells(row, col).Formula

        If colval1 <> colval2 Then
          difference = difference + 1
          .Cells(row, col).Value = colval1 & "<> " & colval2 'I guess you want to show, that the formulas used are not equal.
          If unionRng is Nothing Then
            Set unionRng = .Cells(row, col)
          Else
            Set unionRng = Application.Union(unionRng, .Cells(row, col))
          End If
        End If
      Next row
    Next col

    .Columns("A:B").ColumnWidth = 25
  End With

  unionRng.Interior.Color = 255
  unionRng.Font.ColorIndex = 2
  unionRng.Font.Bold = True
  report.SaveAs Filename:="report.xlsx"

  If difference = 0 Then
    report.Close False
  End If
  Set report = Nothing
  MsgBox difference & " cells contain different data! ", vbInformation, _
         "Comparing Two       Worksheets"
End Sub
```


1. Prefer passing parameters by const reference

The std::string parameters should be passed by const reference rather than by value.

Even if passing by value would work properly, it makes the function signature clearer for the caller semantically and may be more efficient.

2. Fix all warnings

The line

return (mistakes <= tolerance);

results in a compiler warning:

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

3. Prefer to use numeric_limits over the C-style INT_MIN

For C++ code you should prefer to use std::numeric_limits<int>::min() instead of the INT_MIN macro (I couldn't even get that to compile, though stdint.h was included).

4. Always use {} braces for conditional code sections

You always should use braces to enclose conditional code sections

if(similarCharacters != nullptr) {
     *similarCharacters = (unsigned int)abs(searchLength - mistakes);
}

Not only it improves the readability of the code, omitting the braces may make the code error prone for changes.

My compiling version can be found here.


Display content if form field is filled - Do not display if field is empty

Oh yes, I recommend some DRYing principles here.  Don't ask php to do the same thing over and over for the same result in a loop -- execute those tasks, just once, before entering the loop.

Rather than repeating whole portions of mark up only to change a few values, create a lookup array of the social networks that you want to cycle through and only replace those values in a reusable piece of the dom.

The social variables are always going to be "set", because they are unconditionally declared when get_field() is called.  There is no point in isset().

If there are any qualifying socials, then the parent
 will enclose all qualifying -tagged-wrapped s.

This ALSO makes it easy for you to scale your application.  In case you ever want to add more socials in the future, just add a new element to $socials (assuming all of the other data is consistent) and you won't need to touch any part of the processing code.

Code: (Demo)

$socials = ['facebook', 'twitter', 'instagram'];
$templateDirectory = get_template_directory_uri();
foreach ($socials as $social) {
    $socialHref = trim(get_field($social, 'option'));
    if (strlen($socialHref)) {
        $socialLinks[] = sprintf(
            '

            ',
            $socialHref, $templateDirectory, $social, ucfirst($social)
        );
    }
}
if (isset($socialLinks)) {
    echo '
' , implode(' ', $socialLinks) , '
';
}

Output:


There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

  Phil Karlton

I'd suggest leaving the job to the browser and to the experts that make it. Additionally, peppering your code with a lot of if-else just to use your cache is too much unnecessary effort really.

Now if you insist going in this route...

First, your function names. They're like from C# land. JavaScript usually uses camel case, with the very first letter in lower case.
There's no sense storing date in a formatted way. You can store it in milliseconds instead. You can get the current timestamp using Date.now().
Your cache tracks time globally, not on a per-item basis. This means there will be a period after wiping that you'll be loading stuff fresh instead of the cache.
An better way to clear an array is to set its length property to 0 instead of assigning another array.
You can take advantage of localStorage to cache content more persistently than just in memory. Note that localStorage has a size limit of 5-10Mb depending on the browser and it only stores strings (objects need be serialized first).
Instead of peppering your code with a lot of if-else operations, consider making a wrapper function for data-fetching mechanisms. Sort of like a decorator.

function cacheWrapper(fn){
  var sourceId = generateIdForFn(fn);
  var isCached = MyCache.hasData(sourceId);
  return isCached ? MyCache.getData(sourceId) : fn();
}

function() originalGetter{ return someRemoteApi.getData(); }

var cachingGetter = cacheWrapper(originalGetter);

var potentiallyCachedData = cachingGetter();

undefined == null. It's always best to use strict comparison to avoid ambiguity.


Finding the Nth occurrence of character in string

It's not necessary to set the return string @ret all the time. You can first look for occurrences of @TargetStr with an incrementing start_location parameter of the CHARINDEX function. Only after no (new) occurrences are found, or when the required max number of occurrences are found is it time to set the return string:

CREATE FUNCTION fn_getFirstNthSentence
(
  @TargetStr VARCHAR(MAX) ,
  @SearchedStr VARCHAR(8000) ,
  @Occurrence INT
)
RETURNS varchar(MAX)
AS
BEGIN
    DECLARE @counter INT = 0
          , @index INT = 0
          , @newIndex INT
          , @end BIT = 0;

    WHILE(@end = 0 AND @counter < @occurrence)
    BEGIN
        SET @counter = @counter + 1;
        SET @newIndex = CHARINDEX(@TargetStr, @SearchedStr, @index + 1);
        IF (@newIndex > 0)
            SET @index = @newIndex;
        ELSE
            SET @end = 1;
    END
    IF @index > 0 SET @index = @index - 1;
    RETURN LEFT(@SearchedStr, @index)
END

Note that this returns an empty string if no occurrences are found. I think that's more correct for a function that returns "everything until the nth occurrence of x".


Speed and efficiency

Just don't worry about it.  You need to generate 1000 random numbers, and do a little bit of accounting work.  Any reasonable solution, such as yours, will perform similarly.

Types

Why use an array of char to keep track of the number of occurrences?  You're putting 1000 random numbers into 10 bins.  What if one of those bins gets more than 127 items?  You would get an overflow.

In summary, those bins should be of type int.  Don't even think about skimping on a few bytes of storage, if you want your code to be not-a-mess.

Naming

nums actually stores counts.  count, as you've used it in the second loop, actually refers to the generated numbers.  I suggest the following renaming:

nums → bins
count → i


Better way to repeatedly use istringstream in "counting minutes" challenge

In to24HourTime(), pos doesn't need to be passed by reference as it's not being modified.  Just pass it by value.

Instead of passing hourToConvert by reference (which is being modified), you can just pass by value and then return the result.  It may also increase readability as it'll be clear that the third argument is to be reassigned by the function.

Final changes:

hour1int = to24HourTime(str, stringPos, hour1int);

// ...

int to24HourTime(string timeString, int pos, int hourToConvert) {
    if (timeString[pos] == 'p' && hourToConvert != 12)
        hourToConvert += 12;
    if (timeString[pos] == 'a' && hourToConvert == 12)
        hourToConvert = 0;

    return hourToConvert;
}


Fetch Keywords from comment and assign keyword id to comment

From performance point of view, 40 iterations is nothing.

However, given such a condition that your keywords are like the Highlanders, as there could be only one, the number of repetitions could be reduced as we won't need anymore after we get one.

foreach($matches as $match) {   //only 1
    foreach ($match as $item) {    //max 10 if a user is mad :\
        foreach ($keywords as $keyword) {   //Max 4
            $keywordBody = strtolower($keyword['keyword_name']);
            if ($item === $keywordBody) {
                    $comment['keyword_id'] = $keyword['id'];
                    break 3; // stop all loops
                }
            }
        }
    }
}


Overall, it seems like your implementation is fine and accurately represents the relationships between the different classes and interface.  You could improve on your design however if you would consider some style guides.

Explicitness

The default modifier for your classes / interfaces will make them only visible from within your package.  While this may be what you intended, it's always better to be explicit and state the level of access you intend each portion of your code to have.  This reduces guess-work made by others who work with your code (which can help to reduce bugs made based on assumptions) and it improves the readability.

This has the additional benefit of making the rest of your code more consistent (since you do not use default modifiers for your methods).

Naming

EDIT

In the following section I borrow wisdom from .NET Land.  This would appear to be contrary to the style guide used by most JAVA developers. As illustrated in the links below:

https://stackoverflow.com/questions/541912/interface-naming-in-java
https://stackoverflow.com/questions/2814805/java-interfaces-implementation-naming-convention

That being said, it used to be convention to not have to dial an area code in the U.S. but after seeing the shortcomings, it was changed to always require area code.  My point is that conventions often change (and usually for pragmatic reasons in the programming community) and as a result be open to other schools of thought.  I think you'll find if you take both pieces of advice (creating interfaces based on attributes / behaviors) along with the "I" prefix, it makes the most sense.  Ultimately this is a SMALL piece of the review and as with the rest of it, feel free to take or not take the input.

END EDIT

Typically (in .NET and Eclipse) interfaces begin with the letter "I" to denote this fact.  So your interface Animals would be better named IAnimal (also without the plural unless you intend the interface to handle multiple animals).

Separation of Concerns

This is more of an esoteric critique, but generally speaking you'll want your interfaces to be well-segregated and more specific.  The current Animals interface doesn't really communicate what the interface is used for.  If I were making an application for example that only showed pictures of various animals, it is unclear whether or not I should use your interface on my new class.
Rather, it is better to split interfaces (usually) based on the behavior they add.  This forces them to be very targeted and succint, which in turn produces code that is more stable and typically easier to maintain since changes are very isolated.

For example, instead of:

interface Animals {

    void callSound();
    int run();

}

You might have:

interface IMakesSound {
    void callSound();
}

interface ICanMove {
    int move();
}

interface IWarmBlooded {
    int currentBodyTemperature();
    bool isOverheated();
}

abstract class Animal implements IMakesSound, ICanMove {
    abstract void callSound();
    abstract int move();
}

abstract class Mammal extends Animal implements IWarmBlooded {
    private int _bodyTemp;
    abstract void callSound(); // We don't know what ALL mammals sound like
    abstract int move(); // Some mammals run, others walk, some swim, and some do all of the above.
    public int currentBodyTemperature() {
        return _bodyTemp;
    }

    public bool isOverheated() {
        return _bodyTemp > 98; // This can be overridden based on the child class if needed
    }
}

// Other classes here that inherit either from `Animal` or `Mammal`.

In the above example, I have separated out your interface into two separate interfaces and an abstract base type that combines them.  Using this structure, I can create something that makes a sound but isn't an animal (for example, a robot toy dog) that can still have all of the attributes of a "real" dog, but none of the inherited animal features.

This allows your code to be more flexible and more loosely coupled (which is the point of using an interface).  By having code dependent on these loosely typed constructs, it allows for more flexibility.

For example:

public class Main {

    public static void main(String[] args) {
        Animals[] animals = new Animals[4];
        animals[0] = new Cat();
        animals[1] = new Dog();
        animals[2] = new Wolf();
        animals[3] = new Lion();

        for (int i = 0; i < animals.length; i++) {
            animals[i].move();
        }

        ShowPetSounds(animals);
    }

    public static void ShowPetSounds(IMakesSound[] petNoises) {
        for (int i = 0; i < petNoises.length; i++) {
            petNoises[i].callSound();
        }
    }

}

This allows us to write code that only knows about pet sounds without having to worry about what kind of animal it is (or indeed that it is an animal).  This allows us to have imaginary pets like dragons (which we all love) or unicorns that would defy the "normal" inheritance hierarchy of an Animal type.

Ultimately both abstract classes and interfaces should be designed to be helpful abstractions, not abstraction for that sake of abstraction.  When you do this, you will find that as your code-base grows over time, it will respond much better to additional requirements and changes in the system.


You could use delegates. Set delegates in the Change event of ddl1, then you can always call the same delegates in your button handlers. This way you only need a switch in ddl1 Change event, and your button handlers will become much cleaner. However, even though this would make the code much more maintainable/readable, it'd probably be less efficient, though you still wouldn't be able to feel the difference in UI handlers.

Update: example added

Something along these lines (not copy&paste):

Public Delegate Function CreateClassDelegate() As NumberClass

Public Class Form
    Public CreateClass As CreateClassDelegate

    Private Sub ddl1_SelectedValueChanged(sender As Object, e As EventArgs)
        Select Case Integer.Parse(TryCast(ddl1.SelectedItem, String))
            Case 0
                CreateClass = New CreateClassDelegate(AddressOf ClassZero.CreateClassZero)
                Exit Select
            Case 1
                CreateClass = new CreateClassDelegate(AddressOf ClassOne.CreateClassOne);
                Exit Select
            Case 2
                CreateClass = new CreateClassDelegate(AddressOf ClassTwo.CreateClassTwo);
                Exit Select
        End Select
    End Sub

    Private Sub btn1_Click(sender As Object, e As EventArgs)
        Dim cl As NumberClass = CreateClass()
        cl.GetNames()
    End Sub

    Private Sub btn2_Click(sender As Object, e As EventArgs)
        Dim cl As NumberClass = CreateClass()
        cl.RunInsert()
    End Sub
End Class

Public MustInherit Class NumberClass
    Public MustOverride Function GetNames() As List(Of String)
    Public MustOverride Sub RunInsert()
    Public MustOverride Sub Remove()
End Class

Public Class ClassZero
    Inherits NumberClass
    Public Overrides Function GetNames() As List(Of String)
         ...
        Return Nothing
    End Function
    Public Overrides Sub RunInsert()
             ...
    End Sub
    Public Overrides Sub Remove()
         ...
    End Sub

    Public Shared Function CreateClassZero() As ClassZero
        Return New ClassZero()
    End Function
End Class

' ... same as above for ClassOne, ClassTwo


Using polymorphism is the way to get an great solution. You are receiving the class in your method just to infer the the return type while you could abstract the idea of conversion and use it to do the inference too. Let's create an interface to convert the result and its implementations:

interface ResultTransformer<T> {
    T transform(ResultSet rs, String column) throws SQLException;
}

public class IntegerResultTransformer implements ResultTransformer<Integer> {
    public Integer transform(ResultSet rs, String column) throws SQLException {
        return rs.getInt(column);
    }
}

public class StringResultTransformer implements ResultTransformer<String> {
    public String transform(ResultSet rs, String column) throws SQLException {
        return rs.getString(column);
    }
}

public class DoubleResultTransformer implements ResultTransformer<Double> {
    public Double transform(ResultSet rs, String column) throws SQLException {
        return rs.getDouble(column);
    }
}

Now the method will receive a ResultTransformer and just call its method transform:

public <T> T getValueFromDb2(String col, String table, String cond, ResultTransformer<T> transformer) {
    // concatenate strings isn't a good idea,
    // use the PreparedStatement methods: setString, setDouble and so on
    ResultSet rs = getSet("SELECT " + col + " FROM " + table + " WHERE " + cond);
    try {
        return transformer.transform(rs, col);
    } catch (SQLException e) {
        throw new RuntimeException(e); // don't return null
    }
}

Using the method:

Integer anInteger = getValueFromDb2("col", "table", "cond", new IntegerResultTransformer());
String aString = .getValueFromDb2("col", "table", "cond", new StringResultTransformer());
Double aDouble = .getValueFromDb2("col", "table", "cond", new DoubleResultTransformer());

For now on, you just need to create a new ResultTransform implementation.