I like your trick to create this syntactic sugar.  The implementation is also pretty good, as are the doctests.

Feature suggestions

I think it would be nice if a case() could test for multiple values.   A case('jack', 'queen', 'king') should match if the Switch was created with any of those three strings.

It would also be nice if there were a case.match() that performed a regular expression match.

Minor issues

If execution ends up inside case.call() due to fall-through, then I would expect the test function not to be called at all, as a kind of short-circuiting behaviour.  Specifically,

elif call(self._value) or self._fall_through:

should be reversed and written as

elif self._fall_through or call(self._value):

Having a parameter named call when the method is also named call is confusing.  I suggest renaming the parameter to test.
Avoid testing variables for equality with True and False explicitly.  Just use boolean expressions.  For example, in __exit__(), change

def __exit__(exc_type, exc_val, exc_tb):
    if exc_type is self.StopExecution:
        return True
    return False

to

def __exit__(exc_type, exc_val, exc_tb):
    return exc_type is self.StopExecution

Initialize _fall_through to False instead of None; it's slightly more informative.
Rename expr → case_value.  Rename _value → _switch_value.
Rename / invert _use_default to not _matched_case, because _use_default is too confusingly similar to _default_used.  Also, by inverting the logic, all three private variables can be initialized to False, which is more elegant.
Instead of a _finished property, write a _check_finished() method that raises StopException too.

Proposed solution

import re

class Switch(object):
    """
    Switch, simple implementation of switch statement for Python, eg:

    >>> def test_switch(val):
    ...   ret = []
    ...   with Switch(val) as case:
    ...     if case(1, fall_through=True):
    ...       ret.append(1)
    ...     if case.match('2|two'):
    ...       ret.append(2)
    ...     if case.call(lambda v: 2 < v < 4):
    ...       ret.append(3)
    ...     if case.call(lambda v: 3 < v < 5, fall_through=True):
    ...       ret.append(4)
    ...     if case(5, 10):
    ...       ret.append('5 or 10')
    ...     if case.default:
    ...       ret.append(6)
    ...   return ret
    ...
    >>> test_switch(1)
    [1, 2]

    >>> test_switch(2)
    [2]

    >>> test_switch(3)
    [3]

    >>> test_switch(4)
    [4, '5 or 10']

    >>> test_switch(5)
    ['5 or 10']

    >>> test_switch(10)
    ['5 or 10']

    >>> test_switch(7)
    [6]

    >>> def test_switch_default_fall_through(val):
    ...   ret = []
    ...   with Switch(val, fall_through=True) as case:
    ...     if case(1):
    ...       ret.append(1)
    ...     if case(2):
    ...       ret.append(2)
    ...     if case.call(lambda v: 2 < v < 4):
    ...       ret.append(3)
    ...     if case.call(lambda v: 3 < v < 5, fall_through=False):
    ...       ret.append(4)
    ...     if case(5):
    ...       ret.append(5)
    ...     if case.default:
    ...       ret.append(6)
    ...   return ret
    ...
    >>> test_switch_default_fall_through(1)
    [1, 2, 3, 4]

    >>> test_switch_default_fall_through(2)
    [2, 3, 4]

    >>> test_switch_default_fall_through(3)
    [3, 4]

    >>> test_switch_default_fall_through(4)
    [4]

    >>> test_switch_default_fall_through(5)
    [5]

    >>> test_switch_default_fall_through(7)
    [6]
    """

    class StopExecution(Exception):
        pass

    def __init__(self, switch_value, fall_through=False):
        self._switch_value = switch_value
        self._default_fall_through = fall_through
        self._fall_through = False
        self._matched_case = False
        self._default_used = False

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        return exc_type is self.StopExecution

    def __call__(self, case_value, *case_values, **kwargs):
        def test(switch_value):
            return any(switch_value == v for v in (case_value,) + case_values)
        return self.call(test, **kwargs)

    def call(self, test, fall_through=None):
        if self._default_used:
            raise SyntaxError('Case after default is prohibited')

        self._check_finished()
        if self._fall_through or test(self._switch_value):
            self._matched_case = True
            self._fall_through = fall_through if fall_through is not None else self._default_fall_through
            return True

        return False

    def match(self, regex, fall_through=None):
        if self._default_used:
            raise SyntaxError('Match after default is prohibited')

        self._check_finished()
        if isinstance(regex, str):
            regex = re.compile(regex)
        if self._fall_through or regex.match(str(self._switch_value)):
            self._matched_case = True
            self._fall_through = fall_through if fall_through is not None else self._default_fall_through
            return True

        return False

    @property
    def default(self):
        self._check_finished()
        self._default_used = True
        return not self._matched_case

    def _check_finished(self):
        if self._matched_case and not self._fall_through:
            raise self.StopExecution()

class CSwitch(Switch):
    """
    CSwitch is a shortcut to call Switch(switch_value, fall_through=True)
    """
    def __init__(self, switch_value):
        super(CSwitch, self).__init__(switch_value, fall_through=True)


Writing an MVC project for the first time - how close am I?

This is a little abstract, without much actual code, but perhaps it's useful nonetheless.

A game is actually a little tough to apply "stringent" MVC to. It's not quite clear cut what belongs where. The world is obviously a model, resources are obviously models, and tiles are too. But is a player a controller or a model? That's more difficult.

I'd say that you shouldn't worry about what the player is. Instead you should add an overall "game controller". Its responsibility would be to update resources before and after #turn is called on a player. The game controller would also be responsible for printing the world, etc., while the player would only responsible for actually making a turn (or, given that there seems to be 2 distinct parts to a turn, make those 2 separate methods). Return a decision (or two), and let the game controller and world sort out how to change the game state (reduce resources, update tiles, etc.).

You might also wait until this point to check the validity of a decision. Let the player make a decision first, and if it's nonsense, let the player try again. The player doesn't necessarily have to know the rules of the game, as long as the game controller knows 'em.

Never mind if the player is M, V, or C. Approach it simply as a "decision maker". It may be AI or a human player, but the point is that it returns a decision. It's sort of a controller, but I'd avoid having it update models or updating the view. It's basically a service object. It could even be completely stateless: Give it a world and a set of resources, and let it come up with a decision somehow.

In terms of code review:

My gut reaction is that there's too much going on in #turn. This is irrespective of the MVC design; the method is just doing too much. (In Ruby you often aim for methods that are super, super short. If you go above 5 lines, you need a reason. Above 10 lines, and you need a very good reason).

Many, if not all, of the UIHandler methods might work better as a module. They appear state-less, so it might well be simpler to just include them where necessary.

There are also some mixed responsibilities. You have tile.check_cost(decision, @resources) but you also have price = GameData.get_price(decision). If you can get the price yourself, you might as well check the cost yourself too. The check_cost method is nicely abstract - you don't need to worry about the cost, just if you can afford it. But that's undermined by you having to fetch the price later anyway.

On a micro level: To get a decision from the command line, I'd recommend something like

def get_decision(&block)
  begin
    input = gets.chomp # or however you read input
  end until !block_given? || yield(input)
  input
end

which you then call like

decision = get_decision { |input| input.empty? || possible?(input) }

where possible? would be a method that checks tile.accepts?(input) and whether it fits the available resources.

Most of all, since there seems to be two steps in a "turn", I'd split those into separate methods. Again, have a game controller and let it call one method first, then the other.


Homework distribution terminal app in C++

Here are some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Make sure you have all required #includes

The code uses std::string but doesn't #include <string>.  It's important to make sure that your code includes all required library headers both the reliably compile and to give the reader a clue as to what is within the program.

Eliminate unused variables

The variables daysUntilDue and result in your code are defined but never used.  Since unused variables are a sign of poor code quality, you should seek to eliminate them.  Your compiler is probably smart enough to warn you about such things if you know how to ask it to do so.

Use objects

Since you're writing in C++, what would make more sense to me would be to create a grades object. Then each operation would be very naturally expressed as an operator on the object.

Decompose your program into functions

Almost all of the logic here is in main in one rather long and dense chunk of code.  It would be better to decompose this into separate functions.

Eliminate magic numbers

The constants 3, 4, 99 and 199 are used in multiple places.  It would be better to have them as named const values so that it would be clear what those numbers represent.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Parsing a component of a regex followed by an optional quantifier character

Whenever I find myself using a lambda, I usually replace it with a local definition:

factor = unit >>= factor'
 where
  factor' x
    =  try (char '?' >> return (Or Epsilon x))
   <|> try (char '+' >> return (Then x (Star x)))
   <|> try (char '*' >> return (Star x))
   <|> return x

Since you only need to look at one character to pick the right branch, you don't need to use try everywhere:

factor = unit >>= factor'
 where
  factor' x
    =  (char '?' >> return (Or Epsilon x))
   <|> (char '+' >> return (Then x (Star x)))
   <|> (char '*' >> return (Star x))
   <|> return x

Finally, we can get rid of the extra parens by using *> instead of >>, and we can replace return with pure:

factor = unit >>= factor'
 where
  factor' x
    =  char '?' *> pure (Or Epsilon x)
   <|> char '+' *> pure (Then x (Star x))
   <|> char '*' *> pure (Star x)
   <|> pure x

This works because *> has higher precedence than <|> which has higher precedence than >>.

I find this easier to read. We've restricted the bulk of our code to Applicative operations, and we only need to use Monadic bind at the beginning where factor' has a direct dependency on unit.

EDIT: We don't need try anymore because char x only consumes a character if the next character in the input stream matches x. Furthermore, each of your branches can either completely match or it can completely fail, and there's no danger of overlap between rules. As an example, here's a simple parser that, like yours, has simple match-or-fail parsers that consume only one character and do not overlap:

data Foo = One | Zero
  deriving (Eq, Show)

foo =  char '1' *> pure One
   <|> char '0' *> pure Zero

If we decide to add a new rule that does overlap, we'll have a problem:

data Foo = One | Zero | Ten
  deriving (Eq, Show)

foo =  char '1' *> pure One
   <|> char '0' *> pure Zero
   <|> char '1' *> char '0' *> pure Ten

Now our first and last rule overlap! We can never successfully parse a Ten:

> parse foo "" "1"
Right One
> parse foo "" "10"
Right One

