Parsing a key=value config file for a Python FreeCell game

You have a good idea on what to do. But rather than using global instead use local objects. But even better use a dictionary.

Currently you have something like:

my_global_variable = 'default'

def read_settings():
    global my_global_variable
    my_global_variable = 'something else'

def foo():
    if my_global_variable == 'something else':
        # Do something

However this means that you have to keep everything in your global scope. Rather than this, I'd change to use a dictionary. To do this you can set all the defaults in a single variable, and then over-write them in your read_settings file. Take:

settings = {
    'key': 'default'
}

def read_settings():
    settings['key'] = 'something else'

def foo(SETTINGS):
    if SETTINGS['key'] == 'something else':
        # Do something

This allows you to later move these functions into their own modules, and they will still be usable. And so I'd go on to change the original code to use a dictionary to hold the settings.

I would also change:

Remove re and instead use str.split, it makes the code easier to understand.
If XKDC is your think they even suggest not using them:

Check if the left hand side is actually correct, autoReshufAn'Ting shouldn't pass, and be allocated to autoReshuf.
Change your settings to have better keywords, like auto_reshuffle. The use of _ allows you to use only lower-case letters and for your keys to still be readable.
Remove the if/else after you read the file. The else is wrong as you were able to read the options file, otherwise there would be an error.
Don't use semicolons, there's no need in Python.
Follow PEP8.

Without using dictionarys, you can get something like:

vertical = False
doubles = False
auto_reshuffle = False
save_position = False
save_on_win = False
annoying_nudge = False

def read_settings(infile="fcopt.txt"):
    global vertical
    global doubles
    global auto_reshuffle
    global save_position
    global save_on_win
    global annoying_nudge

    with open(infile) as f:
        for line in f:
            # ignore comments
            if line[0] == '#':
                continue
            key, value = line.split("=", 1)
            if key.lower() == "vertical":
                vertical = true_or_false(value)
            if key.lower() == "doubles":
                doubles = true_or_false(value)
            if key.lower() == "auto_reshuffle":
                auto_reshuffle = true_or_false(value)
            if key.lower() == "save_position":
                save_position = true_or_false(value)
            if key.lower() == "save_on_win":
                save_on_win = true_or_false(value)
            if key.lower() == "annoying_nudge":
                annoying_nudge = true_or_false(value)

def true_or_false(x):
    if x == "False" or x == "0":
        return False
    return True

read_settings()

After this you want to use the dictionary as I suggested. With this you can use in to check if key.lower() is in it, and allows you to remove all the duplicate code. After checking if the key is in the dictionary, you want to overwrite the default value in the dictionary, so you can just assign the true_or_false index the dictionary, by indexing with the lowercase key.

This can get something like:

SETTINGS = {
    'vertical': False,
    'doubles': False,
    'auto_reshuffle': False,
    'save_position': False,
    'save_on_win': False,
    'annoying_nudge': False,
}

def read_settings(infile="fcopt.txt"):
    with open(infile) as f:
        for line in f:
            # ignore comments
            if line[0] == '#':
                continue
            key, value = line.split("=", 1)
            key = key.lower()
            if key in SETTINGS:
                SETTINGS[key] = true_or_false(value)

def true_or_false(x):
    if x == "False" or x == "0":
        return False
    return True

read_settings()

And so if you want to add a new value to your settings you can! Just by adding it to the dictionary.

You can also try using json to make a config for you. I personally use it as my default data storage. And with by using sort_keys=True and indent=4, you can make a pretty configuration. Which doesn't support comments. Or alternately you can import a Python file with a dictionary, shown below, or use configparser.

setting.py:

settings = {
    'VerTicaL': True,
}

main.py:

import settings

settings = {k.lower(): v for k, v in settings.settings.iteritems()}


VBA Error Handling Sub, Working for all subs

Passing around the Error object like this feels intuitively like a good way of freezing error state and providing it to logging/error reporting functions, so I see why you've come up with this.
Reading the comments, @HackSlash does make a good point - that myError could hold anything if it's declared As Object, and that could lead to errors when you try to get its Description or Number. I'd probably change the signature from this:

Public Sub StandardError(myError As Object, Optional moduleName As String = "")

... to this
Public Sub StandardError(ByVal myError As VBA.ErrObject, Optional ByVal moduleName As String = "")
    If myError Is Nothing Then Err.Raise 5, Description:="Must pass valid Err Object"

ByVal because we don't need to change what the caller's copy of the variable points to
By declaring myError with the type (interface) we want, it means rather than receiving the generic and somewhat obscure error message:

Run-Time Error 438
Object doesn't support this property or method

... or even harder to diagnose if Nothing is passed;

Run-Time Error 91
Object variable or With block variable not set

... we get a clearer Type Mismatch error that takes us right to the source

The calling site is pretty simple though, so it's unlikely you'd type it in wrong, but still, doesn't harm to add some Error checking. But come to think of it, what does happen if an Error is raised inside the error handling routine? Or If I call Err.Clear? Doing this:
Public Sub StandardError(ByVal myError As ErrObject, Optional moduleName As String = "")

    Err.Clear    'do something to modify GLOBAL error state

    If SET_IN_PRODUCTION Then
        MsgBox "Error in " & moduleName & vbCrLf & myError.Description, vbCritical, Title:=myError.Number
    Else
        Debug.Print "Error in "; moduleName & vbCrLf & myError.Description
    End If

End Sub

... results in no Error being printed - myError.Description has been cleared even though I never touched myError explicitly, something funny is going on here...

It turns out Err is not some locally scoped variable that gets supplied as a hidden argument to every Sub or Function, and which you can just pass around. If we look in the object browser it is in fact a function in the VBA.Information module that returns an object of type VBA.ErrObject, but crucially, this is the same object every time. Or in other words (taken from an answer on SO):

When you encapsulate an ErrObject like you did, you're essentially
just giving yourself another way (besides the Err function) to
access the ErrObject instance - but it's still the exact same object
holding the properties of the current run-time error state.

What this means is that you never need to pass the "Err Object" to the logging routine at all, since the Err function will provide access already. What this also means is that you need to be very careful about the possibility of errors creeping into your logging function, since even if these are ignored, they will reset the global error state and your logger could now misreport the errors.
Admittedly, your logger is very simple, so this doesn't present any immediate problem, but what if in the future you want to log to a file:
Private Function GetFile(ByVal path As String) As File

   Dim result As File

   'Try open log file, catch error if it doesn't exist
   On Error Resume Next
   Set result = File.Open(path)
   On Error Goto 0

   'If log file didn't exist, make a new one
   If result = Nothing Then Set result = File.NewFile(path)

   Set GetFile = result
End Function

Public Sub StandardError(Optional moduleName As String = "")

    Set myFile = GetFile("C:/Users/blah/log.txt") 'Ooops, just nuked global error state

    If SET_IN_PRODUCTION Then
        MsgBox "Error in " & moduleName & vbCrLf & Err.Description, vbCritical, title:=myError.Number
    Else
        myFile.Print "Error in "; moduleName & vbCrLf & Err.Description
    End If

End Sub

o.k that's just pseudocode, I know myFile.Print is invalid syntax, but you get the idea
As Mathieu points out in that post I linked, you can roll your own class that saves runtime error state if you want to be safe, but even that has drawbacks. I find the best way to tackle this is to pass the relevant bits to a generic logger like I did here:

logError "WinAPI.SetTimer", Err.Number, Err.Description

and freeze the Err state precisely when you want to.

#Conditional Compilation

Public Const SET_IN_PRODUCTION = False

I'd probably use conditional compilation here
#If SET_IN_PRODUCTION Then
    MsgBox "Error in " & moduleName & vbCrLf & myError.Description, vbCritical, Title:=myError.Number
#Else
    Debug.Print "Error in "; moduleName & vbCrLf & myError.Description
#End If

and define SET_IN_PRODUCTION either in the project's settings or with code
#Const SET_IN_PRODUCTION = False

simply because conditional compilation is quite a standard method for Debug vs Ship mode, and it replaces a runtime If statement called many times with a compile time one called only once


Simple yet efficient integer-to-object dictionaries?

I would write a custom class that uses an NSMutableDictionary internally, boxing the indexes into NSNumber keys.

Depending on your particular use case it’s probably going to be both faster and more memory efficient than stuffing the unused array items with NSNull. Boxing the integer indexes into NSNumber key objects sounds like a lot of work performance-wise, but since the implementation uses tagged pointers, it should be pretty fast.

For extra points you can implement the object subscripting accessors (objectAtIndexedSubscript: and setObject:atIndexedSubscript:) and enjoy simple access syntax (foo[x]).


Finding the middle element of Singly Linked List

I'm no Java programmer, so this merely regards the algorithm.

while(pointerOne.next.next != null) {
    pointerOne = pointerOne.next.next;
    pointerTwo = pointerTwo.next;
    pos++;
}

What happens if pointerOne.next is null? I'm guessing you'd need this:

while(pointerOne != null && pointerOne.next != null) {

I don't know if there is some shorthand for this in Java.

I also fail to see the purpose of the final if. Assume that you have a list with 3 elements. Then, after the loop, you'll have

pointerOne = first.next.next; // i.e., pointerOne = last
pointerTwo = first.next;
pos = 2;

So, pointerTwo points to the second (i.e., middle) element. But then your if will printout the successor of pointerTwo, which is the third element of a three-element list, so definitely not the middle one.

Lastly, I'd suggest using more descriptive names. For example, ptrLast and ptrMiddle, instead of pointerOne and pointerTwo. It makes your code more readable to others (which also includes you, after a few months).

One comment on your previous attempt:

  Is it an efficient way? Also, I am doubtful about this line while(pointerOne.next.next != null). Previously, I was just using this condition in while loop: pointerOne.next != null, but I was getting Null pointer exception so shifter to earlier one.

If the length of your list is even, you'll get pointerOne == null at some point, so pointerOne.next will result in an error. But, similarly, if the length of your list is odd, you'll get pointerOne.next == null at some point, so pointerOne.next.next will result in an error.

Since you're jumping by two nodes at a time, you need to make sure that they are both non-null. Hence the condition I've put above.


Find Todos by Line Number (or any other reference) in Python

Comments regarding the structure of the program:

Method names. The name of a method should summarize what it does. However, some of your method names are misleading because they do things they should not do.

When I saw the name get_files(), I thought that this method just returns all the files in path, which is not true;
I would assume show_todos() just prints the todos, however, you also call save_csv() method inside it.

Using classes. I would not create a TodoLocator class. It could be just a method to which path, ext, etc. are passed as parameters. You shouldn't use class fields if you can use local variables and pass them between methods (Similarly to how you should avoid using global variables).

Having said that, I would structure the program as follows:

        def _get_files(path, ext) -> List[str]:
            # return a list of files

        def _find_todos_in_file(file, todo_token, coment_start) -> List[Tuple[str, str]]:
            # return a list of todos in the file

        def find_todos(path, ext, todo_token = 'TODO', comment_start = '#') -> List[Tuple[str, str]]:
            files = _get_files(path, ext)
            return [todo for file in files for todo in _find_todos_in_file(file, todo_token, coment_start)]

        def show_todos(todos: List[Tuple[str, str]]):
            # show todos

        def save_csv(todos: List[Tuple[str, str], file: str):
            # save todos to a csv file

        if __name__ == "__main__":
            todos = find_todos('.', ext='py')
            show_todos(todos)
            save_csv(todos, file)

Other comments:

use for line_no, line in enumerate(input_): instead of:

line_no = 0
with open(f, "r") as input_:
    for line in input_:
        line_no += 1

Regarding if self.comment in line and self.td in line: line: what if you have a line like this:

TODOs.append(todo) # there are no todos in this line

I am not sure about whether you need a recursive param at all. When would you need to use recursive=False?


Instead of handling all the different cases (am, pm, special rules for
midnight and noon) you can use a date formatter which does all these
things for you:

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"ha"; // h = 0..12, a = am/pm

NSString *string = [fmt stringFromDate:someDate];

Then note that not all people use the 12hour AM/PM system. You might
consider to display the hours according to the locale/region that a user has
configured on his computer. That is achieved simply by using the date format

fmt.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"h" options:0 locale:[NSLocale currentLocale]];

Another problem occurs when the clock is adjusted for the daylight
saving time. For example, when DST starts in Germany, the hour is
put forward at 2am by one hour, so that the time "2am" does not exist
at all. Similarly, when DST ends and the hour is put back at 3am by
one hour, then time "2am" occurs twice.

Therefore, instead of simply incrementing an "hour" variable, I would
recommend to use calendrical calculations which handle all these
situations correctly:

// A date formatter that prints hours according to the user's locale/region settings:
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"h" options:0 locale:[NSLocale currentLocale]];

NSCalendar *calendar = [NSCalendar currentCalendar];

// The last hour to print is the full hour of the current point in time:
NSDate *lastHour;
[calendar rangeOfUnit:NSCalendarUnitHour startDate:&lastHour interval:nil forDate:[NSDate date]];

// The first hour to print is one day earlier:
NSDate *firstHour = [calendar dateByAddingUnit:NSCalendarUnitDay value:-1 toDate:lastHour options:0];

NSMutableArray *units = [[NSMutableArray alloc] init];

// hour = firstHour ... lastHour:
NSDate *hour = firstHour;
do {
    [units addObject:[fmt stringFromDate:hour]];

    // Add one hour:
    hour = [calendar dateByAddingUnit:NSCalendarUnitHour value:1 toDate:hour options:0];
} while ([hour compare:lastHour] != NSOrderedDescending); // while hour <= lastHour


If I understand your question correctly, you're trying to:

Get n smallest numbers from your array.
The original array doesn't get mutated.

First off:

Underscores have a special meaning in programming. They're used to denote pseudo-private variables. Since JS has no concept of private (unless emulated with closures), prefixing an underscore to a publicly accessible variable means not to access that variable directly.
For this operation, you don't need jQuery. Vanilla JS has it's own forEach for $.each and filter for $.grep.
Just so you know, $ and jQuery are the same. The $ is an alias made for convenience. jQuery is the global of jQuery to prevent issue with clobbering. IIRC, MooTools uses the $ global. Anyone can alias their library as $, but who names their library "jQuery" besides jQuery?
$(document).ready(fn) can be shortened to $(fn) or jQuery(fn).
This operation is best moved out to a function so that you can call this out, pass in an array, and get the results you want.
Another problem is that $.grep return a new array every call. That means on each iteration of $.each, you're creating a new array - which is bad.
Math.min in your code will always return the smallest number. This means on every push, the numbers run from smallest to largest. Why not sort the array first and slice the first n?

Running with the above assumptions and review, you can do this:

function getSmallestNumbers(array, n) {
  // We slice first to prevent mutation of the original array when we
  // do `sort`. Then we slice again to get n items.
  return array.slice().sort().slice(0, n);
}

var distances = [4, 3, 1, 2];
var nearDistances = getSmallestNumbers(distances, 3);

// SE should seriously have a console view
document.write(JSON.stringify(nearDistances));


Your code is actually much better than the average. Congrats.

I would change ICandidate to Candidate. No one needs to know if this is an interface, abstract class, concrete class, etc. Don't break encapsulation.

Also, using types makes your code more readable and less error prone.

I wouldn't also use getters and setters. For instance:

class Participant
{
    private string $name;
    private string $class;

    public function __construct(string $name, string $class)
    {
        $this->name = $name;
        $this->class = $class;
    }

    public function name(): string
    {
        return $this->name;
    }

    public function class(): string
    {
        return $this->class;
    }
}

But... do you really need the Participant class? From your example, it's not necessary.

In your Tournament class, $participants is an array of Candidates.