One's first instinct might be to switch the order of the rules, but this just introduces a new problem:

foo =  char '1' *> char '0' *> pure Ten
   <|> char '0' *> pure Zero
   <|> char '1' *> pure One

> parse foo "" "10"
Right Ten
> parse foo "" "1"
Left (line 1, column 2):
unexpected end of input
expecting "0"

Since the first char '1' has already consumed a character, we've committed to that branch. This is the case where you want to use try; where you might need to backtrack after initially committing to some rule that consumes input:

foo =  try (char '1' *> char '0' *> pure Ten)
   <|> char '0' *> pure Zero
   <|> char '1' *> pure One

> parse foo "" "0"
Right Zero
> parse foo "" "1"
Right One
> parse foo "" "10"
Right Ten

Because many parsers are more complicated than char, it can be easy to just add try without thinking. This can make your parser less efficient because it may have to backtrack many times before it makes progress. It can be worth your time to investigate whether a try is really necessary.


I am suspicious of this line here:

my ($time, $report) = ($line =~ /(\d+),(.*)$/); # time, XML file

That line needs to scan and group the entire XML doc, but my instinct is that a 2-limited split (see note on LIMIT) would be more efficient:

my ($time, $report) = split /,/, $line, 2;

Apart from that, really, everything looks sane, and far better than a typical perl hack. I am impressed.

About perl using all your memory... are you sure? perl may just be struggling to allocate more than it is allowed. Do you have a ulimit condition that is constraining memory allocation? Are there problems with heavily fragmented memory? (You're not running 32-bit, are you... just checking?)

As it happens, for a task like this, you may find that everything is better with a language other than perl. Not to dismiss perl as incapable, but with the XPath expressions and other items your code looks surprisingly complicated. 2.5gig files are way beyond the normal I would consider for perl performance.


I was confused by your code until reading the comments. You want to change the name of sum-once to sum-digits or digit-sum (pick this one!) or anything like it, since that's what it really does.

Your current sum-digits should become digital-root (that's the term for what you're trying to achieve).

  The digital root (also repeated digital sum) of a non-negative integer
  is the (single digit) value obtained by an iterative process of
  summing digits, on each iteration using the result from the previous
  iteration to compute a digit sum. The process continues until a
  single-digit number is reached.


comparative-review:
In both variants, both "traversing indices" get compared to their (respective upper) limit in each traversal of the "proper merge loop".
While "the copy2res-loops" should never execute in merge1, the "res-index" gets compared to its limit right from the start.
In merge2, the "proper merge loop" isn't traversed as often.
Exactly one of the copy2res-loops should be traversed for the same total.

remarks:

merge() isn't doc-commented.
the comments for start&mid might as well be @params,
index of mid looks off,
all three may be final.
Both subarrays include their start - excluding end would be consistent.
I don't get the inversion counting - lack of documentation doesn't help.

Speed-up:

beware memory hierarchy effects
old school complexity analysis assumes uniform memory access time - far from what I'd want to pay and wait for.
don't copy back and fro. Use the auxiliary sequence as the/one source for the next pass.
don't convert between Integer and int time and again.
when using Lists, avoid relying on the "random accessors" to be fast
(implementing RandomAccess is a hint - read backwards, its doc recommends to "always")
use ListIterators to iterate Lists  (note how they (optionally) support set(newValue))
don't time-consumingly ponder/implement variants unless you

established it matters
fixed a measure for good enough

converting to arrays and never looking back (with the possible exception of a terminating conversion/copy back) is an option promising sequential storage and allowing bulk operations. With Lists, operations on sublists may be more efficient.
Most JREs allow a peek at their implementation (have a look at java.util.Arrays, too).


Transformed and stored reversed order digits of an integer to a complete integer number

Indentation
The indentation of your post is very bad, mainly because it is very inconsistent. It doesn't really matter what indentation style you choose, as long as you consistently follow the style. However I strongly recommend the following things:

Use spaces around binary operators, after keywords, after comma's.
Use a single empty line around functions and if, case, do and while blocks.
Prefer foo += bar instead of foo = foo + bar to avoid repeating yourself.

So for example:
int find_out_the_number_of_digit(int number) {
    int count = 0;
    int value = 1;

    // Getting total digits of a given integer number
    while (number != 0) {
        number /= 10;
        count++;

        if (count == 1) {
            value = 1;
        } else {
            value *= 10;
        }
   }

   return value;
}

Try to write correctly formatted code at all times, it helps both yourself and others reading your code. If possible, configure your editor to automatically indent code for you. Be aware though that editors are usually a bit dumb and might not always produce correct indentation, in which case you should correct it yourself. You can also run your code through a program that indents the code for you, like indent or ClangFormat.
Comments
Use comments to clarify things that are not already clear from the code itself. Most of the comments you wrote are superfluous, because they repeat exactly what the code below does, or because it is already clear from the context. Let's look at your comments:
//put variables for further proceed
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);

The sentence is not completely correct English, but it's clear that you mean you are storing information in variables for further processing. But that's just something that is done all the time when programming, it doesn't clarify anything here.
int get_input_validation(){
    ...
    //Taking input from the user
    printf("Enter an integer number: ");
    scanf("%d",&number);

It is already clear from both the name of the function and the two lines below that you are indeed reading input from the user. So in this case I would say the comment is superfluous. A comment like this might be useful however if you have a longer function that does multiple things, and where the comments then separate the various parts of the function, although in that case it is probably better to split such a function up into several smaller ones, which you already did here.
int find_out_the_number_of_digit(int number){
    ...
    //Getting total digits of a given integer number

Here the comment is just repeating what is already in the name of the function.
//get the last digit
last_digit=number%10;

//get the quotient
number=number/10;

Here each comment basically repeats exactly what the line below does. What would be better is to write a comment that explains what is happening at a higher level:
// Pop the last digit from number
last_digit = number % 10;
number /= 10;

Simplifying the solution
There is a simpler solution that is also more efficient, by avoiding the first pass over all the digits to find the length of the number. The solution could be a single loop that does this:
while (number != 0) {
    // Step 1: pop last digit from number
    ...

    // Step 2: push the digit to the back of complete_integer
    ...
}

Doing this will result in the order of the digits to be reversed. You already implemented popping the last digit from a number, now try to implement the reverse operation of pushing something to the back of a number, without having to know the exact length of that number.
About input validation
I wonder why you don't allow the number 0 to be reversed. It seems that this has a clear answer. You should be able to handle that case without having to write any additional code.
For negative numbers, you could indeed disallow them, or instead define how a negative number will be reversed. For example, you could say that the reverse of the number -123 will be -321, and then ensure your code implements this case. If the requirements for this project don't say anything about negative numbers, it is up to you.
Naming things
It is good to have descriptive names for functions and variables. One-letter names are usually bad, unless it's for very commonly used things such as i for a loop iterator, or x and y for coordinates. But too long names can be bad as well; they require more typing, and they are distracting. Not only try to be clear, also be concise. For example:
int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){
    ...
}

That's a lot of text! Now compare the following:
int reverse_digits(int number) {
    ...
}

The name of this function, along with the type of the input parameters and return value, are still very descriptive; it tells you that if you give it a number as a parameter, the function will reverse the digits, and returns the result as an interger. The name is much more concise though.
Similarly, even though you shouldn't need this function, find_out_the_number_of_digit() could be shortened to count_digits().
On the other hand, also be aware of using too similar names. For example:
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);

Now you have two variables, number and value. Now I have to look at what function was called to find out that value is actually the number of digits in number. Here is a suggestion for renaming it:
int input = get_input();
int digits_in_input = count_digits(input);


Reading a .raw file while looking for .jpeg signatures

Binary mode
You should use binary mode to open your file instead of text mode.  So change:

FILE* inptr = fopen(infile, "r");

to
FILE* inptr = fopen(infile, "rb");

Otherwise, your CR/LF characters may get converted when you don't want them to be.
Buffer overrun
Your filename buffer is too short:

char filename[7];