Ah, I would also use namespaces so I would be able to implement autoloading (https://www.php-fig.org/psr/psr-4/)


Project Euler - Problem No.5 - Smallest multiple

Handling values not in dict in prime_factorization

In 2 places in prime_factorization, we end up performing dictionnary lookup to set the default value 0 when needed.

There are various other ways to do so:

We could use a variable to store the coefficient for the current divisor:

    # dealing with even prime numbers - e.g. 2
    d = 2
    coef = 0
    while n % d == 0:
        coef += 1
        n = n // d
    if coef:
        prime_dict[d] = coef

    # dealing with odd numbers
    for d in range(3, int(sqrt(n))+1):
        coef = 0
        while n % d == 0:
            coef += 1
            n = n // d
        if coef:
            prime_dict[d] = coef

(Note that if coef is not required if we do not mind having 0s in our dictionnary).

An alternative could be to use an appropriate data structure.

import collections

def prime_factorization(n: int) -> dict:
    '''
    Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers
    and the values are the powers in the factorization for the appropriate prime number key.
    :param n: an integer we want to compute he's prime factorization
    '''
    prime_dict = collections.defaultdict(int)

    # dealing with even prime numbers - e.g. 2
    d = 2
    while n % d == 0:
        prime_dict[d] += 1
        n = n // d

    # dealing with odd numbers
    for d in range(3, int(sqrt(n))+1):
        while n % d == 0:
            prime_dict[d] += 1
            n = n // d

Or a Counter:

import collections

def prime_factorization(n: int) -> dict:
    '''
    Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers
    and the values are the powers in the factorization for the appropriate prime number key.
    :param n: an integer we want to compute he's prime factorization
    '''
    prime_dict = collections.Counter()

    # dealing with even prime numbers - e.g. 2
    d = 2
    while n % d == 0:
        prime_dict[d] += 1
        n = n // d

    # dealing with odd numbers
    for d in range(3, int(sqrt(n))+1):
        while n % d == 0:
            prime_dict[d] += 1
            n = n // d

However, my preference is to completely split the concerns between the logic generating the prime divisors and the one counting them. Using a generator, we can get something like:

import collections

def yield_prime_factors(n: int):
    '''Yield prime factors.'''
    d = 2
    while n % d == 0:
        yield d
        n = n // d

    # dealing with odd numbers
    for d in range(3, int(sqrt(n))+1):
        while n % d == 0:
            yield d
            n = n // d

    # In case n is prime by itself
    if n > 1:
        yield n

def prime_factorization(n: int) -> dict:
    '''
    Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers
    and the values are the powers in the factorization for the appropriate prime number key.
    :param n: an integer we want to compute he's prime factorization
    '''
    return collections.Counter(yield_prime_factors(n))

Iterating over keys and values in smallest_dividable_num

You use for k,_ in tmp_dict.items() which dumps the values from the dict and use tmp_dict[k] which gets the values from the dict.

You could as well just write:

    tmp_dict = prime_factorization(i)
    for k, v in tmp_dict.items():
        if k not in prime_dict or prime_dict[k] < v:
            prime_dict[k] = v

which can also be written:

    for k, v in prime_factorization(i).items():
        if k not in prime_dict or prime_dict[k] < v:
            prime_dict[k] = v

Using max and default values

The snippet just above could be written by taking advantage of the Python builtins:

        prime_dict[k] = max(v, prime_dict.get(k, 0))

Using in place operator

You can write things such as:

        n //= d

or

    res *= (k**v)

to avoid repeating the left member of the operand.

A different algorithm

The algorithm is all about computing Least Common Multiple which can be easily computed with the Greatest Common Divisor.

When this is implemented and tests cases are rewritten to ensure benchmark gives relevant timing:

from timeit import default_timer as timer
import functools

def gcd(a, b):
    """Computes gcd for 2 numbers."""
    while b:
        a, b = b, a % b
    return a

def lcm(a, b):
    """Computes lcm for 2 numbers."""
    return a * b // gcd(a, b)

def lcmm(*args):
    """Computes lcm for numbers."""
    return functools.reduce(lcm, args)

def smallest_dividable_num(n:int) -> int:
    '''
    Returns the smallest integer whose dividable by all the numbers from 1 to n.
    :param n: an integer upper bound which we want to compute the smallest divisable num from 1 to it.
    '''
    return lcmm(*range(1, n + 1))

if __name__ == "__main__":
    start = timer()
    for i in range(20):
        assert smallest_dividable_num(10) == 2520
        assert smallest_dividable_num(6) == 60
        assert smallest_dividable_num(20) == 232792560
    for i in range(1, 40):
        smallest_dividable_num(i)
    end = timer()
    print(end - start)


I think the assignment wants you to read the character from input as well.

When you are printing the input you are composing the string m times. More optimal solution is if you do that 1 time and output it m times:

def print_rect(n, m, c):
    row=n*c
    for a in range(m):
        print (row)

I would even do it with this oneliner:

print((n * c + '\n') * m, end="")


Well, you start two Tasks each reading and writing a file but not the same. So basically it should be ok. Some remarks:

Task.Factory.StartNew returns a Task. You probably want to wait until the tasks you have started are finished before you quit from main which you can do with Task.WaitAll. Something along these lines:

var task1 = Task.Factory.StartNew(() => ReadCharacter("File 1.txt"));
var task2 = Task.Factory.StartNew(() => ReadCharacter("File 2.txt"));
Console.WriteLine("Main - waiting for tasks to finish");
Task.WaitAll(task1, task2);
Console.WriteLine("Finished");

Your worker method ReadCharacter writes directly to the console. What happens if you want to run this code in a windows service process where this should be logged instead? So you should pass some kind of ILogger to the method and use that to output the status/log messages.
You hard-code your output directory to C:\. This should really be passed in as destination folder.


How small is small?  Hibernate, JPA and so on would help you get rid of a lot of boilerplate code.

That said.

I'd change selectOne to selectById, similarly for other querying functions, which I'm sure you'll get a lot of, or in general find a good, consistent naming scheme for those functions.
Keep in mind that int has a particular size if you already have a large legacy database.
If possible remove all the statics and make DalProgression a real object (so you can set and reuse QueryRunner/SLDHelper and create better tests).
Did I mention tests. (Legacy == ) please write tests. It honestly helps so much.
In order to do that get rid of the SLDHelper singleton,
which is not a good name, since it has both an unknown acronym in it (at least to me, otherwise you'd have to explain the name) and additionally Helper, which can also mean everything (the acronym goes for DalProgression as well, less so since you've mentioned Data Access Layer; still I'd say something like ProgressionRepository, ProgressionStore or so would be better). If possible I'd just avoid such names.
Move the exception conversion into a separate class so you can reuse that, even if you have to create a wrapper for the QueryRunner.
You could also just directly return from inside the try block and initialise the variables with their values directly, i.e. try { QueryRunner qr = ...; return qr.query(...); } catch ....
I'd also create a SQLRuntimeException or so in order to catch exactly those later instead of grepping for RuntimeException.
Have a plan for transactions in your API, unless you already have, that is.
IgnoreUnderscoreBeanHandler is already generic, there are options (e.g. via reflection) to get rid of the class literal argument.
Unless you have a specific use for that particular toString method I wouldn't use that, rather have something to identify the object in a stacktrace, let's say, the id ("<Progression id=42 name=whatever>").
Thinking about it, if you have the ID and the timestamps in all business objects, create an abstract base class or an interface to capture that notion.

For the joins, I guess that unless you have extra data in join tables, creating separate business objects isn't necessary.  So I'd imagine it would be easier to understand if you just have methods List<Foo> selectFooForProgression(Progression) or Map<Foo, Progression> selectFoosForProgressions(List<Progression>) in the DalProgression class, basically where you start the join from.


This really should be put into a table, if possible.

If such a table already exists, you can take the SELECT for your existing view and simply wrap an INSERT INTO TargetTable statement around it.

INSERT INTO TargetTable
SELECT key1,key2,key3,key4 FROM YourView;
COMMIT;

Otherwise, you can CREATE TABLE TargetTable AS to generate a new table from your return query.

CREATE TABLE TargetTable AS
SELECT key1,key2,key3,key4 FROM YourView;
COMMIT;


Can calculation of word wrapping be made notably faster?

One possibility is to cache the measured length for each word. I do this, when the line breaks need to be recalculated (i.e. when document needs to be reflowed) frequently, for example because the user edits words or the user resizes the width of the control.

A second possibility is to use different APIs, for example:

A different StringFormat value passed as a parameter
A different method for example TextRenderer.MeasureText instead of Graphics.MeasureString

My code says ...

        //http://msdn.microsoft.com/en-us/magazine/cc163630.aspx#S7 i.e.
        //"Practical Tips For Boosting The Performance Of Windows Forms Apps" in MSDN says,
        //
        //It's better to use the TextRenderer method overloads that do not get IDeviceContext as an argument.
        //These methods are more efficient because they use a cached screen-compatible memory device context
        //rather than retrieving the native handle for device context from the internal DeviceContext and
        //creating an internal object to wrap it.
        //
        //My profiling shows that the method without the Graphics parameter takes 0.025 msec instead of 0.1 msec.
        //However, the resulting calculation is inaccurate.
        Size size = TextRenderer.MeasureText(
            m_graphics,
            text,
            paintStyle.font,
            proposedSize,
            textFormatFlags);

... and ...

    static TextFormatFlags textFormatFlags =
        TextFormatFlags.NoPrefix |
        TextFormatFlags.NoPadding |
        TextFormatFlags.ExternalLeading |
        TextFormatFlags.Left |
        TextFormatFlags.Bottom;

This code recalculates dozens of pages in a fraction of a second (and because it caches the measured word sizes it only measures all words once, when the document is first loaded).

The corresponding method which I use for drawing the text is:

        TextRenderer.DrawText(
            m_graphics,
            text,
            paintStyle.font,
            drawingPoint,
            color,
            textFormatFlags);


Whitespace Following Code Blocks
According to the Python style guide, you should use whitespace sparingly. Try aiming for one single line between functions and code blocks.
Unclear Function Naming
main_func() is not a very clear function name. As a developer reading the code, I am unsure as to what this function contains.
For a solution to this problem, read the next section:
Single-Responsibility Principle
Instead of grouping all of the main game code into main_func(), figure out blocks of code that have a single responsibility, and refactor them into their own function.
For example, the start of main_func() contains code to choose a word. You could refactor this into a choose_word() function that takes the list of words. From this point, you might choose to not pass word_lst into main_func, but instead the chosen word as a result of the choose_word() function.
As another example, further into your main_func() function, you may choose to refactor the "check" code (to see if the player has correctly guessed the word) into a check_guess() function.
Parameter Naming
I am not sure if this is just a typo or a stylistic choice, but you should rename word_lst to word_list. In this example, other developers (and possibly yourself in future) will be able to figure out that lst == list, but some words may not be so obvious. Try not to shorten words when naming variables parameters.


Using quickCheck for "99 Haskell problems" - problem 1

Most important point: Your answer does not do what is asked.

Question:

Prelude> myLast [1,2,3,4]
4
Prelude> myLast ['x','y','z']
'z'

Your implementation:

*Main> myLast [1,2,3,4]
Right 4

You should quickCheck for the equivalence of the function you are asked to implement myLast xs == last xs (with appropriate type signatures),
or write a unit test suite comprising at least the cases given.

Other points:

import Data.Int is unused.
(xs !! 0) should be head xs
Nested parentheses should be used sparingly because trying to match them reduces readability. Composition using operators . and $ should be preferred:

-- instead of this
myLast xs = Right (head (reverse xs))
-- this reads better
myLast' xs = Right $ head $ reverse xs
-- this makes the composition of 3 steps more explicit
myLast'' = Right . head . reverse


Preorder, Postorder, inorder Traversal in an Binary Search Tree

Recursion

Test if the current node is valid (return if it is not).
Processes node or Recurse

All your functions can be written much more succinctly and easier to read if you follow those rules.

void Tree::preorderTraversal(Node *tmp)
{
    // Always check to see if the node is valid first.
    if (tmp == nullptr) {
        return;
    }

    //processes your data (this could come after recursion or between the calls depending on the type of the traversal needed).
    std::cout << tmp->data << " ";

    // Recursion.
    preorderTraversal(tmp->left);   // Don't care if these are null
    preorderTraversal(tmp->right);  // This will be checked at the beginning of the next call.
}

Code Review

Make this part of Tree class (ie declare this as a private member of Tree). There is no reason for anbody outside the tree to know or use this class.

struct Node
{
  int data;
  Node *left;
  Node *right;
};

Why is root public?

  public:
    Node *root;

This breaks encapsulation and allows a non member to mutate the state of the class without the class knowing or understanding about the mutation.

    Tree()
    {
      root=NULL;
    }

Your Tree class does not obey the rule of Three or Five. This needs to be fixed immediately. Currently it does not break much because you have missed the destructor but it will lead to unexpected results when you copy and mutate the tree.

Also because you don't have a destructor you are leaking memory. You basically need to add the following methods to your Tree class.

     ~Tree();
     Tree(Tree const& rhs);
     Tree& operator=(Tree const& rhs);

You should avoid protected. Though it has its uses these are mostly advanced reasons to use protected. Stick to private and public.

  protected:

Note: As all these expose Node these should be private members. Your interface to the public should not expose internal types and Node is an internal type that affects the implementation.

    void SearchPos(Node *);
    void Inorder_Traversal(Node *);
    void Preorder_Traversal(Node *);
    void Postorder_Traversal(Node *);
};

You can initialize objects created with new.

  p=new Node;
  p->left=p->right=NULL;

  // Like this:
  p = new Node{0, nullptr, nullpre};

In 2011 ( 6 years ago) we introduced nullptr to replace the nasty C macro NULL. Please use nullptr.

  if(root==NULL)

Also a bit of horizontal space makes your code less clustered and nicer to read.

 if (root == nullptr) {
 }

Better Insertion

public:
    void Tree::insert(int data)
    {
        root = insertData(root, data);
    }
private:
    Node* Tree::insertData(Node* current, int data)
    {
        if current == nullptr) {
            return new Node{data, nullptr, nullptr};
        }
        if (date <= current->data) {
            current->left  = insertData(current->left,  data);
        }
        else {
            current->right = insertData(current->right, data);
        }
        return current;
    }


Function by function review

findPosition()

This function is inefficient because it searches an alphabetized string trying to find the index of a lowercase letter.  It would be faster to not even use the string and just compute the position directly like this:

if (x >= 'a' && x <= 'z')
    return x - 'a';

The other problem is what to return if the input character is not found.  Currently you return 26 and this causes the caller to print a null character (because chars[26] is the end of the string).  I think it would be preferable to return -1 and have the caller detect and deal with that.  So in total:

int findPosition(char x)
{
    if (x >= 'a' && x <= 'z')
        return x - 'a';
    return -1;
}

nextChar()

This function works fine, but it gets called n times, where n is the number of times you are rotating.  You should be able to delete this function if you modified rotChar() appropriately.

rotChar()

Instead of calling nextChar() rotNum times, you should be able to use the modulo operator to compute the next character in one step:

// Rotate char desired amount
char rotChar(char x, int rotNum)
{
    int pos = findPosition(x);

    if (pos == -1)
        return x;
    return 'a' + ((pos + rotNum) % 26);
}

Notice that this also returns the character unmodified if it wasn't a lowercase character.  At this point, you might want to just eliminate findPosition() and just do everything in rotChar() like this:

// Rotate char desired amount
char rotChar(char x, int rotNum)
{
    if (x >= 'a' && x <= 'z')
        return 'a' + (((x - 'a') + rotNum) % 26);
    return x;
}

Then you could easily extend this to handle uppercase letters as well:

// Rotate char desired amount
char rotChar(char x, int rotNum)
{
    if (x >= 'a' && x <= 'z')
        return 'a' + (((x - 'a') + rotNum) % 26);
    if (x >= 'A' && x <= 'Z')
        return 'A' + (((x - 'A') + rotNum) % 26);
    return x;
}


Reverse the word in a string with the same order in javascript

I would split this into two function, simply because they do different things:

First a simple string reverser:

function reverseString(input)
{
    var output = "";
    for(var i = input.length - 1; i >= 0; i--) {
        output +=  input[i];
    }
    return output;
}

This is an easy function that everybody can understand. But we need to reverse words, so we make another function for that.

function reverseWords(input)
{
    var word = "", output = "";
    for(var i = 0; i < input.length; i++) {
        if (input[i] == " ") {
            output += reverseString(word) + " ";
            word = "";
        }
        else {
            word += input[i];
        }
    }
    return output + reverseString(word);
}

And that's it. Now this might not be the niftiest, or shortest, solution, but it is one that reasonably easy to understand, and you get two functions for the price of one.

I had to correct this code after a comment from Blindman67 saying it didn't work for some cases.

A shorter version is also possible:

function reverseWordsShorter(input)
{
    var word = "", output = "";
    for(var i = input.length - 1; i >= 0; i--) {
        if (input[i] == " ") {
            output = " " + word + output;
            word = "";
        }
        else {
            word += input[i];
        }
    }
    return word + output;
}

Also notice that there's no erroneous space at the end anymore.


Merging two hashes with the mean values of each key if both hashes exist

There are many ways to do this, but all have two common elements. Firstly, since hash1 and hash2 are methods, you want to only call those methods once, which means saving the return values in variables:

h1 = hash1
h2 = hash2

Secondly, there are four possible courses of action, depending on the values of h1 and h2. You may wish to represent these with a case statement:

def merged_hashes(hash1,hash2)
  h1 = hash1
  h2 = hash2
  case [h1.is_a?(Hash), h2.is_a?(Hash)]
  when [false, false] then nil
  when [false, true]  then h2
  when [true, false]  then h1
  else compute_avg(h1, h2)
  end
end

Note that it is necessary to compute both h1 and h2 even if the first one computed is found to not be a hash.

All that remains is to construct the method compute_avg. Here are three ways that might be done:

Merge h1 and h2, using the form of Hash#merge that employs a block to determine the values of keys that are present in both hashes being merged, which here is all keys.

compute_avg(h1,h2)
  h1.merge(h2) { |_, v1, v2| [v1, v2].compact.mean }
end

You used merge in this way in your solution.

Extract values of h2 and send Enumerable#each_with_object to h1 to build the desired hash

compute_avg(h1,h2)
  values2 = h2.values
  h1.each_with_object({}) { |(k,v1),h| h[k] = [v1, values2.shift].compact.mean }
end

Extract the values of h1 and h2, compute their averages, element-by-element, then construct the hash to be returned

compute_avg(h1,h2)
  keys = h1.keys
  averages = { h1.values.zip(h2.values).map { |x1,x2| [x1, x2].compact.mean  } }
  keys.zip(averages).to_h
end


Simple pattern matching between two string inputs using Java (Google interview challenge)

Empty pattern should only match empty text

isMatch("aa", "a") returns true, when it should be false.
The problem is with this condition:

 if (p.length() == 0) {
     return true;
 }

An empty pattern should match only an empty text:

 if (p.isEmpty()) {
     return s.isEmpty();
 }

Notice that I replaced s.length() == 0 with s.isEmpty().
This is a more natural way to check if a string is empty.

Use better variable names

Instead of s and p it would be more natural to call them text and pattern.

The function isNextCharStarred is always used on the pattern,
but its parameter is called s, which is the same name as the variable used for text in the other function. Even p would have been less confusing. pattern would be nice and natural.

Eliminate hasPatternBeenEaten

The parameter hasPatternBeenEaten looked a bit suspicious to me.
Let's take a closer look.

The value of the variable is only read in one place in the code.
Let's look at the piece code just before that:

 if (isNextCharStarred(p)) {
     // will always return from this block
 }
 if (s.charAt(0) == p.charAt(0)) {
     return ...
 }
 if (hasPatternBeenEaten) {
     return false;
 }

That is:

If the pattern starts with X* (where X is any letter), the first if block will return.
If the pattern doesn't start with X*, and the first characters match, the second if block will return.
If the pattern doesn't start with X*, and the first characters don't match, then we need not look further: the pattern doesn't match, we can return false.

Therefore, the hasPatternBeenEaten is unnecessary, and can be safely eliminated.

Simplify

With the above changes, the code will look more like this:

  private boolean isMatch(String text, String pattern) {
    if (pattern.isEmpty()) {
      return text.isEmpty();
    }

    if (text.isEmpty()) {
      if (isNextCharStarred(pattern)) {
        return isMatch(text, pattern.substring(2));
      }
      return pattern.isEmpty();
    }

    if (isNextCharStarred(pattern)) {
      if (text.charAt(0) != pattern.charAt(0)) {
        return isMatch(text, pattern.substring(2));
      }
      return isMatch(text.substring(1), pattern)
        || isMatch(text, pattern.substring(2));
    }

    if (text.charAt(0) == pattern.charAt(0)) {
      return isMatch(text.substring(1), pattern.substring(1));
    }

    return false;
  }

This can probably be written simpler, by rearranging the conditions and extracting common patterns.

First of all the second pattern.isEmpty() condition is redundant,
because at that point we already know that pattern is not empty,
due to the very first condition in the method.

Next, we can extract the common condition text.charAt(0) == pattern.charAt(0) to a variable firstMatch, and flatten the if conditions to direct return statements, like this:

if (pattern.isEmpty()) {
  return text.isEmpty();
}

if (text.isEmpty()) {
  return isNextCharStarred(pattern) && isMatch(text, pattern.substring(2));
}

boolean firstMatch = text.charAt(0) == pattern.charAt(0);

if (isNextCharStarred(pattern)) {
  return firstMatch && isMatch(text.substring(1), pattern)
    || isMatch(text, pattern.substring(2));
}

return firstMatch && isMatch(text.substring(1), pattern.substring(1));

Lastly, we can generalize firstMatch to include the case of empty text,
which will make the second if redundant:

if (pattern.isEmpty()) {
  return text.isEmpty();
}

boolean firstMatch = !text.isEmpty() && text.charAt(0) == pattern.charAt(0);

if (isNextCharStarred(pattern)) {
  return firstMatch && isMatch(text.substring(1), pattern)
    || isMatch(text, pattern.substring(2));
}

return firstMatch && isMatch(text.substring(1), pattern.substring(1));


jQuery is entirely unnecessary and will just make your solution slower
Don't initialize to new Class() - this is not Java. Instead, initialize to the initial value, or undefined (var x;).
use a function to encapsulate your verification logic, and to separate it from the DOM interface.
don't call me.val() more than once; cache the result
instead of the slow $.each, use a simpler loop
You already know the length of the id string, so you can get rid of the p%2 check and simply operate twice on each loop, once on the current position and once on p + 1, and increment by 2 each time (this also results in half as many iterations, speeding up the loop even further).
Cast using +string (resulting in a number) and '' + number (resulting in a string)
split the string into the first 12 and the last 1 at the beginning, so you don't have to keep excluding the last character and re-extracting it.
'string'.slice(-1) is a more concise way to access the last character in a string
check to make sure that not only is the string 13 characters long, but also that every character is a numeral

With all that and a few stylistic preferences, here's my take on your problem:

function isValidSAID(id) {
    var i, c,
        even = '',
        sum = 0,
        check = id.slice(-1);

    if (id.length != 13 || id.match(/\D/)) {
        return false;
    }
    id = id.substr(0, id.length - 1);
    for (i = 0; c = id.charAt(i); i += 2) {
        sum += +c;
        even += id.charAt(i + 1);
    }
    even = '' + even * 2;
    for (i = 0; c = even.charAt(i); i++) {
        sum += +c;
    }
    sum = 10 - ('' + sum).charAt(1);
    return ('' + sum).slice(-1) == check;
}

if (!isValidSAID(document.getElementById('id').innerHTML)) {
    alert('Your South African ID is not valid.');
}


Using best practice with complex iteration

Honestly, that really doesn't look that bad to me.  It's probably what I would come out with after a first go - not that I'm some sort of Rust guru.  That being said, I'll discuss below a couple of things that you might like better.  It'd also be worth running Clippy over the program and having a look at what it says.  Not everyone likes everything Clippy says, but it can be quite informative.

As earlier commenters have said, it would be worth looking into using a linear algebra library, since this appears to be a matrix multiplication and that would probably end up being more efficient, and easier to use or manage.  All that being said, let's examine your program.

The first thing that jumps out at me is that you are doing a floating-point multiplication followed by an addition for every instance of the inner loop.  It so happens that Rust comes with something for that built-in these days.  You could update your inner-most loop to use this:

for x in 0..self.neuron_layers.len() - 1 {
        for y in 0..self.neuron_layers[x+1].len() {
            let mut sum:f64 = 0f64;
            for z in 0..self.neuron_layers[x].len() {
                sum = self.neuron_layers[x][z].mul_add(self.connection_layers[x][y][z], sum);
            }
            self.neuron_layers[x+1][y] = sigmoid(sum);
        }
    }

The two main advantages of this are that it should be less susceptible to floating-point imprecisions, meaning that you actually come out with a 'more accurate' result at the end, and that on certain hardware (actually most processors these days, I think) this should be a faster operation as it uses fused-multiply-add instructions built into said hardware to do both parts in one go.

Secondly, since you seem to be using the z index just to iterate over every entry in neuron_layers[x], you could actually swap over to using map, as per something like the below:

for x in 0..self.neuron_layers.len() - 1 {
    for y in 0..self.neuron_layers[x+1].len() {
        let sum = self.neuron_layers[x].iter().enumerate()
            .map(|(z, nl)| nl * self.connection_layers[x][y][z]).sum();
        self.neuron_layers[x+1][y] = sigmoid(sum);
    }
}

(I didn't have a chance to test this out, so it might need some tweaking to make the compiler totally happy).  In fact, I think you could expand this approach for every element in the first dimension of neuron_layers if you wanted to.  A potential benefit of this would be that Rayon should be quite good for targeting that level of the loop for parallelism.  Perhaps you could use this approach at the top level of the loop, and the mul_add approach in the inner loop.  You'd have to do benchmarks to figure out for sure what is fastest/most memory-efficient though.

Finally, having a quick look at your Pastebin link, I could see a couple of things worth mentioning.  Firstly, it looks like in at least one instance you create a Vec with length 1, but immediately push a known number of other elements onto it.  You should consider using Vec::with_capacity() to create this, as it should mean that you get the exact right amount of memory allocated, to begin with, which should be both faster and more efficient.

Secondly, I think with

for x in 0..input.len() {
            self.neuron_layers[0][x] = input[x];
        }

you could look at using extend_from_slice or copy_from_slice.  I must admit that I have never used either of those though, so I'm not 100% sure how to use them correctly with two Vecs.

I know this is nearly two months after you posted, but I hope this is helpful and/or informative nonetheless :)

EDIT: I realised that I had overlooked something an alternative to using map earlier, which I personally feel is a bit cleaner.  You could use fold instead, which should have the same net effect, but be (imho) a bit nicer to look at.

for x in 0..self.neuron_layers.len() - 1 {
    for y in 0..self.neuron_layers[x+1].len() {
        let sum = self.neuron_layers[x].iter().enumerate()
           .fold(0.0, |acc, (z, nl)| nl.mul_add(
           self.connection_layers[x][y][z], acc));
        self.neuron_layers[x+1][y] = sigmoid(sum);
    }
}

It might be the case that the compiler will complain about capturing things in closures, or something along those lines though, I must admit.  You could look at using zip first, e.g.

for x in 0..self.neuron_layers.len() - 1 {
    for y in 0..self.neuron_layers[x+1].len() {
        let sum = self.neuron_layers[x].iter().zip(self.connection_layers[x][y].iter())
           .fold(0.0, |acc, (nl, cl)| nl.mul_add(cl, acc));
        self.neuron_layers[x+1][y] = sigmoid(sum);
    }
}

but I'm not sure that would actually help.

The potential downside to this approach, however, is that you are effectively telling the compiler exactly how to do the summation, while with sum you leave that as an implementation detail of Vec - and there's a pretty good chance that Vec's approach will end up working as well as whatever we could write ourselves in 90%+ of cases.

As things currently stand, I think specifying it yourself is probably for the best, but if in the future someone works out a better way to sum over a Vec, that might end up being incorporated into the Vec struct.  If you are simply using sum, you get that 'for free' when you compile the program, whereas if you are using fold you continue using the exact same approach no matter what (which may or may not be what you want).  Again, you would probably have to test the different approaches out and decide which one works best for you.


Rock, Paper, Scissors, Lizard and Spock with OOP

First of all, you've got a syntax error:

getAction(soft){

should be:

getAction: function (soft) {

Anyway: It's pretty clean, but it a little too... Java'ish, for lack of a better word. Or at least it seems to be adhering too close to practices more applicable to other languages.

You're not using "private" (i.e. closure) variables, so many of the getters and setters aren't necessary. For instance, if I want the name of the user, I'd just write user.name. I wouldn't bother with user.getName().

Related to that, though there's no setter for the name property, that doesn't stop me from just assigning something.

All object properties are essentially public in JavaScript, and trying to avoid that is typically more hassle than it's worth. I find it easier to just roll with it for the most part.

Of course, you may want to keep some things "private", which is where closures come in. However, it's a little outside the scope of just a review, so I'll leave that be.

Point is, without all the getters/setters, you end up with a lot less code. And less code means less potential for bugs. Bugs like this:

getWins: function(){
    return this.won; // always returns undefined
},

The property this.won doesn't exist; you're looking for this.score.won. The same error is repeated for the other getters (except getMatches).

Related to all of this is the object copying you're doing with returning strengths and weaknesses. Again, it's a good idea - but is it worth it? Again, if I want to mess with the internal weaknesses obj, I can just go user.weaknesses... and manipulate the object directly anyway.

The getters only provide safety if I agree to use them. I'd rather agree to tread carefully in return for direct access to properties (which I already have, but still).

There's also a lot of type checking going on, which I often find a little too strict. If you pass an object to, say, winsTo that's duck-typing the correct API, there's no reason it should fail. Conversely, if it's completely incompatible, well, that'll probably manifest itself soon enough anyway. Yeah, I know, that's pretty loose (even lazy!), but this isn't a power plant control system, so...

Often times, a better solution to type-checking is feature detection. Instead of checking an object's ancestry, check whether it supports whatever it is you need:

if(typeof obj.someMethod === "function") {
  // ok, obj supports someMethod, so we can proceed
}

Lastly some style and structural things:

As ErikR points out, the names aren't great. RockPaperScissors is pretty vague. It's more a concept than object.
On that note, RockPaperScissorsGame, while a clearer name, isn't an impartial game. It's more of a scorecard, really - the user's score card, specifically. Values like won and lost are all from the perspective of one of the players. It'd be completely the opposite for the enemy player. Seems iffy to me.
You've got under_scored names like soft_action, but the JS convention is to use camelCase, i.e. softAction.
The something + '' trick isn't pretty. You can just use String(something) to coerce something to a string.
I'm not a fan of the asymmetry in strengths and weaknesses. For instance, if user beats enemy, you have to ask enemy how it happened by looking up the user in the enemy's weaknesses. That seems odd to me. I might prefer a central "table" object of sorts that keep track of what beats what and how.


Conditions

if ((one or two or three or four or five) > 69)

one or two will return one if it isn't falsy (0 / None / False), you should use separate conditions, like so :

if (one > 69 or two > 69 or three > 69...)

alternatively, you could just check the maximum value of your list

if (max(one, two, three, four, five) > 69)

The same problem occur in this part :

elif choice != ('R' or 'P')

it should be elif choice not in ('R','P')
variable names

instead of writing

m=0#matches

directly use the variable matches, your code will be easier to understand
loops

for i in range(0,5): #If you only get normal numbers, no powerball.
    if human[i] in real:
      m += 1
    i += 1

you don't need to increase i in a for loop, it is done automatically
code structure

in the powerball function, you have the following blocks:

if powerball:
    price = 4

for i in range(0,5):#no powerball
...
for i in range(0,5):#yes powerball
    if powerball and human[i] == real:
        ...

You should change that in a if/else structure with the if powerball while counting the number of corresponding number outside :

matches = 0
price = 0

for i in range(0,5):
    if human[i] in real:
        matches+=1

if human[5] == real[5]:# with powerball
    if matches == 0:
        price = 4
    elif matches == 1:
        price = 4
else:# without powerball
    if matches == 3:
        price = 7
    elif matches == 4:
        price = 100

multiple elif for variable assignation

(I don't know if this one is considered good practice, but it's faster to use and to add case)
instead of writing multiple elif, try to use a dictionary :

prices_for_matches = { 3 : 7,
                       4 : 100,
                       5 : 1000000}
if matches in prices_for_matches:
    price = prices_for_matches[matches]
else:
    price = 0

note i don't know much about powerball, but your solution doesn't care about the order of the balls (human[i] in real instead of human[i] == real[i]) or if the user selected multiple times the same number


MySQL proliferation of subqueries and left joins

Quick look at this and you have a lot of sub queries that seem unnecessary and could just be rewritten as normal joins. If the is_primary field is added to the foreign keys then this would enable the individual records to be accessed with an index.

Something like this:-

$sql = "SELECT p.id, p.fname, p.mname, p.surname, p.consultant_id,
                e.address,
                ph.number,
                a.street, a.street_more, a.city, a.country,
                co.label as 'nationality',
                msap.label as 'module'
        FROM per_person AS p
        LEFT JOIN per_phone ph ON p.id = ph.person_id AND ph.is_primary = 1
        LEFT JOIN per_email e ON p.id = e.person_id AND e.is_primary = 1
        LEFT JOIN per_address a ON p.id = a.person_id AND a.is_primary = 1
        LEFT JOIN per_sap sap ON p.id = sap.person_id
        LEFT JOIN meta_country co ON p.nationality = co.country_id
        LEFT JOIN meta_sap msap ON sap.module = msap.sap_id
        WHERE p.is_deleted IS NULL
        ORDER BY p.fname ASC
        LIMIT ".$index.", ".$per_page.";";

Note an index on fname might well help to order the results.


Use char[n] instead of string to store each individual solution.
Copy just the eligible solutions to a brand new vector (as Ben Voigt said) instead of deletion.

Assume n<=10. So, memory you need is less than 73Mb (i.e. twice 10*10!). Sequential memory access (#2) and avoiding pointer dereference (#1) means high performance on modern DDR memory.

UPDATE: Some notes on random or even non-random, but non-sequentional DDR memory read. Say, four 8-byte reads at addresses 0x8000 0x8100 0x8200 0x8300 will be slower than four 8-byte reads at 0x9000 0x9008 0x9010 0x9018, because in the later case all the data for the last reads (i.e. 0x9008 0x9010 0x9018) are already in processor 32-byte cache line (also, there are 64-byte cache lines in some processors). Each memory read (say, 8-byte read) transfers the whole 32-byte cache line from memory to processor cache.

Next, even the best possible optimizer can not decrease non-sequentional memory access latency (that is, the time between the memory address was calculated and the memory address contents was arrived into the processor)


Using jQuery UI .position() in a backwards compatible way

Interesting question,

have you tried passing +0 as an offset, that should work and make your code a little easier to read.

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}

As for the isVersionAtLeast($.ui.version, 1, 9) I would only check this once.

function generateCompatibleOffsetFunction(){

  if( isVersionAtLeast($.ui.version, 1, 9) ){
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left" + offsetString(offsetX ) + " top" + offsetString(offsetY );
    }
  } else {
    return function setOffset( options , offsetX , offsetY ){
      options.my = "left top";
      options.offset = "" + offsetX + " " + offsetY;
    }
  }
}

var setOffset = generateCompatibleOffsetFunction();

/** Prefix number with '+'/'-' or return empty string for 0. */
function offsetString(n){
    return '' + ( n < 0 ? n : '+' + n );
}

var posOpts = {
    at: "left top",
    of: $target
};

setOffset( posOpts, markerOffsetX, markerOffsetY );

$dropMarker.position(posOpts);


Overall

Not bad.

Resizing.

The maths is in favor of using a refactoring size of less than 1.63 as it potentially allows for memory to be reused after several allocations.

    static const int m_growth_factor = 2;

But on the other hand all the standard libraries do use 2.

Copy and Swap Idiom

    inline MyStack(const MyStack<T> &rhs) { *this = rhs; }

You are defining the copy constructor in terms of the assignment operator. The idiomatic way to do this is the other way around and define the assignment operator in terms of the copy constructor. Its called the copy and swap idiom. It provides the strong exception guarantee (ie the assignment works or the object is unchanged). Your assignment operator does not provide this.

Pre-Allocation

template <class T>
void MyStack<T>::init()
{
    m_array = new T[m_max_size];
    m_count = 0;
}

Here you are pre-allocating an array of T. This means that T must be default constructible (i.e. have a zero parameter constructor). Also if T is expensive to create and you don't use the whole array then you may be creating these object unnecessarily at an expensive point in the code.

You can allocate memory without calling the constructor then use placement new during the push to copy the data into the memory pool.

The same problem also appears in increase_array_size()

Potential Leak.

template <class T>
void MyStack<T>::increase_array_size()
{
    // STUFF

    for(int i = 0; i < m_count; i++)
        tmp[i] = m_array[i];           // If this throws an exception.
                                       // then you are leaking `tmp` pointer.

    // STUFF
}

Potential Invalid object.

template <class T>
void MyStack<T>::increase_array_size()
{
    // STUFF

    delete [] m_array;         // If this throws (because a T destructor throws)
                               // then you leave this object in an undefined
                               // state and you leak the `tmp` pointer.

    // STUFF
}

Use the copy and swap idiom to provide strong exception guarantee. This will also solve the problems in the last two points.

Provide Move Semantics.

This interface provides the standard copy semantics.

template <class T>
void MyStack<T>::push(T data)  // Also not passing by value causes a copy here
                               // So prefer to pass by const reference.
{
    if(m_count == m_max_size)
        increase_array_size();
    m_array[m_count++] = data;
}

But in C++11 we introduced move semantics which is potentially faster than copy semantics and Veridic template also allowing you to build the object in place.

template <typename T>
void MyStack<T>::push(T const& data);    // Copy data into MyStack.
template <typename T>
void MyStack<T>::push(T&& data);         // Move data into MyStack
template <typename... Args>
void MyStack<T>::emplace(Args&&... data);// Build data into MyStack

Assume the user knows the pre-conditions

You can check the pop() operation and throw. But if the user has already checked and knows that the stack is not empty you are doing extra work. For example the user is popping all the values from the stack in a for loop check for empty() in each iteration. Then your check becomes redundant extra work (because empty() was already called).

template <class T>
void MyStack<T>::pop()
{
    if(m_count == 0)
        throw std::underflow_error("Underflow Exception!!!");
    m_count--;

}

So in C++ you usually provide unchecked interface (let the user do the checking).

If you want you can also provide a checked interface then that is fine but usually not the default.

For example look at std::vector. Provides operator[](std::size_t index) for unchecked access to the data. But also provides at(std::size_t index) for checked access to the index.

Un-needed work.

Do you really need to call delete here?

template <class T>
void MyStack<T>::clear()
{
    delete [] m_array;
    m_max_size = m_initial_max_size;
    init();
}

You pre-initialized all the values initially. So you are not reallying on constructor/destructor properties. So this function can be simplified to:

template <class T>
void MyStack<T>::clear()
{
    m_count = 0;
}

If you want to release all the resources and re-create the default versions you can manually destroy all the objects.

Potential Leak.

template <class T>
void MyStack<T>::operator=(const MyStack<T> &rhs)
{
    if(this != &rhs)
    {
        delete [] m_array;                  // You should not delete the current
                                            // state until you know the operation
                                            // has succeeded. If the operation fails
                                            // you currently can not recover your state.

        init();
        for(int i = 0; i < rhs.m_count;i++)
        {
            this->push(rhs.m_array[i]);
        }

    }
}
#endif // MYSTACK_H


Safely handling memory allocation across DLL boundaries in Windows

The standard (and recommended) way to solve this is for each module to provide its own exported AllocMem and FreeMem functions (or whatever you want to call them—the names are not important).

This is what Windows DLLs do (for example, the Network API functions provide NetApiBufferAllocate and NetApiBufferFree to handle memory management), and you should strongly consider following the same model in your own project.

Regardless of their names, the implementation of these functions is downright trivial. AllocMem just needs to call new (or malloc if you're using C), and FreeMem just needs to call delete (or free if you're using C). They are just wrappers.

Header:

EXPORTED void* AllocMem(size_t cb);

EXPORTED void FreeMem(void* ptr);

Implementation:

EXPORTED void* AllocMem(size_t cb)
{
    return new char[cb];
}

EXPORTED void FreeMem(void* ptr)
{
    delete[] ptr;
}

You then follow the simple rule that every call to AllocMem is matched with a corresponding call to FreeMem from the same module. This ensures that the block of memory is always deallocated by the same module that allocated it.

For additional robustness, you might want to add error checking and even modify the function signatures to make extra information available to the callee for this purpose and/or return a status code to the caller.

Along similar lines lines, if you don't actually need general-purpose memory allocation, you might modify the function signatures to allocate only a certain type of memory and thus make them harder to use incorrectly. For example, AllocIntArray could always allocate an array of integers, taking as its only parameter the length of the array, and FreeIntArray would free a block of memory allocated by AllocIntArray.

These wrappers actually give you a lot of power. If diagnostics indicate that you have memory-fragmentation issues, you can add fixed-size allocation logic or switch over to the low fragmentation heap without introducing breaking behavior that would affect your clients.

As far as your goal of making it easy for the client to use, no competent programmer is going to have a hard time understanding how to use AllocMem and FreeMem functions. Personally, I make it a rule that all memory a caller needs to be freed must be explicitly allocated by the caller. This makes memory-management responsibilities significantly easier to reason about. But if you don't have such a rule (and I can't encourage you to adopt one, because you care more about simplicity than correctness), you could just have the DLL allocate the memory internally by calling the AllocMem function and return that block. Then, the client will just follow the rule that any memory it gets from the DLL, whether implicitly or explicitly, must be freed by calling FreeMem. There are Win32 functions that follow this model, too.