char * name()
{
    if (filenum < 10)
        sprintf(filename, "00%d.jpg", filenum);
    else
        sprintf(filename, "0%d.jpg", filenum);
    // ...

Here, your filenames will be something like "000.jpg" which require 7 characters plus a terminating null character, or 8 characters in total.  Also, if you generate 100 or more files, you will need even more characters.
Pad string with leading zeros
There is a better way to generate filenames padded with leading zeros.  Instead of:

if (filenum < 10)
    sprintf(filename, "00%d.jpg", filenum);
else
    sprintf(filename, "0%d.jpg", filenum);

you can do this:
sprintf(filename, "%03d.jpg", filenum);


Implement Scala-like Trampoline to gain tail call optimization in Rust

Run Rustfmt. It will automatically fix such things as

Opening curly braces go on the same line as the function signature (unless the function signature is already multiple lines).
There is no comma at the end of a match arm that uses curly braces.

Your function name has a typo: recurse_trampolin
Instead of taking a trait object reference (&Fn(...) -> ...), take a generic. This allows for better optimizations and avoids unnecessary indirection.

enum Trampoline<A, R> {
    Continue(A, R),
    End(R),
}

impl<A, R> Trampoline<A, R> {
    fn start<F>(function: F, mut arg: A, mut sum: R) -> R
    where
        F: Fn(A, R) -> Trampoline<A, R>,
    {
        loop {
            match function(arg, sum) {
                Trampoline::Continue(r_arg, r_sum) => {
                    arg = r_arg;
                    sum = r_sum;
                }
                Trampoline::End(result) => return result,
            }
        }
    }
}

fn recurse_trampoline(arg: i32, sum: i32) -> Trampoline<i32, i32> {
    if arg == 0 {
        Trampoline::End(sum)
    } else {
        Trampoline::Continue(arg - 1, sum + arg)
    }
}

fn recurse_normal(arg: i32, sum: i32) -> i32 {
    if arg == 0 {
        sum
    } else {
        recurse_normal(arg - 1, sum + arg)
    }
}

fn main() {
    println!("{}", recurse_normal(5, 0));
    println!("{}", Trampoline::start(recurse_trampoline, 5, 0));
}


Code that prints ASCII bowties to screen given inputs

I think the main issue you need to focus first, is to split the input from the processing and maybe even from the output. I'm not sure if you meet the requirements of the task, when you start outputting stuff before completing the input.

If Java was a conscious choice, you might want to think about a more OOP approach. BowtieSet seems a good candidate for a class.

I assume you left away any input validation/user interface by purpose in relation to the task.

In Java you usually define variables not at the beginning of a method, but where you use them. In addition to that, for loops general start with 0 and end <max.

public class Main
{
    public static class BowtieSet
    {
        private final int  length;
        private final int  repeat;
        private final char style;

        public BowtieSet(final int length, final int repeat, final char style)
        {
            this.length = length;
            this.repeat = repeat;
            this.style = style;
        }

        public String getAscii()
        {
            return "TODO:" + length + "-" + repeat + "-" + style;
        }
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        final int numberOfBowtieSets = in.nextInt();
        List<BowtieSet> bowties = new ArrayList<>(numberOfBowtieSets);
        for( int i = 0; i < numberOfBowtieSets; i++ )
        {
            int length = in.nextInt();
            int repeat = in.nextInt();
            char style = in.next().charAt(0);
            bowties.add(new BowtieSet(length, repeat, style));
        }

        bowties.forEach(b -> System.out.println(b.getAscii()));
    }
}

If you stay with an procedural style (totally fine for such a task), you could anyway try to split your main method into smaller well names methods.

Nevertheless, after this initial objectifaction or extracting of a method like

public String getAscii(int length, int repeat, char style)

it is far easier to test your code (automatically and manually). You don't need to type stuff anymore and there is nothing on stdout that needs to be read. As a first step you can simply move the content of your outer for loop into such an method (plus some minor adaptations and appending to a StringBuilder instead of printing to system out).

Afterwards it's time to write some unit tests, or at least two for your samples.

public class BowtieSetTest
{
    @Test
    public void sample1()
    {
        assertEquals("...", new BowtieSet(5, 2, '#').getAscii());
    }

    @Test
    public void sample2()
    {
        assertEquals("...", new BowtieSet(11, 1, '!').getAscii());
    }
}

The length parameter in your space() method is "useless". I think in your application you will have no benefit from defining the capacity of the StringBuilder, it just reduces the readability of your code. In case you ever need an other millisecond, come back to this place. Nevertheless, padding strings can also be done with following common and shorter method:

public static String space(int spaces)
{
    if( spaces == 0 ) return "";
    return String.format("%1$" + spaces + "s", "");
}

You can skip the same optimization in your stringMulti method. In addition to that in Java you usually don't pass arrays around the system and modify them. If we make the the method private and keep the issue local, I think we can live with this for the moment. (List as parameter and new list as return values would be more common)

private static void repeatEachLine(String lines[], int repetitions)
{
    for( int x = 0; x < lines.length; x++ )
    {
        StringBuilder sb = new StringBuilder(lines[x]);
        for( int y = 1; y < repetitions; y++ )
        {
            sb.append(" ");
            sb.append(lines[x]);
        }
        lines[x] = sb.toString();
    }
}

It really took me a moment to figure out what the methods stringMulti did. I hope the new method name will help others (or my future self) to be faster at this point.

Let's get back to your main method. You have two for loops, one to the mid and the second for the remaining lines. You already notice that the lower lines are mirrored from the upper lines, so you can also merge the fors and omit your counter

At this point my remaining getAscii method looks like (Disclaimer: I like oneliner, many don't):

public String getAscii(int length, int repeat, char style)
{
    int width = length + 3;
    int mid = length / 2 + 1;
    String[] lines = new String[length];

    for( int x = 0; x < mid; x++ )
    {
        if( x == 0 )
        {
            int intspaces = width - 2;
            String intspace = space(intspaces);
            lines[x] = style + intspace + style;
            lines[length - x - 1] = lines[x];
        }
        else if( x != (mid - 1) )
        {
            int intspaces = width - 2 * (x + 1);
            int extspaces = x - 1;
            String intspace = space(intspaces);
            String extspace = space(extspaces);
            lines[x] = style + extspace + style + intspace + style + extspace + style;
            lines[length - x - 1] = lines[x];
        }
        else
        {
            int extspaces = x - 1;
            String extspace = space(extspaces);
            lines[x] = style + extspace + style + "[]" + style + extspace + style;
        }
    }

    if( repeat != 1 ) repeatEachLine(lines, repeat);
    return Arrays.stream(lines).collect(Collectors.joining("\n"));
}

I think now it is time to extract the content of the for loop to a getAsciiLine(...) method. Add some tests and check if we can simplify the ifs. At least I would inline the int variables. They no longer add any information.

Let me try an other approach here. Instead of building the string character by character, let me take a blank string of the correct length (char[]) and only fill some places with the style character:

void getAsciiLine(final String[] lines, final int currentLine, final int width, final int mid /*...+ style, length if not an object*/)
{
    char[] string = space(width).toCharArray();
    // set left and right border
    string[0] = style;
    string[width - 1] = style;
    // moving to the center
    string[currentLine] = style; //redundant for 0/width-0, but at least no if
    string[width - currentLine - 1] = style;

    final boolean isMiddleLine = currentLine == (mid - 1);
    if( isMiddleLine )
    {
        string[currentLine + 1] = '[';
        string[currentLine + 2] = ']';
    }
    lines[currentLine] = new String(string);
    if( !isMiddleLine ) lines[length - currentLine - 1] = lines[currentLine];
}

Keep in mind that some refactorings are opinion based, so this answer is not the only truth.

BowtieSet:

import java.util.Arrays;
import java.util.stream.Collectors;

public class BowtieSet
{
    private final int  length;
    private final int  repeat;
    private final char style;

    public BowtieSet(final int length, final int repeat, final char style)
    {
        this.length = length;
        this.repeat = repeat;
        this.style = style;
    }

    public String getAscii()
    {
        int width = length + 3;
        int mid = length / 2 + 1;
        String[] lines = new String[length];
        for( int x = 0; x < mid; x++ ) getAsciiLine(lines, x, width, mid);
        if( repeat != 1 ) repeatEachLine(lines, repeat);
        return Arrays.stream(lines).collect(Collectors.joining("\n"));
    }

    private void getAsciiLine(final String[] lines, final int currentLine, final int width, final int mid)
    {
        char[] string = space(width).toCharArray();
        // set left and right border
        string[0] = style;
        string[width - 1] = style;
        // moving to the center
        string[currentLine] = style; //redundant for 0/width-0, but at least no if
        string[width - currentLine - 1] = style;

        final boolean isMiddleLine = currentLine == (mid - 1);
        if( isMiddleLine )
        {
            string[currentLine + 1] = '[';
            string[currentLine + 2] = ']';
        }
        lines[currentLine] = new String(string);
        if( !isMiddleLine ) lines[length - currentLine - 1] = lines[currentLine];
    }

    private static String space(int spaces)
    {
        if( spaces == 0 ) return "";
        return String.format("%1$" + spaces + "s", "");
    }

    private static void repeatEachLine(String lines[], int repetitions)
    {
        for( int x = 0; x < lines.length; x++ )
        {
            StringBuilder sb = new StringBuilder(lines[x]);
            for( int y = 1; y < repetitions; y++ )
            {
                sb.append(" ");
                sb.append(lines[x]);
            }
            lines[x] = sb.toString();
        }
    }
}

Main:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        final int numberOfBowtieSets = in.nextInt();
        List<BowtieSet> bowties = new ArrayList<>(numberOfBowtieSets);
        for( int i = 0; i < numberOfBowtieSets; i++ )
        {
            int length = in.nextInt();
            int repeat = in.nextInt();
            char style = in.next().charAt(0);
            bowties.add(new BowtieSet(length, repeat, style));
        }

        bowties.forEach(b -> System.out.println(b.getAscii()));
    }
}

BowtieSetTest:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class BowtieSetTest
{
    @Test
    public void sample1()
    {
        assertEquals(//
            "#      # #      #\n" +//
                "##    ## ##    ##\n" +//
                "# #[]# # # #[]# #\n" +//
                "##    ## ##    ##\n" +//
                "#      # #      #",//
            new BowtieSet(5, 2, '#').getAscii());
    }

    @Test
    public void sample2()
    {
        assertEquals(//
            "!            !\n" +//
                "!!          !!\n" +//
                "! !        ! !\n" +//
                "!  !      !  !\n" +//
                "!   !    !   !\n" +//
                "!    ![]!    !\n" +//
                "!   !    !   !\n" +//
                "!  !      !  !\n" +//
                "! !        ! !\n" +//
                "!!          !!\n" +//
                "!            !",//
            new BowtieSet(11, 1, '!').getAscii());
    }
}

The empty comments in the test are only used to trick my IntelliJ IDEA formatter.


Splitting payments in a number of installments

I tried to simplify the loop:

    int availableAsset = paymentList.stream().mapToInt(Integer::intValue).sum();

    for (Integer currentInstallmentAmount : installmentList) {
        if (availableAsset > currentInstallmentAmount) {
            balanceList.add(0);
            depositList.add(currentInstallmentAmount);
            availableAsset -= currentInstallmentAmount;
        } else {
            if (availableAsset > 0) {
                depositList.add(currentInstallmentAmount - availableAsset);
                balanceList.add(availableAsset - currentInstallmentAmount);
                availableAsset = 0;
            } else {
                balanceList.add(-currentInstallmentAmount);
                depositList.add(0);
            }
        }
    }

Since we have just this or that decisions (instead of a selection) it's not really a benefit to use polymorphism here.


Basic calculator program in Python as a beginner

Thanks for asking your question! I'll try and give a concise answer to the main issues with your code. Overall it is well done for a beginner.

First, I'll address the code block you're having trouble with. The restart variable is never defined, so I'm not even sure how your code ran at all. You will need to give restart some initial value, supposedly "Y" as that would have it skip over that code in the beginning.

There is a bigger problem here though, which is that you are putting code in the global scope and also in a main function. Usually, Python scripts do one or the other, as they mean different things to other Python programmers. Although it is completely valid what you're doing, it's not good Python. The purpose of the main function and the if __name__ == '__main__' conditional is so that you can separate the "executable" part of your program from the "library" part.