Alternatively, if you don't want to add additional exported functions to your libraries, you can just ensure that all of your code is standardized to use a single external memory allocator. For example, if you are targeting the Windows API, you can use either LocalAlloc and LocalFree, or CoTaskMemAlloc and CoTaskMemFree. This is safe because these allocators are universal and don't depend on the calling module.

I should also point out that if you are writing strictly C++ code and don't have any need for a lowest-common-denominator "C" API, then you can just return a shared smart pointer object from any function that needs to allocate memory. In addition to the obvious benefit of preventing the possibility of memory leaks and vastly simplifying the client code, smart pointer objects remember their associated deleter, thus guaranteeing that the memory will be correctly deallocated, even across module boundaries. If you're C++11, use std::shared_ptr; otherwise, you can use Boost's shared_ptr.


Currying?

Photo hosted via unsplash, taken by Monika Grabkowska
Yes you used Function.bind() to fix the callback function as the first argument to the private function, and this is a good approach to avoid excess functions and reduce the number of lines. While the concept is similar, what this code uses is actually Partial Application. Read more about the differences in this article.

The first couple functions appear to catch errors, but fetchMessage() doesn't appear to. Maybe you have updated it since you posted it but if not, I would suggest adding error handling there too.

You could consider using async and await to reduce the .then() callbacks.


What you implemented is different from what you were asked. Both the numbers in the array as well as k can be positive and negative, while it seems like you assumed both are strictly positive.

Even if you made those assumptions, it still doesn't produce the desired output. For example, if your list of numbers were 5,10,2,4 and your sum is 12, then your subroutine would return 0 when it should return 1.


Verifying requirements before deleting a user-parent-student-school relationship

One of the biggest things you can do to clean up you code is to simply remove the unnecessary if-else blocks.  In many cases you have a return inside the first conditional, which means there is no reason for an else block at all.

For example, you code rewrite like this:

Student.findOne({parent_ids:parent_id},function(err,parentF){
    if(err){
        console.log(err);
        res.json({status:"error",message:"an error occurred"});
        return
    }
    if(parentF){
        res.json({status:"error", message:"you can not delete a parent who has students associated with it"});
        return;
    }
    Parent.findOne({_id:parent_id},function(err,parent){
        if(err){
            console.log(err);
            res.json({status:"error",message:"an error occurred"});
            return;
        }
        if(parent.school_id.length>1){
            var a = parent.school_id.indexOf(school_id);
            parent.school_id.pop(a);
            parent.save(function(err,parent){
                if(err){
                    console.log(err);
                    res.json({status:"error",message:"an error occurred"});
                    return;
                }
                User.findOne({refid:parent_id},function(err,user){
                    if(err){
                        console.log(err);
                        res.json({status:"error",message:"an error occurred"});
                        return;
                    }
                    user.school_id.pop(a);
                    user.save(function(err) {
                        if(err){
                            console.log(err);
                            res.json({status:"error",message:"an error occurred"});
                            return;
                        }
                        res.json({status: "success", message: "parent removed"});
                        return;
                   });
               });
           });
        } else {
            Parent.remove({_id: parent_id}, function (err) {
                if (err) {
                    res.json({status: "error", message: err.message});
                } else {
                    User.remove({refid:parent_id},function(err){
                        if (err) {
                            res.json({status: "error", message: "parent user wasn't deleted"});
                            return;
                        }
                        res.json({status: "success", message: "parent data successfully deleted"});
                        return;
                    });
                }
            });
        }
    });
});

Hmm... half my post went away :(

I had also mentioned that you should look into naming your functions as a way to get away from the nesting that can be proliferated by anonymous functions.  You could add named functions for handling you error and success logging/response formation.   You could also add named functions to perform the callbacks, so as to flatten these callbacks out as well as provide re-use.

Finally, I think you have some style problems:

inconsistent use of semicolons at end of line
inconsistent spacing around flow control structures
inconsistent spacing around commas in function arguments and object literals
inconsistent use of camelCase vs. snake_case (you should probably just stick to camel casing in JS)

You should consider defining a style and enforcing it.


C++ class template for notification management

Your class seems generally well done and easy to use.  I have only a few suggested improvements.

Add text to throws

It would be useful to have something other than a null string when the object throws an error.

Add text to the static_assert

The same issue exists for the static_assert in that it would be useful to provide a meaningful error message instead of an empty string.

Provide some comments

Because the class is compact and generally well written, not much explanation is required, but a brief explanation, especially noting which exceptions might be thrown, would be useful.


Class with methods to retrieve data with Linq to sql

I can see some room for improvement:

Most importantly, you shouldn't hide exceptions like this. You should most likely let the exceptions bubble up and let the called decide what to do when an exception happens. And if you return null, it means you will either have to add null checks everywhere, or you will get NullReferenceException instead of the exception that actually caused the problem, which makes it harder to debug.
You don't need to add items into the list one by one, you can do it all at once using AddRange(). Or even better, just use ToList():

return crmTenants.ToList();

This one is really minor, but the query from tenant in context.CrmTenant select tenant can be simplified to just context.CrmTenant, the LINQ doesn't do anything useful there.

#1 is by far the biggest issue, I think, because it shows an error in your design. #2 and #3 could just simplify your code a bit.


Compare two files and save the result into a pickle file

One suggestion is to use numpy to vectorize your dot product.

>>> timeit.timeit('dot_product(range(10000),range(10000))', setup='from itertools import izip\ndef dot_product(v1, v2):\n    return sum(map(lambda x: x[0] * x[1], izip(v1, v2)))', number=1000)
2.666857957839966
>>> timeit.timeit('np.dot(range(10000),range(10000))', setup='import numpy as np', number=1000)
0.9193508625030518

Another suggestion is to use multiple threads or processes to run multiple compare results at the same time. The libraries threading or multiprocessing would be useful here.


Find the number of quadraples (a,b,c,d) from 4 respective arrays such that a+b+c+d=0

Well, you are going about it wrong.

As a wise man once said: If in doubt, sort.

Read all four lists.
Sort them.
Calculate the smallest and biggest value which can be compensated by the lists after the first m.
Iterate over those elements of the first list which can be compensated according to 3.

Iterate over those elements of the second list which can be compensated according to 3, keeping in mind your choice for 4.

Repeat step 5 for the third list, keeping in mind your choice for 5.

Add the number of elements in the last list which can compensate the previous choices to the result.

Aside from that:

Your indentation is very haphazard.
using namespace std; is a good way to shoot yourself in your own foot, and makes any toolchain-change unpredictable.
Dynamically-sized automatic arrays aren't C++, they are C99+. Try for std::vector or such.
return 0; is implicit for main in C++.

My own solution, which can still easily be optimized further. Don't peek before you have it.


Print code-fenced sections of a Markdown document

While your code looks ok, it could be improved greatly by making use of RS (record separator) and NR number of record, provided you're using GNU awk.

 awk -v RS='```[a-z]*\n' '(NR+1)%2' file

In this case RS is set such that it is catching everything between triple backticks with optional text.

The only awk statement is to print one record out of two.


Generating a list of alternatively positioned odd and even number out of an array of unsorted integers

You probably should have used Math.min(). Even if it was requested by the interviewer to not use anything else besides ArrayList, min can be written much more concise as

return n <= m ? n : m

(1 line of code vs. 8)
This loop is little bit ugly:

  for (i = 0; i < minOfOddAndEven; i++) {
    resultList.add(2*i,oddList.get(i) );
    resultList.add(2*i+1,evenList.get(i));
}

While I think it should work (don't have a Java compiler handy to try) it's a bit confusing to add the numbers at specified indices. I think it is legal to call add(index, item) where index == size() which should add an element to the end of the list. So your code happens to work but you need to look twice to make sure. It's totally unnecessary to do this. You could have simply done:

for (i = 0; i < minOfOddAndEven; i++) {
    resultList.add(oddList.get(i));
    resultList.add(evenList.get(i));
}

Same result but cleaner.
Copying the remainder of the list could have been done with subList:

if (longestList != null)
{
    resultList.addAll(longestList.subList(minOfOddAndEven, longestList.size());
}

Overall I think the interviewer might have wanted to see the use of iterators. You could have greatly simplified your code with this:

Iterator<Integer> odds = oddList.iterator();
Iterator<Integer> evens = evenList.iterator();

while (odds.hasNext() || evens.hasNext())
{
     if (odds.hasNext())
     {
         resultList.Add(odds.next());
     }
     if (evens.hasNext())
     {
         resultList.Add(evens.next());
     }
}

This way you iterate over both lists at once and don't have to implement the "which list is longer and then copy the remainder part"


Lookup country codes with a JavaScript ES6 Map Object

The natural data structure for looking up things is a map. In JavaScript this is simply an object and is written like {key: value}. It provides efficient access.

Therefore my first idea was to use two maps for the two kinds of lookup you need: country by ISO-3166-alpha2 and country by ISO-3166-alpha3. So instead of your single countries map, I prefer to have these two maps:

const countryByIso2 = {};
const countryByIso3 = {};

These are currently empty but will be filled soon.

function init() {
    const countryCodes = [
        ['US', 'USA'],
        ['UK', 'GBR'],
        ['CA', 'CAN'],
        ['AU', 'AUS'],
        ['PR', 'PRI'],
        ['GB', 'GBR']
    ];

    const overrides = [
        ['GB', 'UK'],
        ['CA', 'US']
    ];

    for (let country of countryCodes) {
        countryByIso2[country[0]] = country;
        countryByIso3[country[1]] = country;
    }
    for (let override of overrides) {
        let from = countryByIso2[override[0]];
        let to = countryByIso2[override[1]];
        countryByIso2[from[0]] = countryByIso2[to[0]];
        countryByIso3[from[1]] = countryByIso3[to[1]];
    }
}

init();

In this function I have removed all the unnecessary data and left just the country codes. There are two configuration sections. The first is the mapping you already know. The second are the overrides that you wrote in the if clauses of your getCountry function.

After the first part of the initialization, countryByIso2['CA'] contains ['CA', 'CAN']. But when the overrides are done, they overwrite the existing map entries. This means that after the initialization you can inspect the countryByIso2 object and quickly see what you will get.

What's missing is the actual lookup.

function lookupCountry(code) {
    if (!code) {
        return null;
    }
    let upperCode = code.toUpperCase();
    return countryByIso2[upperCode]
        || countryByIso3[upperCode];
}

function getCountry(i18nHeader, i18nQuery) {
    return lookupCountry(i18nHeader)
        || lookupCountry(i18nQuery)
        || countryByIso2['US'];
}

In total, this code is longer than yours, but it uses only very few and very fast operations. It is suitable for country lists of several thousand. Your code on the other hand walks through all entries (lookupCountry) and takes a long time when the data grows.

There's another difference. If i18nHeader is set to some unknown value, your code returns undefined while my code returns the US country codes.

The next topic is putting your code into its own namespace. After the above definitions, all parts of the code (even those you didn't write) can access the init function, the countryByIso2 tables, the lookupCountry function. But these are meant to be internal to your code and should not be seen by any unrelated code.

Therefore, it is best practice to explicitly define those pieces of code you want to export to the other code and only make that visible. This is typically done with the following pattern, putting all your code into an anonymous function and then returning the things to be exported:

const getCountry = (function() {

    const countryByIso2 = {};
    const countryByIso3 = {};

    const countryCodes = [
        ['US', 'USA'],
        ['UK', 'GBR'],
        ['CA', 'CAN'],
        ['AU', 'AUS'],
        ['PR', 'PRI'],
        ['GB', 'GBR']
    ];

    const overrides = [
        ['GB', 'UK'],
        ['CA', 'US']
    ];

    for (let country of countryCodes) {
        countryByIso2[country[0]] = country;
        countryByIso3[country[1]] = country;
    }
    for (let override of overrides) {
        let from = countryByIso2[override[0]];
        let to = countryByIso2[override[1]];
        countryByIso2[from[0]] = countryByIso2[to[0]];
        countryByIso3[from[1]] = countryByIso3[to[1]];
    }

    function lookupCountry(code) {
        if (!code) {
            return null;
        }
        let upperCode = code.toUpperCase();
        return countryByIso2[upperCode]
            || countryByIso3[upperCode];
    }

    function getCountry(i18nHeader, i18nQuery) {
        return lookupCountry(i18nHeader)
            || lookupCountry(i18nQuery)
            || countryByIso2['US'];
    }

    return getCountry;
})();

When I saw your code, the first thing I did was to remove the unnecessary else clauses from the getCountry function. Then it looked like this:

function getCountry(i18nHeader, i18nQuery) {
    if (i18nQuery) {
        return lookupCountry(countries, i18nQuery);
    }
    if (!i18nHeader || !i18nHeader.length) {
        return countries.UNITED_STATES;
    }
    if (i18nHeader.toUpperCase() === countries.GREAT_BRITAIN[0]) {
        return countries.UNITED_KINGDOM;
    }
    if (i18nHeader.toUpperCase() === countries.CANADA[0]) {
        return countries.UNITED_STATES;
    }
    return lookupCountry(countries, i18nHeader);
}

It's a one-dimensional chain of decisions now, instead of a hard-to-grasp nested decision tree. It's still difficult to follow, and that's why I rewrote it in the alternative way described above.


Randomises capitalisation of letters like bird spongebob

Unnecessary comments

You have a lot of comments telling WHAT the code does. Comments should tell -why- you do it in a certain way or what else you have tried but failed. Just repeating in comment what the code says is a waste of time (for the reader and the writer as well)

Method name

You method is called randCap. I prefer just naming it what it does, so randomCapitalize() for example. Makes the code more readable.

Logic

I tried to understand what the logic behind the prevCharacter is. It is not immediately clear how it works, and what is has to do with the blacklist.

I think you mean to make sure there are not many lowercase or uppercase characters in a row?

You don't need such a long blacklist, because you can safely call toUpperCase() and toLowerCase() on comma's etc.

Code in main loop

You can move a lot of the code out of the main loop, by adding a method public String spongeBobify(String s) to the class. The main method will only take care of the input/ouput.

Unnecessary calculations

What is wrong with:

boolean isCap = Math.random() >= 0.5;

or, if you have a Random object, random.nextBoolean()?

Closing the scanner

You need to close your Scanner, you can do this by using a try-with-resources:

try (Scanner scanner = new Scanner(System.in)) {
    ...


Optimization and restructuring

Function's responsibility

The initial approach makes the read_page function depend on both requests and BeautifulSoup modules (though BeautifulSoup functionality/features is not actually used there). Then, a soup instance is passed to news_scraper(soup) function.To reduce dependencies let read_page function extract the remote webpage and just return its contents r.content. That will also uncouple news_scraper from soup instance arguments and allow to pass any markup content, making the function more unified.

Namings

BASE = "https://www.pravda.com.ua" within news_scraper function is essentially acting like a local variable. But considering it as a constant - it should be moved out at top level and renamed to a meaningful BASE_URL = "https://www.pravda.com.ua".

i is not a good variable name to reflect a document element in for i in soup.select("div.news.news_all > div"). Good names are node, el, atricle ...

The main function is better renamed to news_to_df to reflect the actual intention.main(START_URL) - don't give arguments uppercased names, it should be start_url.

Parsing news items and composing "date" value

As you parse webpages (html pages) - specifying html.parser or html5lib (not lxml) is preferable for creating BeautifulSoup instance.

Extracting an article publication time with generic i.div.text would be wrong as a parent node div.article could potentially contain another child div nodes with text content. Therefore, the search query should be more exact: news_time = el.find(class_='article__time').text.Instead of assigning, traversing and dropping "time" column and aggregating:

dataframe["date"] = (
        dataframe["link"]
        .str.extract("(\d{4}/\d{2}/\d{2})")[0]
        .str.cat(dataframe["time"], sep=" ")
    )

- that all can be eliminated and the date column can be calculated at once by combining the extracted date value (powered by precompiled regex pattern DATE_PAT = re.compile(r'\d{4}/\d{2}/\d{2}')) and news_time value.

Instead of collecting a list of lists - a more robust way is to collect a list of dictionaries like {'title': ..., 'subtitle': ..., 'date': ..., 'link': ...} as that will prevent confusing the order of values for strict list of column names.

Furthermore, instead of appending to list, a sequence of needed dictionaries can be efficiently collected with generator function. See the full implementation below.

The main function (new name: news_to_df)

The while next_page: turned to while True:.

except: - do not use bare except, at least catch basic Exception class: except Exception:.

The repeated blocks of read_page, news_scraper and results.append(df) statements can be reduced to a single block (see below).One subtle nuance is that the ultimate "next" page will have '/archives/' in its a.button.button_next.href path, signaling the end of paging. It's worth to handle that situation explicitly:

if next_page == '/archives/':
    break

The final optimized solution:

import requests
import pandas as pd
from bs4 import BeautifulSoup
from time import sleep
import re

BASE_URL = "https://www.pravda.com.ua"
DATE_PAT = re.compile(r'\d{4}/\d{2}/\d{2}')

def read_page(url):
    r = requests.get(url)
    return r.content

def _collect_newsitems_gen(articles):
    for el in articles:
        a_node = el.a
        news_time = el.find(class_='article__time').text
        yield {'title': a_node.text,
               'subtitle': el.find(class_="article__subtitle").text,
               'date': f'{DATE_PAT.search(a_node["href"]).group()} {news_time}',
               'link': f'{BASE_URL}{a_node["href"]}'}

def news_scraper(news_content):
    soup = BeautifulSoup(news_content, "html5lib")
    articles = soup.select("div.news.news_all > div")
    next_page_url = soup.select_one("div.archive-navigation > a.button.button_next")["href"]
    df = pd.DataFrame(list(_collect_newsitems_gen(articles)),
                      columns=["title", "subtitle", "date", "link"])

    return df, f'{BASE_URL}{next_page_url}'

def news_to_df(start_url):
    next_page = start_url
    results = []

    while True:
        print(next_page)
        try:
            content = read_page(next_page)
            df, next_page = news_scraper(content)
            results.append(df)
            if next_page == '/archives/':
                break
        except Exception:
            break

        sleep(1)

    return pd.concat([r for r in results], ignore_index=True)

if __name__ == "__main__":
    df = news_to_df("https://www.pravda.com.ua/archives/date_24122019/")
    assert df.shape == (120, 4)  # it's true as of today, 12.26.2019

If printing the final resulting df with print(df.to_string()) - the output would look like below (with cutted the middle part to make it a bit shorter):

https://www.pravda.com.ua/archives/date_24122019/
https://www.pravda.com.ua/archives/date_25122019/
https://www.pravda.com.ua/archives/
                                                 title                                           subtitle              date                                               link
0    Голова Закарпаття не зрозумів, за що його звіл...  Голова Закарпатської обласної державної адміні...  2019/12/24 23:36  https://www.pravda.com.ua/news/2019/12/24/7235...
1    Стало відомо коли відновлять будівництво об'єк...  На зустрічі представників керівництва ХК Київм...  2019/12/24 22:41  https://www.pravda.com.uahttps://www.epravda.c...
2          ВАКС продовжив арешт Гримчаку до 14 лютого   Вищий антикорупційний продовжив арешт для коли...  2019/12/24 22:25  https://www.pravda.com.ua/news/2019/12/24/7235...
3    Економічні новини 24 грудня: транзит газу, зни...  Про транзит газу, про зниження "платіжок", про...  2019/12/24 22:10  https://www.pravda.com.uahttps://www.epravda.c...
4    Трамп: США готові до будь-якого "різдвяного по...  Президент США Дональд Трамп на тлі побоювань щ...  2019/12/24 22:00  https://www.pravda.com.uahttps://www.eurointeg...
5    У податковій слідчі дії – електронні сервіси п...  Державна податкова служба попереджає, що елект...  2019/12/24 21:55  https://www.pravda.com.ua/news/2019/12/24/7235...
6     Мінфін знизив ставки за держборгом до 11% річних  Міністерство фінансів знизило середньозважену ...  2019/12/24 21:31  https://www.pravda.com.uahttps://www.epravda.c...
7    Україна викреслила зі списку на обмін ексберку...  Російський адвокат Валентин Рибін заявляє, що ...  2019/12/24 21:13  https://www.pravda.com.ua/news/2019/12/24/7235...
8    Посол: іспанський клуб покарають за образи укр...  Посол України в Іспанії Анатолій Щерба заявив,...  2019/12/24 20:45  https://www.pravda.com.uahttps://www.eurointeg...
9    Міністр енергетики: "Газпром" може "зістрибнут...  У Міністерстві енергетики не виключають, що "Г...  2019/12/24 20:03  https://www.pravda.com.uahttps://www.epravda.c...
10   Зеленський призначив Арахамію секретарем Націн...  Президент Володимир Зеленський затвердив персо...  2019/12/24 20:00  https://www.pravda.com.ua/news/2019/12/24/7235...
...
110  Уряд придумав, як захистити українців від шкод...  Кабінет міністрів схвалив законопроєкт, який з...  2019/12/25 06:54  https://www.pravda.com.ua/news/2019/12/25/7235...
111  Кіберполіція та YouControl домовилися про спів...  Кіберполіція та компанія YouControl підписали ...  2019/12/25 06:00  https://www.pravda.com.ua/news/2019/12/25/7235...
112  В окупованому Криму продають прикарпатські яли...  У центрі Сімферополя, на новорічному ярмарку п...  2019/12/25 05:11  https://www.pravda.com.ua/news/2019/12/25/7235...
113  У США схожий на Санту чоловік пограбував банк,...  У Сполучених Штатах чоловік з білою, як у Сант...  2019/12/25 04:00  https://www.pravda.com.ua/news/2019/12/25/7235...
114  У Росії за "дитячу порнографію" посадили блоге...  Верховний суд російської Чувашії засудив до тр...  2019/12/25 03:26  https://www.pravda.com.ua/news/2019/12/25/7235...
115  Уряд провів екстрене засідання через газові пе...  Кабінет міністрів у вівторок ввечері провів ек...  2019/12/25 02:31  https://www.pravda.com.ua/news/2019/12/25/7235...
116  Нова стратегія Мінспорту: розвиток інфраструкт...  Стратегія розвитку спорту і фізичної активност...  2019/12/25 02:14  https://www.pravda.com.ua/news/2019/12/25/7235...
117  Милованов розкритикував НБУ за курс гривні та ...  Міністр розвитку економіки Тимофій Милованов р...  2019/12/24 01:46  https://www.pravda.com.uahttps://www.epravda.c...
118  Російські літаки розбомбили школу в Сирії: заг...  Щонайменше 10 людей, в тому числі шестеро – ді...  2019/12/25 01:04  https://www.pravda.com.ua/news/2019/12/25/7235...
119  Ліквідація "майданчиків Яценка": Зеленський пі...  Президент Володимир Зеленський підписав закон,...  2019/12/25 00:27  https://www.pravda.com.ua/news/2019/12/25/7235...

P.S. From Ukraine with love ...


Important stuff:

Missing header:

The std::less<> is from <functional>.

Relying on type deduction:

Although it is generally good, the lines

            auto& i_val = *i;
            auto& i_next_val = *i_next;

seem somewhat dangerous to me. For std::vector<bool>, for example. I think it should be at least const auto&, or even better, the comparison could be called without them:

cmp(*i, *i_next);

Dangerous swap:

        auto& i_val = *i;
        auto& i_next_val = *i_next;
        if (cmp(i_val, i_next_val)) {
            break;
        }
        std::iter_swap(&i_val, &i_next_val);

The swap assumes that types didn't overload operator&. It is pretty rare these days, but still exist. The swap should just be std::iter_swap(i, i_next).

Style:

Complicated inner loop:

The control flow inside of the loop is very hard to follow. This is the version in my library:

        auto j = i;
        while (std::prev(j) != first && !cmp(*std::prev(j), *j))
        {
            std::iter_swap(std::prev(j), j);
            --j;
        }

The i is the iterator of the outer loop. It might not be that descriptive, but I think it is ok. The main idea here is that while loop is used and the condition is inside of the condition brackets, which closely follows plain english description of an algorithm.

Naming:

Usually range is denoted by [first, last). At least this is what I see quite frequently on cppreference. Also, the concept is called Compare, so it might be worth sticking to it, although it is somewhat confusing.

Testing:

There is std::greater template function object which could be used instead of handwritten lambda.


Newton's algorithm for a polynomial of arbitary degree

In general, LGTM. Few notes:

The name f is meaningless. newtonDelta perhaps?
It feels right to compute a derivative's coefficients once, and reuse evalPoly for both the function and its derivative. After all, the polynomial's derivative is also polynomial. There is an usual space-time tradeoff, but in the case of polynomials DRY rule casts a deciding vote.
Newton's algorithm does not necessarily converge. You should be prepared to handle the divergent case.
Hardcoding ε is dubious. I recommend to solveNewton have it as a parameter.
Using Horner schedule is a definite improvement.


Search DataTable by column for a specific row

I have two suggestions:

Trim ColValue once rather than every iteration through the loop.
Use a case-insensitive string compare rather than performing .ToLower() on two different strings on every loop iteration.

Result:

private string FindInT(DataTable dt, string ColName, string ColValue, string returnCol)
{
    ColValue = ColValue.Trim();
    foreach (DataRow row in dt.Rows)
    {
        if (string.Equals(
            row[ColName].ToString().Trim(),
            ColValue,
            StringComparison.InvariantCultureIgnoreCase))
        {
            return row[returnCol].ToString();
        }
    }
    return "";
}