(See this StackOverflow answer for more detail: https://stackoverflow.com/questions/419163/what-does-if-name-main-do)

The main function allows your code to have different behavior when your program is run on its own, as opposed to when it's imported and usually this means that the imported code does not run anything on its own especially the blocks you're having trouble with.

I would suggest putting all the "running" code, that is, the restart check, and the "calculator startup" all in the main function. And, if you want to logically separate these ideas, then put them all in separate functions that run from main. Something perhaps along the following lines:

def restart(response):
    # uses "in" to check multiple values,
    # a replacement for (response == "Y" or response == "y")
    # which is longer and harder to read.
    if response in ("Y", "y"):
        return True
    else:
        # statements you want to print to the screen before exiting
        ...
        return False

And in the main function:

def main():
    ...
    setup_calculator()  # something you would write, feel free to give it a better name
    ...
    restart_msg = "Would you like to make more calculations?" \
                  "Enter (Y) for yes, or any other character for no. "
    if not restart(str(input(restart_msg))):  # uses the function I wrote
        return  # would not need to import "sys", just exit from main normally

You can do a similar thing for the calculator startup, but I'll leave that to you.

In your run_operation function, you write conditionals with int("1"), int("2"), ... etc. You can just write 1, 2, ... etc, for each if statement. Also, you don't have to worry about typecasting the inputs to run_operation because you do that in the input in main. Once you have the types from the user input, assume that your code runs on that specific type.

One more thing I noticed is that almost everytime you print to the console, you also perform a time.sleep(1), (in one case a time.sleep(2)). What I suggest, so that you don't repeat yourself, is to write your own print function that also performs a sleep every time,

def calculator_print(*args, delay=1):
    print(*args)
    time.sleep(delay)

You could give it a better name, I'm just concerned with the form that it has. This would probably halve your line count and improve readability by many times. The *args is a way for you to accept any number of arguments to calculator_print to match the way that print itself can and does accept many arguments, like in your run_operation function. The delay default argument is there to set the sleep delay to a different value other than 1 like in your calculator startup. This will get rid of all of your explicit time.sleep calls and abstracts away the details of the printing itself. (Say you wanted to change it to do something different, you can still use the rest of the code you've written in the same way. You would only have to change the calculator_print function. Encapsulation is good!)

If you fix these few problems, I think you will be rid of any bugs that you have already and your readability will skyrocket. A very very important part of programming that is grossly overlooked is readability. This should always be taught alongside syntax. As a programmer you will be reading code more than writing it so you should be good at reading good (and bad) code and writing code that makes it easier for others to read; you may even be reading your own old code one day. Writing comments and clear code are both essential for readability.

You've done a really good job here as a beginner. Let me know if you have any questions about what I've said or about anything else Python.

Keep up the good work!


There's really no purpose in having 3 banner images if you're going to add and remove the image source from each one. You might as well just have a single image and change the source of it on each iteration.

When you do that trick with setTimeout, where your timeout is the index of the array multiplied by an offset, you are effectively creating a new thread for every iteration, which can be memory intensive when you have a lot of images. A better approach would be to use recursion.

Consider this slowLoop function.

/**
 * Execute the loopBody function once for each item in the items array,
 * waiting for the done function (which is passed into the loopBody function)
 * to be called before proceeding to the next item in the array.
 * @param {Array} items - The array of items to iterate through
 * @param {Function} loopBody - A function to execute on each item in the array.
 *      This function is passed 3 arguments -
 *          1. The item in the current iteration,
 *          2. The index of the item in the array,
 *          3. A function to be called when the iteration may continue.
 * @returns {Promise} - A promise that is resolved when all the items in the
 *      in the array have been iterated through.
 */
function slowLoop(items, loopBody) {
    return new Promise(f => {
        let done = arguments[2] || f;
        let idx = arguments[3] || 0;
        let cb = items[idx + 1] ? () => slowLoop(items, loopBody, done, idx + 1) : done;
        loopBody(items[idx], idx, cb);
    });
}

Using this you're able to keep the entire script on a single thread.

var myImage = document.querySelector("#banner");

var arrayImage = [
  "https://via.placeholder.com/150x150/f00/fff?text=Slider1",
  "https://via.placeholder.com/150x150/f0f/fff?text=Slider2",
  "https://via.placeholder.com/150x150/00f/fff?text=Slider3"
];

function slowLoop(items, loopBody) {
    return new Promise(f => {
        let done = arguments[2] || f;
        let idx = arguments[3] || 0;
        let cb = items[idx + 1] ? () => slowLoop(items, loopBody, done, idx + 1) : done;
        loopBody(items[idx], idx, cb);
    });
}

function slideChange(){
  slowLoop(arrayImage, function(img, idx, done){
    myImage.setAttribute("src", img);
    setTimeout(done, 2000);
  }).then(slideChange);
}

slideChange();
.banner {
  display: block;
}
<img id="banner">


Just focusing on the Javascript:

I feel a urge to to reference a story about a monk. Instead I'll just say that descriptive names will help when you come back to your code or when others try to read it.
for example:

var obj = document.getElementById(id);
obj.style.position = "absolute";
obj.onmousedown = function () {
    scr = obj;
}

Here it would be better to name obj something like draggableElement or some such. this was I know instantly what we are referring to.
You are testing e and pageY and assigning a variable in two different way. Pick one way and be consistent about it. It really matters not what you choose so much as sticking to it.

Here are a couple of different ways you could do it.

if

if (!e) e = window.event;
var y = e.pageY;
if(!y) y = e.clientY;

ternary

e = e ? e : window.event;
var y = e.pageY ? e.pageY : e.clientY;

or

e = e || window.event;
var y = e.pageY || e.clientY;

I personally favour this last way.


Convert boolean array to integer in Typescript

Binary Math
Using string to do integer maths is very slow. You can use bitwise operators to encode and decode bit fields.
Encode bool array to int
The first function sets the low bit depending on the boolean. Each iteration the bits set are shifted to the left. The result is that the first array item is the highest bit (bit 7) and the last day is the lowest bit (bit 1)
Decode int to bool array
The second uses bitwise AND & to mask out all but the bit position required and adds a boolean to an array depending on the state of the bit.

// high bit is first item in days eg 0b1000000 is day[0]
function serializeDays(days) {
     return days.reduce((bin, day) => (bin << 1) + (!!day), 0);
}

function parseDays(bitField) {
     var bit = 7, days = [];
     while (bit) { days.push((bitField & (1 << --bit)) !== 0) }
     return days;
}

console.log(serializeDays([true,false,true,false,true,false,true]).toString(2));
console.log(parseDays(0b1010101).join(","));


public EndPoint LocalEndPoing { get; private set; }

should be LocalEndPoint.

public void Start()
{
    try
    {
        if (Listening)
            return;

why is this if statement inside the try..catch ? It can be granted that this won't ever throw any exception. As a rule of thumb, only put code inside a try..catch which can throw.

You should always use braces {}, although they might be optional, to make your code less error prone.

_server.Listen(10);

why 10 and not 1000? Using magic numbers should be avoided to make the code easier to read and understand. You should extract magic numbers/strings into meaningful variables/constants so Sam the maintainer will see at first glance what this is about.

_asyncOperation.Post(ex=>OnErrorOccured(ex as Exception),exception);

Let your variables and operators have some space to breathe, its just making your code more readable like so

_asyncOperation.Post(ex => OnErrorOccured(ex as Exception), exception);

private void _acceptArg_Completed(object sender, SocketAsyncEventArgs e)

having an underscore prefixed methodname is a no go. Underscore prefixing is tolerated for class level variable names only.


Function signatures
You've made the best out of a slightly silly situation. I think your function signatures, while abiding to the template, have improved since the last post of yours that I reviewed.
I'm not sure whether this will break LeetCode compatibility, but if you want to enforce that no one can instantiate this class, try making a private default constructor.
Mean
A simpler way to express the arithmetic mean than
        size_t mid = lo + (hi - lo) / 2;

is
        size_t mid = (hi + lo) / 2;


pcmpistri
This seems like the obvious choice searching withing a string. However, while pcmpistri is very general/powerful, it is also not very fast. On typical Intel processors it consists of 3 µops that all go to execution port p0 (therefore limiting this loop to at best running one iteration every 3 cycles), on AMD Zen(1/2) it's slightly less bad coming in at 2 µops and executing once every 2 cycles.
There is an in way more primitive way (just using SSE2) based on pcmpeqb and pmovmskb. That leaves you with a mask instead of an index, but for most of the loop that doesn't matter (all that matters is whether the mask is zero or not), and in the final iteration you can use tzcnt (or similar) to find the actual index of the zero byte within the vector.
That technique also scales to AVX2, which pcmpistri does not. Additionally, you could use some unrolling: pminub some successive blocks of 16 bytes together to go through the string quicker at first, at the cost of a more tricky final iteration and a more complex pre-loop setup (see the next point).
A bug
While an aligned load that contain at least one byte of the string is safe even if the load pulls in some data that is outside the bounds of the string (an aligned load cannot cross a page boundary), that trick is unsafe for unaligned loads. A string that ends near a page boundary could cause this function to fetch into the next page, and possibly trigger an access violation.
There are different ways to fix it. The obvious one is using the usual byte-by-byte loop until a sufficiently aligned address is reached. A more advanced trick is rounding the address down to a multiple of 16 (32 for AVX2) and doing an aligned load. There are bytes in it that aren't from the string, maybe including a zero. Therefore those bytes must be explicitly ignored, for example by shifting the mask that pmovmskb returned to the right by data & 15. If you decide to add unrolling, then the address for the main loop should be even more aligned, to guarantee that all the loads in the main loop body are safe.


Converting colours in an image using Python Imaging Library

The easiest way is to use the numpy interface for this, since it allows you to do operations on the whole image:

from PIL import Image
import numpy as np

def _colour_mask(img, colour):
    """Finds all indices of a single colour in a PIL.Image"""
    if len(img.shape) == 3:
        return (img == colour).all(axis=2).nonzero()
    elif len(image.shape) == 2:
        return (img == colour).nonzero()
    else:
        raise ValueError("Invalid image shape {}".format(img.shape))

def _convert_colour(img, incolour, outcolour):
    """Replaces incolour with outcolour in a PIL.Image.

    Returns a new PIL.Image.
    Assumes that img has as many channels as len(incolour) and len(outcolour).
    """
    img = np.array(img)
    img[_colour_mask(img, incolour)] = outcolour
    return Image.fromarray(img)

def convert_colour(region_number, incolour, outcolour):
    file_name = region_list.regions_d[region_number][0]
    img = Image.open(file_name)
    new_img = _convert_colour(img, incolour, outcolour)
    new_img.save(file_name, "PNG")
    colour_change_single(region_number, outcolour)


I would define a shift function that shifted the letters like so:

from string import whitespace, punctuation

def shift(c, shift_by = 2):
    if c in whitespace + punctuation: return c

    upper_ord, lower_ord, c_ord = ord('A'), ord('a'), ord(c)
    c_rel = (c_ord - lower_ord) if c_ord >= lower_ord else (c_ord - upper_ord)
    offset = lower_ord if c_ord >= lower_ord else upper_ord
    return chr(offset + (c_rel + shift_by) % 26)

Then, to translate a message:

msg = 'a quick brown fox jumped over the lazy dog'
encoded_msg = ''.join(shift(l) for l in msg)

Alternatively, combine Mark Tolonen's maketrans suggestion with g.d.d's deque suggestion to get:

import string
from collections import deque

alphabet = string.ascii_lowercase
alphabet_deque = deque(alphabet)
alphabet_deque.rotate(-2)
rotated_alphabet = ''.join(alphabet_deque)
tbl = string.maketrans(alphabet, rotated_alphabet)

Then, later in the code:

msg = 'a quick brown fox jumped over the lazy dog'
encoded_msg = string.translate(msg, tbl)

This second method only works for lowercase letters, but you can always create two separate translation tables -- one for uppercase letters and another for lowercase letters -- to account for case.

Offtopic note: sometimes I wish Python had Smalltalk-like cascaded message sends. Ah well, one can dream.


Implementation of KeyEventDispatcher in Java

First...
I'd, personally, rely on the virtual key code over the key character.  It's possible that the key character may not have been interpreted  until the KEY_TYPED event (or at least I remember some issue where the char could be interpreted at certain stages)
private HashMap<Integer, Boolean> keyPresses = new HashMap<>();

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    int keyCode = e.getKeyCode();

    if (e.getID() == KeyEvent.KEY_PRESSED) {

        if (keyPresses.contains(keyCode) && keyPresses.get(keyCode).booleanValue()) {
            return false;
        }
        keyPresses.put(keyCode, new Boolean(true));

This also means you don't need to convert the key to lower case, as the virtual key doesn't carry the modifier information (the key character is the key code + the modifiers)
There is a problem with this, KeyEvent.VK_1 can represent both 1 and !, so you might need to consider using KeyStroke instead...
Second...
It's a nitpick on my behalf, but I like a single entry and single exit point in the code...
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    int keyCode = e.getKeyCode();

    if (e.getID() == KeyEvent.KEY_PRESSED) {

        if (!keyPresses.contains(keyCode) || !keyPresses.get(keyCode).booleanValue()) {
            keyPresses.put(keyCode, new Boolean(true));

It generally makes the code easier to read and the logic to follow as return statements can "hide" in code and it's easy to miss them (IMHO)
Third
Rather than something like this...
switch (keyToLowerCaseIfUpperCase(e.getKeyChar())) {
    case 'a': System.out.println("D"); break; // these are just two test cases
    case 'b': System.out.println("E"); break;
    default: break;
}

I would consider using another Map, to map between the virtual key and the value or "callback" you want to call.  It will be easier to add new values and reuse the code
I'd also consider using a callback mechanism, which would notify of the KEY_PRESSED and KEY_RELEASED events, so the dispatcher didn't do the conversion itself, but simply managed the notification processes, further separating the implementation logic and allow the dispatcher to be more reusable.
You could achieve the same thing through abstraction, but I think some kind of Observer Pattern would be more pratical (IMHO)
Fourth
Unless you really need to know if a key is not been pressed, I would remove the keyCode from the Map on the KEY_RELEASED event
} else if (e.getID() == KeyEvent.KEY_RELEASED){
    keyPresses.remove(keyCode);
}

As it would simpler to just use something like keyPresses.contains(keyCode) instead of then actually needing to check the value associated with, but this comes down to needs.
You could replace the Map with a Set instead which would be simpler, either the keyCode exists or it doesn't...


Convert JSON from a webservice to text file

I am here for some criticism and learning :)

That's really a great attitude. Keep it up and you'll get far.

Handling the last item differently

You alluded to the issue of doing social treatment for the last item in a loop. There are two related relevant places in the posted code:

    for dictionary in list_of_dictionaries:
        for column in list_of_columns:
            # ...
            if column != list_of_columns[-1]:
                # special treatment 1
        if dictionary != list_of_dictionaries[-1]:
            # special treatment 2

Having a conditional statement that is executed for every item in a list, and you know it is false for all items except the last, is not pretty. It could be acceptable, if the condition is super fast, for example a simple comparison of two numbers. Here you are comparing strings and objects, which may not be super fast.

You could convert this to a simple numeric comparison by using a range loop, and then comparing indexes instead of objects.

You could also change the loops to iterate until the element before the end, and then do the special treatment for the last, outside the loop. That way you can eliminate the conditional statements.

Seeking in a file

When opening a file for writing with the w option only, there's no need to seek(0) in it, that will happen automatically, and the file will be rewritten.

Extracting the beginning of a string until some character

It's not efficient to use split for this. It will allocate a list to store the results, and scan until the end of the string, even though you only need the first part. It would be better to find the index of the dot, and then get a substring.


Matrix indexing

The display function is a handful. It's often better to use a matrix library like numpy to allow better indexing features. For instance,

import numpy as np
one_thru_nine = list(range(1,10))
print(one_thru_nine)
matrix = np.array(one_thru_nine).reshape(3,3)
print(matrix)
print(matrix[0, 1])
print(matrix[1, 1])
print(matrix[2, 2])

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
2
5
9

(Disclaimer: np.array(one_thru_nine).reshape(3,3) is not really an ideal way of initializing numpy arrays, it's just for demonstration purposes.)

Of course, do beware of zero-indexing.

Magic numbers

As a rule of thumb, avoid magic numbers. Try not to put raw integers into code.

return 0 < box_num < 10

will be more readable as

min_boxes, max_boxes = 0, 10
return min_boxes < box_num < max_boxes

Similarly, I can understand what Turn=3 does, but it's unintuitive.

If-Else statements

else:
  pass

is redundant. If you don't have anything to do when if and elif conditions fail, you don't have to add the else statement altogether -- unlike some other languages.

That is, you can just do:

while True:
  if condition_one:
    do_something()
  elif condition_two:
    do_something_else()

Class declaration

You don't need to put parentheses next to class declarations if you are not inheriting from a super class.

class Board():
   def __init__(self):

can just be

class Board:
   def __init__(self):

Casing

As a general rule of thumb, in classes are in PascalCase and everything else (modules, variables, functions, methods) are in snake_case. As such, from AskUser import ask_user as As should be reformatted as from ask_user import ask_user as as_as or something similar.

Similarly, things like Turn should be turn.

Wrap your module with main

In general, if you are not declaring globals, and you declare functions that you will actually call as main (perhaps you're familiar with C or Java?) you should wrap them in a statement of

if __name__ == "__main__":
  board = Board()
  turn = randint(0,1) ...

If you don't get into the habit of this, you'll end up executing code you don't want to when you're just importing code from other modules.

Others

I don't see the use of valid and invalid_message anywhere?


Polling an API endpoint with timeout using channels

How about this?
I used context.Context with the deadline which also gives control to the caller of poll if you want to cancel the poll before the deadline through CancelFunc. I do not have a full context of the problem here, but this should help you.

// PollStatus will keep 'pinging' the status API until timeout is reached or status returned is either successful or in error.
func (client *APIClient) PollStatus(ctx context.Context, id int, pollInterval time.Duration) (*Status, error) {
        ticker := time.NewTicker(pollInterval)
        defer ticker.Stop()
        tickerCounter := 0
        for {
            select {
            case <-ctx.Done():
                return nil, ctx.Err()

            case tick := <-ticker.C:
                status, err := client.GetStatus(id)
                tickerCounter++
                if err != nil {
                    return nil, err
                }

                log.Printf("tick #%d at '%ss', %s", tickerCounter, tick.Format("05"), status)
                if status.IsErrorStatus() {
                    return nil, errors.New("error while polling for status")
                }

                if status.IsCompletedStatus() {
                    return status, nil
                }

            }
        }

        return nil, errors.New("unable to get status")
  }

func someFunc() {
    log.Printf("polling status, id: %d", sid)
    ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
    // Having cancelFunc here gives control if you want to cancel the poll before deadline
    // but for this instance, I'm just gonna defer cancel it
    defer cancelFunc()
    status, err := api.PollStatus(ctx, sid, 1*time.Second)
    if err != nil {
        log.Fatalf("PollStatus error: %+v", err)
    }

    log.Print(status)
}


Getting student demographics report with ActiveRecord

I'd suggest a couple of things:

the for i in 0...@distinct.length takes your array's length and uses it to construct a range which it turns into an array again. Not necessarily time consuming but unnecessary and hard to read. Ruby gives you each_with_index which can do it in a nicer, more concise way.
favoring working with IDs should speed things up because no Active Record objects need to be created and filled and it's quite enough for your calculations. One important tool for that is pluck.
I also removed several local variables as you only use them for tallies and that's, again, not really necessary. But no real speedup here, either.

TL;DR: here's the re-factored version with calculations in ruby.

safe_ids = safe.map(&:student_id)
@distinct.each_with_index do |date, i|
  @active[i] = safe_ids.length
  @inactive[i] = 0
  @student_ids = StudentDemographics.where("id not in (?)", safe_ids).where("date <= ?", date).pluck("student_id")
  @student_ids.each do |student_id|
    @stu = StudentWeeklyReport.where(:student_id => student_id).last(5).pluck(:golden_eggs)
    if @stu.length <= 4 || @stu[4] > @stu[0]
      safe << student_id
      @active[i] += 1
    else
      @inactive[i] += 1
    end
  end
end

You could also try and have the whole calculation done by the database, by using group_by and having in a fairly complicated but probably very fast query.

But I'll leave it to the astute reader to figure that one out (mainly since I couldn't manage to get it right in time).


Updating items in a list from a blocking source asynchronously

My try to simplify and prettify the method.
Avoid using globals in async code, pass Token as argument.
// optimized out async State Machine
private Task UpdateLogsAsync(IProgress<string> status, CancellationToken token) => Task.Run(async () =>
{
    await foreach (var message in this.Server.GetLogMessages().WithCancellation(token))
    {
        status.Report(message);
    }
}, token);

Usage
// synchronized callback. Create new in UI Thread and its body will be always executed there.
IProgress<string> status = new Progess<string>(message =>
{
    this.textLogs.AppendText($"{message}{Environment.NewLine}");
});
try
{
    await UpdateLogsAsync(status, this.CancellationTokenSource.Token);
}
catch (OperationCanceledException ex)
{
    status.Report(ex.Message);
}


Validation Error Handling - DRY Pattern Implementation

public static class ExistsHelper
{
    public static bool Country(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool State(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool City(int id)
    {
        return (id > 10) ? true : false;
    }
}

The usage of a ternary here is senseless, you can just return the evaluated condition like so
public static class ExistsHelper
{
    public static bool Country(int id)
    {
        return (id > 10);
    }

    public static bool State(int id)
    {
        return (id > 10);
    }

    public static bool City(int id)
    {
        return (id > 10);
    }
}

but looking at it, it seems it doesn't matter what "type"  you are validating because they all have the same condition. You could simply use only one method and extract the magic number 10 into a meaningful constant.

ValidateNotExistImproved
Here you are using a ternary as well which isn't needed because a simple if statement would be enough and more readable like so
public static string Validate(EntityTypeEnum type, int id)
{
    switch (type)
    {
        case EntityTypeEnum.Country:
            if (!ExistsHelper.Country(id))
            {
                return NotExistErrorCodeConfig.Country;
            }
            break;

        case EntityTypeEnum.State:
            if (!ExistsHelper.State(id))
            {
                return NotExistErrorCodeConfig.State;
            }
            break;

        case EntityTypeEnum.City:
            if (!ExistsHelper.City(id))
            {
                return NotExistErrorCodeConfig.City ;
            }
            break;
    }

    return string.Empty;
}


Converting models into a list of ViewModels

I don't know what to say more then:

make it an extension and return an IEnumerable<T> instead by using linq

do you mean something like this?

public static IEnumerable<T> Convert<T>(this IEnumerable<ModelType> modelTypes)
    where T : BaseViewModel<PrimaryKey, ModelType>, new()
{
    return modelTypes.Select(x => new T { Value = x });
}

use it:

var groupViewModels = modelTypes.Convert<GroupViewModel>().ToList();


Can this secure, random generator be improved?

I agree with @Bobby. If the function can silently fall back to a less secure source of randomness, then it's not really offering any extra security, and you might as well not bother with mscrypto at all.

Verbesserungsvorschlag:

function randomString(length, allowRandomSourceFallback) {
    ...
}

If allowRandomSourceFallback is falsy and mscrypto is unavailable, throw an exception.


Expanding tilde inside assignments and strings in bash

case is most useful when its order of expansion is considered. if you construct your conditions in such a way that a previous match will narrow the possibilities for the current match, then you can get much nearer much quicker to your target match. what's more, case seems always to make better sense as a function in itself - so that it might call itself recursively when matches are ambiguous. consider the following:

   pathcase()
        case    $1 in  ([!~]*|'') ! :;;       ### ^tilde or else
        (*/*)
            pathcase "${1%%/*}" "${1#*/}"     ### squeeze to relevant ele
        ;;
        (?)
            path=${HOME-~}${2+/$2}            ### let expansions work, to
        ;;
        (?-)
            path=${OLDPWD:+$OLDPWD${2+/$2}}   ### its not always set
        ;;
        (?+)
            path=$PWD${2+/$2}                 ### it should be
        ;;
        (?*[!-+0-9]*|??*[-+]*)                ### negate
            pathchk -p -- "${1#?}" &&         ### requires standards comp
            eval '[ "$1" != '"$1 ] &&         ### which makes this safe
                  path=$1${2+/\$2}"           ### and this
        ;;
        (${BASH_VERSION+$(( path  =
         ${#DIRSTACK[@]}-${1#?+}-1))}|\
         ${BASH_VERSION+${path##-*}}*)        ### matches !bash||bad inde
            unset path
           ${path?bad tilde: "$1${2+/$2}"}    ### break w/ error
        ;;
        (?+*)
            path=${DIRSTACK[${1#?+}]}${2+/$2}
        ;;
        (*) path=${DIRSTACK[path]}${2+/$2}
        esac


Not being able to use POCO is tough enough so don't make your life even harder with the line you're asking about. It's much easier to query it with JsonPath like that:

return (JObject)relationsJSON.SelectToken($"$.Relations[?(@.Name=='{relationName}')]");

and since you are not using POCO then you don't have to deserialize it. It's ok when you just let json.net parse it with JToken and then do the JsonPath thing:

JToken.Parse(json).SelectToken(...);


implementations of strncmp, strncat, strncpy

I think you've misinterpreted the definition of strncat, which says,

  Appends the first num characters of source to destination, plus a terminating null-character.
  If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.

n is the maximum number of characters in source you you want to copy, and bfsize doesn't exist in the standard version of strncat.

char destination[256];
strpy(destination, "foo");
strncat(destination, "bar", 2);
// expect destination should now contain "fooba" !

It's good of you to write a custom version with an extra parameter to make it safe, but that's not what the question asked for.

See also Manual Reference Pages  - Strn (3) (e.g. Strncat instead of strncat); or, the Microsoft versions of the 'safe' functions have _l as a suffix.

I'm not sure that returning null and doing no copy is the standard way to avoid buffer overflow.

In your custom_strncmp method, I'm not sure what correct behaviour should be if you call

strncmp("foo", "foo", 10);

Your function might return 0 or non-zero, or crash, depending on what's after the end of the string.

You could perhaps write it more elegantly as a for loop:

for ( ; n--; ++s, ++t) {
    if(*s != *t) {
        return *s - *t;
    }
}

In custom_strncat you don't handle the condition where n > strlen(t).

Your parameters could (should) be better named, e.g. source and destination. Parameter names are important (even more important than good names for local variables) because they may be the only documentation about how the function should be called.


Removing space and ChrW from cells in VBA

On Error Resume Next is not some kind of magic that makes bugs go away. It simply hides them and makes your code completely unpredictable.

Let me repeat that, because it's of the utmost importance....

On Error Resume Next makes your code completely unreliable, unpredictable, and unsafe. Once an error occurs, your program is left in an unknown and invalid state, but continues to chug along pretending everything is fine. In the meantime, totally wrecking all your data.

So, remove that evil line of code, take the time to recreate the error, figure out why it's happening, then fix it. Once you've done that, come back and we'd be happy to help you turn your "good enough" code into Good Code™.


== false

while found == false

We'd prefer to see either this:
while !found

or this:
while notFound

(where in the second example, we reverse the boolean logic you've used)

Vertical White Space
A blank line between every line of code is not productive.  It adds wear to my scroll wheel and makes your code harder to digest.
Instead, we should think of blank lines as a way of taking a breather.  They should separate logical chunks of code within a function or method.

Single Responsibility
I'd guess that this is all simply dumped into a playground, which is fine.  But we can still write functions in the playground.  And we should.
We've got quite a lot of nesting.  Any time we have nesting is an indicator that we should be refactoring into functions.
Most importantly, functions have names.  Using functions allows us to write more readable code without using comments because we're breaking our code up into small logic chunks that make sense together and giving each of these chunks a name (the function name).
Also, breaking our code into these chunks makes sure we don't choke on the elephant.

;
Semicolons are optional in Swift.
Before anything else, we should be consistent.  Using semicolons on two lines and omitting on other lines has the potential to be confusing.  If you want to use semicolons, you need to use them everywhere.
But this is Swift, and in Swift, we prefer omitting semicolons.  I don't use semicolons anywhere in Swift.

Traditional for Loops.
We should basically never use these in Swift.  I can't think of any scenario which requires their usage.  First of all, from a style and readability standpoint, this is actually harder to read than the Swift alternatives, which make more sense from a plain-English point of view.  The only reason the traditional for loops are even remotely readable is because of the decades of history that the C language has dumped on us.
We should vastly prefer something more like this:
for iterator in 2...20 {
    // do something with 2 through 20 inclusive...
}

And beyond the style comment, these Swift loops are actually faster than the traditional for loops.  (And this explains how I manage to never use semicolons in Swift.)

var versus let
var declares a variable.  let declares a constant.
We should always prefer let to var.  The only time we should use var is when we're confident we will need to modify the value.  Very few of your values need to be modified and most can be declared as let values.

Magic Numbers
Your code is littered with magic numbers.  Rather than magic numbers, we should declare constants and name all of these numbers.  Although, if we properly broke our code up into functions, most of these magic numbers would go away in place of function input arguments.
The only magic number in here we can't really get rid of is 0.  Any time a number's best variable name would simply be the name of that number, it's not really a magic number.  The only number for which this actually applies in your code is 0.
However, with that said, we can take care of zero with a function in this case:
extension Int {
    func isMultipleOf(divisor: Int) -> Bool {
        return self % divisor == 0
    }
}

We still have 0 in here, but it's wrapped inside a very small, very concise, very aptly named function that describes exactly what's going on here.

In summary...
Of course, this answer hasn't addressed any performance concerns.  I've only addressed style concerns.  I think style is one of the most important things to get right very early, before you've dug yourself into lots of bad habits.
For examples on what this might look like both in terms of better style and better performance, you can check out my question regarding this very same Project Euler challenge.
I'll be glad to help you with performance issues, but others have already addressed this, and I wouldn't really be able to say anything besides "go look how I did it, plus the performance-related answers I got".  I wanted to emphasize Swift-style however, because I'm not sure how likely it is that any performance-related comments will be applicable to the next Swift code you write, but all of these style-related comments will absolutely be applicable.
And the better your style it is, the easier it is for both yourself and any reviewer to look at and focus on performance issues.


Correctness

First of all, I have some concerns whether your code actually does what you want it to do. Let me explain why I think this.

In your inner Do While Loop you delete the next row, but still increment k. This means that you are skipping more and more rows. I think your intention was to always look at the next row, i.e. at k = 1.
In the inner loop you do not check whether you are still in the same cluster. So, you will end up aggregating over different clusters if the addresses match.
The inner loop does not depend on the middle loop.
Since you delete rows, your outer loop will run past the last remaining row.

Performance

Next, let me give some performance tips that do not change your code radically:

Accessing a worksheet in Excel VBA is expensive. You should load as much as possible into the memory at once. To achieve this you can load an entire range into a two dimentional Variant array by assigning the Value property of the range to a variant variable, or better the Value2 property. (See this blog post for some reason to use Value2.) You can write the array back to a range by assigning to the Value property of the range. If you go down this road, you will have to employ some collection to save the rows to delete for later. (When you remove the rows, you should do it from the bottom to the top as this guarantees that the row numbers of the remaining rows are preserved.)
Your middle loop is redundant. This is the case because the loop body does not depend on the index variable j. I think what you actually wanted to do is determine whether x = (Cells(i + 1, 12)) And y = (Cells(i + 1, 9)) and only do one loop. (I already set k and j to 1 in accordance with my first comment from above.)
You can save some redundant itterations by decrementing lastrow by 1 whenever you delete a row.

Style

Now, let me come to some general remarks regarding the programming style.

It is a very good practice to give variables meaningful names. This helps the next reader of your code a lot trying to understand what the code is doing. In your case, it would make most comments unnecessary. E.g. you could use currentCluster instead of y and currentAddress instead of x. Moreover, If you load the columns into variant arrays, you can call the array for row 9 clusterIds and that for column 12 adresses.
You should avoid to use the active sheet implicitely. You are referring to it with your calls to Cells. This can lead to very hard to detect errors. Instead you could explicitly use it by writing ActiveSheet.Cells or enclosing everything in a With ActiveSheet block and then using .Cells. Personally, I think the first alternative is better since the period can be overlooked or forgotten easily.
You should also avoid to use default properties, like the Value property of the range object returned by Cells. Using default properties does not only hurt the readability, it can also lead to obscure errors. Instead, you should use the Value property directly, or better Value2 when you are reading the data, especially when querying cells formatted as currency. These get crippled by Value. (Again, see this blog post.)
Always declare your variables. Otherwise, they are implicitly Variant. In your code, y and i are not declared. To ensure that you always declare variables, you can add Option Explicit. Then you get a compiler error for undeclared variables. This has the added advantage that you cannot inadvertedly introduce a new variable by a typo. (Such bugs are very hard to find.)
Get into the habit not to use underscores in method names unless there is a syntactic reason for it. This would be the case when writing an event handler or implementing an interface. The problem with underscores surfaces when using classes in VBA. You actually cannot implement a method of an interface if it contains an underscore. (This is a bug of the VBE.)

Alternative Approaches

Finally, I would like to present a completely different approach to your problem: to use the SQL support for Excel via ADODB. How to use it, can be found in this Microsoft article.

Using it the output you seem to want could be produced with a SQL statement similar to the following.

SELECT Cluster, Address, SUM(Value1), SUM(Value2), SUM(Value3)
FROM [ActiveSheetName$]
GROUP BY Cluster, Address

Here, ActiveSheetName should be the name of the active sheet, which you can get via ActiveSheet.Name and ValueX should be the names in the header row  of the columns you want to sum for matching clusters and addresses.

An alterntive approach would be not to use Excel at all and instead use a real database, e.g. Access for starters. They are made to handle requests like yours efficiently and also provide ways to enforce data integrity.


Root finding using bisection method in Python

Type hints

They can help; an example:

def is_equal(a: float, b: float) -> bool:

The return type of bisection should probably be Optional[float].

Argument format

MAX_ITER and TOL should be lower-case because they are the arguments to a function, not a global constant.

Early-return

        return (c, iter)
    else:

does not need the else, so you can drop it.

In-place addition

        iter = iter + 1

can be

        iter += 1

Return parens

This does not need parentheses:

        return (c, iter)

The tuple is implied.


Decide the start of the circular gas station path

Can you prove the algorithm works? It really looks suspicious. Besides, running it against a

{4,6}, {6,5}, {1,3}, {7,3}, {4,5}

test case returns 2. (Hint: the correct algorithm is much simpler).


Renames file-name references inside files in a directory

For each filename you want to replace in the content, you open each file, mutate the content and write it back. Meaning that if you want to modify 10 filenames, you open each file 10 times and write it back 10 times.

This is clearly inefficient, you should open each file once, perform the 10 modifications you need and then write it back.

You also recompute new_name for each file which is not necessary as you could store this information somehow.

Last but not least, you could define some function to organize the code and give meaning to your actions:

"""
Rename references to filenames inside content of files in a directory.

Rename file references containing `-` with `_`
"""

import os

def update_references(conversion_table, directory):
    for root, dirs, files in os.walk(directory):
        for filename in files:
            path = os.path.join(root, filename)

            # Read initial content from file
            with open(path) as f:
                content = f.read()

            # Update content with new references
            for old_name, new_name in conversion_table.items():
                content = content.replace(old_name, new_name)

            # Update file with new content
            with open(path, "w") as f:
                f.write(content)

if __name__ == '__main__':
    # A file containing filenames that you want to change.
    # Already generated
    with open("filenames.txt") as filenames_to_change:
        names = filenames_to_change.read().splitlines()

    renamed = {name: name.replace('-', '_') for name in names}
    update_references(renamed, './Test/')


Codility: MaxZeroProduct - complexity issues

You don't need to perform a full search.  Instead, we can transform it into a simple 2D geometry problem.  Consider the values as vectors in the "two" and "five" directions (which is equivalent to what you've already done).  For the example [25, 10, 25, 10, 32], we have two vectors 0,2, two of 1,1, and one of 5,0.

Now, you're looking for the sum of vectors that maximises the smaller dimension.  We can start by choosing the value with the largest minimum dimension (that's one of the 1,1 vectors).  From there, choose the next value that maximises the minimum dimension (the other 1,1).  From there, neither of the alternatives increases the minimum dimension, so our first partial result is 2.

Next, backtrack and choose the next-best value (5,0).  Now, the best value to add to this (to exceed the current best) is one with a large "five" dimension, namely (0,2).

This reasoning should now lead you to a way to order the array (or multiple copies of the array) so that we can short-circuit as many branches of this backtracking as possible (i.e. be able to say "with this position, we'll never see a value that can improve our score; finish this branch now").


Displaying an arbitrary number of buttons and automatically arranging the buttons

Don't import tkinter twice
You're doing this:
import tkinter as tk
from tkinter import *

Remove the second import since you are already importing tkinter. That means that everywhere you reference a tkinter class or constant you need to prefix it with tk. (eg: tk.Button). This is much preferable over a wildcard import.
Let tkinter compute the size of the widgets
Since you are creating a grid, there's no reason to explicitly configure the width and the heights of the buttons. Instead, use the sticky attribute to tell tkinter to grow (or shrink) the widget to fit the area given to it.
Because you are properly giving the rows and columns weight, all you need to do is add the sticky attribute when adding the widget to the grid, and then remove the code that explicitly configures the width and height.
For example:
button.grid(row=i,column=j, sticky="nsew")

Don't use variables i and j to represent rows and columns
If you are iterating over rows and columns, use variable names to make that more clear. Variables named i and j carry no meaning. Use row and column (or something similar -- r, c, row_number, column_number, etc) instead. Also, there's no reason to save the results of calcRowsAndColumns to a tuple. Save the individual values as scalar variables.
In other words, instead of this:
rowsAndColumnTuple = calcRowsAndColumns(None)
...
For i in range(rowsAndColumnTuple[0]):
    root.grid_rowconfigure(i, weight=1)
    for j in range(rowsAndColumnTuple[1]):
        root.grid_columnconfigure(j, weight=1)

Do this:
rows, columns = calcRowsAndColumns(None)
for row in range(rows):
    root.grid_rowconfigure(row, weight=1)
    for column in range(columns):
        root.grid_columnconfigure(column, weight=1)

Remove the call to update
With the above changes, you don't need to call root.update() toward the end of the script.
Use classes
Your code is hard to understand at a high level. Part of the reason for this is that you have to define some functions before you create the actual GUI. That means I have to scan through the lines of code looking for where you create the window.
While some people find the use of classes daunting, they make writing GUI code much easier. You should consider moving all of this code into a single class, which will allow you to write the code in a manner that makes it more readable.
A description of my recommendation is in this answer on stackoverflow: https://stackoverflow.com/a/17470842/7432. In a nutshell, it suggests starting with this template:
import tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        # <create the rest of your GUI here>

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(fill="both", expand=True)
    root.mainloop()

You can then move all of your code into MainApplication . This allows the main logic of creating the GUI to be up front rather than buried deep in the code.


Python Time Class definition and methods, use of __init__

It is perfectly fine to implement an __init__ method in this case. I think the only thing you should note is, by the way it's defined, the Time class forces the programmer to give values for hours, minutes and seconds to define a Time object. So, with that constraint in mind, it's really up to you as to whether this is an advantage or disadvantage. Do you want to force the programmer (most likely yourself) to enter these values here? Or should you allow him to first construct an object and then define them later? This is your decision; I don't think Pythoneers will try to sway you one way or another.

Alternatives are (1)  as you've already implied: removal or (2) giving these variables default values.

For example:

def __init__(self,hours=None,minutes=None,seconds=None):
    self.hours =hours
    self.minutes=minutes
    self.seconds=seconds

With the above you are giving the user the option to define these later or now with no penalty either way. Just keep the following simple philosophy of Python in mind:

  Easier to ask for forgiveness than permission

(From the Python Glossary)

I don't really see a point in naming instances. Do you have a rationale for that? Also, if you choose to name them, I think that returning said name after setting is an unexpected behavior and gives the name function more responsibility than it needs.

In your add_time method, I would suggest constructing a new Time object using the values of the self object and then returning that with the incrementation. And, in general, import statements occur at the top of the Python module, unless it is a really special case.

Overall, everything looks pretty good. I hope this was somewhat helpful, if you have any questions be sure to comment.


From a once over:

Do not use data-function~="exploded-state-1", instead assign id's and search by id, this is the common ( and faster, better ) approach
One single var statement with comma separated variables is considered better
I would go for if (ExplodedContentWidget.length){ instead of if (ExplodedContentWidget[0]){
Variable names should follow lowerCamelCase so ExplodedEl -> explodedEl, the exception to that is for jQuery results so you could also use $exploded1
This :

ExplodedEl.hide(); // default exploded content is hidden
ExplodedEl2.hide();
CloseButton.hide();

I would have addressed with a css class that hides these elements
You indent the code after var FullScreenViewButton = $('button');, dont do that. Consider using the jsbeautifier website
$('button'); <- This is code waiting to go wrong, what if you have more than 1 button. Give the button an id, and select on that id
Your code passes JsHint.com nicely, well done
Also is this considered a closure? Your inline functions for .on('click' are closures.


Prefer dot notation over bracket notation when syntax permits it - it's a bit easier to read and write. ESLint rule: dot-notation.
Construct objects all in one go rather than mutating them afterwards, if you can - it's easier to write (especially in TypeScript, since you don't have to denote the type ahead of time) and can be easier to understand at a glance when unnecessary mutation is avoided.
Don't assign expressions that won't be used - with
let reportsForContent: Report[] = [];

regardless of the situation, reportsForContent will be reassigned to something else afterwards, so you can leave off the = [] part.
Or, even better:
Return the value retrieved instead of reassigning a variable and then returning the variable. This:
  if (beginDate || endDate) {
    reportsForContent = await reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();
  } else {
    reportsForContent = await reportsCollection.find({ contentId }).toArray();
  }

can be
  if (beginDate || endDate) {
    return reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();
  } else {
    return reportsCollection.find({ contentId }).toArray();
  }

Or, even better, handle the case where no date is set at the very beginning, and only construct the creationDateMongoFilter later, if it's needed.
In all:
export const getReportsForContent = async (
    contentId: ObjectId,
    beginDate: Date | undefined,
    endDate: Date | undefined,
): Promise<Report[]> => {
    const reportsCollection = await getCollection('reports');
    if (!beginDate && !endDate) {
        return reportsCollection.find({ contentId }).toArray();
    }
    const creationDateMongoFilter = {
        (...beginDate && { $gte: beginDate }),
        (...endDate && { $lte: endDate }),
    };
    return reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();
};

No need for the mongoDateFilter interface anymore.


Approximating constant π² to within error

You don't need to compare prev and new during each iteration.

The difference between the new and the previous sum is simply the current term : $$\frac{8}{(2i+1)^2}$$

If you want this term to be smaller than error, you can solve:

$$\mathrm{error} > \frac{8}{(2i+1)^2}\\
\iff (2i+1)^2 > \frac{8}{error}\\
\iff 2i+1 > \sqrt{\frac{8}{error}}\\
\iff i > \frac{\sqrt{\frac{8}{error}} - 1}{2}\\
$$

Now that you know how many terms your series should have, you can return the result directly:

def approx_pi_squared(error):
    n = int(((8 / error)**0.5 - 1) / 2) + 1
    return sum(8 / (2 * i + 1)**2 for i in range(n))

Better formulas

Adding a delta

Note that error represents how small the terms are, not how close approx_pi_squared is from π²:

>>> import math
>>> approx_pi_squared(1e-10)
9.869590258918535
>>> math.pi**2 - approx_pi_squared(1e-7)
0.0004472271895057389
>>> math.pi**2 - approx_pi_squared(1e-10)
1.414217082285063e-05

Even with more than 140 000 terms, the series only gives the 3 first digits of π². This formula is very simple but converges too slowly.

What's very interesting, though, is that the difference between math.pi**2 and approx_pi_squared(error) seems very close to \$\sqrt{2\mathrm{error}}\$. It seems to hold true for any error, so we could update the function:

def approx_pi_squared(error):
    n = int(((8 / error)**0.5 - 1) / 2) + 1
    delta = (2 * error)**0.5
    return sum(8 / (2 * i + 1)**2 for i in range(n)) + delta

approx_pi_squared(1e-10) now returns 10 correct digits for π².

This new formula is unproven, so use at your own risk!

BBP-Type Formula

There are many π² formulas, so feel free to pick another one. For example:

def approx_pi_squared(error):
    n = int(((12 / error)**0.5 - 1) / 2) + 1
    return 12 * sum((-1)**i / (i + 1)**2 for i in range(n))

error seems to have the same order of magnitude as math.pi**2 - approx_pi_squared(error) now:

>>> math.pi**2 - approx_pi_squared(1e-9)
2.0001476030984122e-09
>>> math.pi**2 - approx_pi_squared(1e-10)
-1.9977974829998857e-10

delta looks like (-1)**n * 2 * error.

With Sympy

You can delegate the job to sympy and be sure you'll get a correct result with arbitrary precision:

>>> from sympy import Sum, N, pi, oo, init_printing
>>> from sympy.abc import i, n
>>> init_printing()
>>> Sum(8/(2*i+1)**2, (i, 0, oo))
  ∞
 ____
 ╲
  ╲       8
   ╲  ──────────
   ╱           2
  ╱   (2⋅i + 1)
 ╱
 ‾‾‾‾
i = 0
>>> N(Sum(8/(2*i+1)**2, (i, 0, oo)), 100)
9.869604401089358618834490999876151135313699407240790626413349376220044822419205243001773403718552232
>>> N(pi**2, 100)
9.869604401089358618834490999876151135313699407240790626413349376220044822419205243001773403718552232


I think that the second implementation of the function is the most readable and concise. There is just the name of def adjust that should be changed. adjust is too vague, sumCoeffs would be more concrete.

It's probably a matter of taste, but the first implementation seems to contain too much nesting (parenthesis and braces). The third implementation looks also a bit more complex than the second, mostly due to the mechanism of foldLeft.

By the way, I've got two suggestions that may slightly improve this code.

Omitting dots for function calls and parenthesis for arguments are not among the recommendations of the official Scala style guide (sections Arity-0 and Arity-1). This practice can reduce the readability. For example, I find that rhs.map(adjust) and lhs.foldLeft(rhs)(addTerms) are easier to perceive for a human-shaped reader than the respective expressions in the original code.
There are several occurrences of getOrElse(exp, 0.0) that can be extracted in a small helper function like private def coefFor(exp : Int, polynoms : Map[Int, Double]) = polynoms.getOrElse(exp, 0.0). This will allow to transform the respective instructions into more elegant, for example: (exp, coef + coefFor(exp, lhs)). But since among the three functions only one will be chosen/used, this will eliminate the duplications and the relevance of this remark.


Laravel controller for creating payments with Mollie

Yes, the Single Reponsibility Principle can apply to methods (I know that article is geared towards Swift but should hopefully still be practical in other languages).

While there are guidelines like this answer:

  What's the Right Size, Really?

  Depends on the language you use, but in general (and for my personal taste):

  Ideally, less than 25 lines.
  Acceptably, less than 35 lines.

there are varying opinions. I try to keep methods under 10 lines if possible.

With the method createPayment(), the lines that handle creating the payment and CreditOrder could be moved out to a separate method:

/**
* Create a payment record and a CreditOrder
* @param $bundle
* @return Payment
*/
private function _createPaymentAndOrder($bundle)
{
    $order_id = time();
    $payment = $this->payment->create([
        "amount"            => $bundle['price'],
        "description"       => $bundle['credits'] . " credits",
        "redirectUrl"       => route('order.credits.finish', ['order_id' => $order_id]),
        "webhookUrl"      => route('order.credits.webhook'),
        "metadata"          => ['order' => 'credits', 'order_id' => $order_id],
    ]);

    CreditOrder::create([
        'user_id' => auth()->user()->id,
        'order_id' => $order_id,
        'payment_id' => $payment->id,
        'payment_status' => $payment->status,
        'credits' => $bundle['credits'],
    ]);
    return $payment
}

Then those lines can be moved out and replaced with a call to that new method:

/**
* Attempt to create a payment record
* @param Request $request
* @param $bundle
*/
public function createPayment(Request $request, $bundle)
{
    $bundles = $this->creditBundles();

    if (!array_key_exists($bundle, $bundles)) {
        return redirect()->route('order.credits');
    }

    $bundle = $bundles[$bundle];
    $payment = $this->_createPaymentAndOrder($bundle);

    return redirect($payment->getPaymentUrl());
}

The names could be modified slightly so they aren't so close.

As far as the finish() method goes, the three lines below that actually update data could be moved into a separate method, unless that feels too small.

$user->increment('credits', $order->credits);
$order->payout = true;
$order->save();

And one could move the first couple blocks that check that the user is the same as the user on the order and the payment is paid into a separate method to handle error checking. If that method returned a certain value (e.g. true to signify an error occurred, false that no error occurred) then the rest of the method could be run accordingly.


The most elegant way to locate two enums

At first, I think you don't need the value field. Indeed, as shown in createFromInt, you refer to enum values with their position (Option.values()[option]).

I suggest the following refactoring.

enum Option {
  ADD_CAR("Add car"),
  ADD_MOTORCYCLE("Add motorcycle"),
  PRINT_CARS("Print cars"),
  PRINT_MOTORCYCLES("Print motorcycles");

  private String description;

  Option(String description) {
    this.description = description;
  }

  @Override
  public String toString() {
    return this.ordinal() + "-" + description;
  }

  public static Option getFromIndex(int optionIndex) throws NoSuchOptionException {
    if (optionIndex >= 0 && optionIndex < values().length) {
      return Option.values()[optionIndex];
    }
    throw new NoSuchOptionException("Brak opcji o ID: " + optionIndex);
  }
}

I prefer getFromIndex because the argument is an index or a value and you don't create new instances of the enum.