A small "TODO" app built using a modular pattern

There's some stuff that's confusing in this coding and it's structure. A few things of note:

First when defining a class you do not need the beginning ( and ending )(); What that is for is to create a nameless function that will then be run once and then for all intents and purposes be removed from memory after. You are wanting to create a class that can be referenced and used later on.
Simply:

function todoApp(){
    //define class here
}

This then creates an object constructor that you then call to create and store the object:

var myTodoApp = new todoApp();

Then your jQuery call after that, outside of your constructor, not in:

  $("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
    myTodoApp.storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
    myTodoApp.view.render();
  });

When giving a class (your todoApp function) a custom class for a variable, that 'sub-class' should be defined separately and then referenced inside of your class.

Inside of your class, anything you want to be accessible outside of your class should start with this.

var mayTodoApp = new todoApp();

$("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
    myTodoApp.storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
    myTodoApp.view.render();
  });

function todoApp(){
    this.storage = new storageClass();
    this.example = 'this is a string accessible outside of the class';
    //run any initialization code here
}

function storageClass(){
    var _db,
        todos,
        addTodo,
        removeTodo,
        updateTodo,
        getAllTodos,
        save;

        this.addTodo = function addTodo(todo) {
            //do stuff
            this.save(); //note: need 'this.' for class to access itself
        };
}

This is more along the structure you are looking for. A few things I would suggest looking into is the concept of this and maybe some Google results on javascript object oriented programming. Also having a good strong IDE (integrated development environment) helps a lot. I recommend Komodo personally, but to each their own. There might be a better one out there for you. But a good strong one can give code completion and show you syntax errors to help you get the structure down.

One other thing of note that helps quite a bit: Javascript is all read and processed into the DOM before anything is actually run (accept for dynamically added stripts, but that is a whole different beast). What this means is that before any coding is already run, the interpreter has already processed over the class definition. In other words, you can call your classes before defining them:

function todoApp(){
    this.storage = new storageClass();
}
function storageClass(){
    this.addTodo = function(todo){
    }
}
var todo = new todoApp();
todo.storage.addTodo('fooBar');

Will do the same as:

var todo = new todoApp();
todo.storage.addTodo('fooBar');

function storageClass(){
    this.addTodo = function(todo){
    }
}

function todoApp(){
    this.storage = new storageClass();
}

Outside of class definition, order matters, or course. You must create the object instance of your class before using it. Note that the latter is the standard. Classes should be defined below the coding to be run globally, this makes for better readability.

EDIT:    I also just noticed your JSON objects. You do not need to define then in that manner. Javascript automatically determines variable type which is why you use var instead of char and int and such. For this same reason JSON objects are automatically defined by format. It's a harder concept for some to grasp at first and I would definitely read more into it but basically it is an associated array, or array of pairs (keys and values). that is in this format:

{key: 'value', key: 'value'}

It is defined inside of curly brackets { } the key is a name to reference the value, and does not need quotes. The value needs quotes unless you want to use a variable. Also numbers do not need quotes for the values. Values can be objects or arrays as well. And the pairs are delimited by a comma ,. As long as you follow these rules javascript does the rest.

var home = '1234 Fake St.';
var example = {date: '12/01/2016', time: '9:42am', location: home, peopleAttending: 10};


Java method to add daily interest to bank account after month is over

Conventions

Java conventions state that code is indented with 4 spaces, not 2. Java also states that the brace should be on the same line, though this is more of your choice; the important part is consistency. After formatting, your code will then look like:

public void incrementDay() {
    if (!paidInFullFlag) {
        interestCharged += (this.balance + interestCharged) * (interestRate
                / 365);
    }
}

/*
 * Method adds interestCharged to balance and checks whether or not account
 * has been paid in full for month
 */
public void incrementMonth() {
    this.balance += interestCharged;
    this.interestCharged = 0;
    if (this.sumPayment >= this.monthlyPayment) {
        this.paidInFullFlag = true;
    } else {
        this.paidInFullFlag = false;
    }

    if (minMonthly < monthlyPayment && sumPayment < minMonthly) {
        this.balance += latePaymentPenalty;
    }
    this.sumPayment = 0;
    this.monthlyPayment = this.balance;
}

Miscellaneous

Here:

    if (this.sumPayment >= this.monthlyPayment) {
        this.paidInFullFlag = true;
    } else {
        this.paidInFullFlag = false;
    }

Since the condition is a boolean already, this could be simplified to:

    this.paidInFullFlag = this.sumPayment >= this.monthlyPayment;

The comment here:

/*
 * Method adds interestCharged to balance and checks whether or not account
 * has been paid in full for month
 */

Should be a JavaDoc comment:

/**
 * Method adds interestCharged to balance and checks whether or not account
 * has been paid in full for month
 */

Very similar, but not exactly the same.


Filling in the card expiry date from transaction data

Your first version of build_expiry_date_string() will be able to build an shorter notation date from any date array. I would therefore rename it to build_short_date_string().

The second version actually is named correctly, but can only convert an expiry date to the shorter notation.

Which is the better version?

Well, clearly, if you need to create a short date string from more than one date array then the first one wins. The second one is more specialized. It will only work for the card_exp date.

In general I don't see the point of overspecializing functions. The more general purpose version does a good job, so I would prefer that one, even if it is, for now, only used for one date array.

Functions should be used to encapsulate functionality that can be reused and therefore make your code easier to maintain. (reference)

It is the reusability that wins for me here, over any other considerations.

Note that we're talking about simple functions here, not methods that are part of classes. OOP is a whole other can of worms.

Some other remarks about your code (this is code review afterall):

You extract() data at the beginning of populate_transaction_info(). This seems like a nice trick, but it makes your code harder to read and debug. For instance, I have to assume that $person is one of these extracted variables, but for me it appears out of thin air. You could help your code reader by using a prefix whenever your extract something: extract(...., EXTR_PREFIX_ALL, 'model'); and then use $model_person, but preferably just explicitly define the person variable in the function.
Your comment: "set to empty array to ensure run-able code" and the subsequent array_merge() make no sense to me. Why not just define the array?


Split a string on spaces, accounting for backslash as escape character, in Haskell

Apart from general code layout I don't see much to improve - the only issue worth talking about is that you should never ever actually use something like ++ [ch]. Your function is needlessly O(n²) for that reason alone. That might not sound like much here, but it is a good idea to shake this habit early.

So let's talk about that a bit. Your options generally are:

Find a library function that frees you from actually constructing the list yourself. But to be fair, for this examples I can't actually think of anything helpful myself.
Use a data structure that copes better with it, such as Seq from Data.Sequence.
First construct the list using just (:), then reverse it at the end. That might seem inefficient, but given that reverse is only O(n), it will never actually increase algorithmic complexity.
Rebuild your function so it constructs the list in the right order right away.

Here is what things look like if we go for the last option:

import Control.Arrow ( first )
token :: String -> (String, String)
token ""          = ("", "")
token (' ' :  cs) = ("", cs)
token ('\\':c:cs) = first (c:) $ token cs
token (c   :  cs) = first (c:) $ token cs

The key here is that we add the character c using first (c:) after the recursive call returns, and therefore to the front of the string.

A notable advantage is that this version has better laziness properties:

*Main> head $ fst $ token ('t':undefined)
't'

We know that the first character is 't' even without looking at the rest of the string, whereas your function always needs to finish a complete token before it can return. And as we are programming in Haskell, we often like our functions as lazy as possible.

Finally, a matching tokens implementation:

tokens :: String -> [String]
tokens str
  | null str'  = []
  | otherwise  = tok : tokens rest
  where str' = dropWhile (==' ') str
        (tok, rest) = token str'

This is again basically your version using direct list construction. Only difference is that we now deal with whitespace once per token, which I feel is slightly more elegant.


There are several improvement areas. Let's review them one-by-one from bottom up:
GetXYZ
private static async Task GetXYZ(string parameter)
{
     await Task.Run(() => {
         var svc = new WebApiService();
         var msg1 = svc.GeXYZ(parameter);
         if (string.IsNullOrWhiteSpace(parameter)) return;
            Console.WriteLine($"XYZ {parameter}");
     });
}

A Task can represent either an asynchronous work or a parallel work. An async work can be considered as non-blocking I/O operation. Whereas the parallel work can be treated as (blocking) CPU operation. (It is oversimplified but it works for us now)
In the above code the Task.Run tells to .NET runtime that this piece of code should run a dedicated thread (in reality this is not as simple as this, but let me simplify the model now). It means that the passed delegate should run a dedicated CPU core.
But inside your delegate you are making a blocking I/O operation. So you have created a delegate, you have moved that code to a dedicated core, which will block and do nothing until the network driver will finish the I/O operation.
You are just wasting a lot of valuable resources. A better alternative would look like this:
private static async Task GetXYZ(string parameter)
{
     var svc = new WebApiService();
     var msg1 = await svc.GeXYZAsync(parameter);
     if (string.IsNullOrWhiteSpace(parameter)) return;
        Console.WriteLine($"XYZ {parameter}");
}

Here you are making a non-blocking I/O operation. The network driver fires of a network call asynchronously and returns immediately. When it completes it will notify the ThreadPool. (Because here we are calling await against an asynchronous work that's why we are not blocking the caller Thread.)
In short: Network driver can do let's say 1000 concurrent network operations at the same time. While the CPU can perform as many operations in parallel as many cores it has.
RunTasks
(I guess you can find a better name for this.)
Here with the Task.WhenAll you are already asking the .NET runtime to run them in parallel. If they are asynchronous operations then the network driver will take care of them and try to run them in parallel. In case of parallel work CPU tries to schedule them on different cores but there is no guarantee that they will run in parallel. They might run only concurrently (with context-switches).
RunLoad
(I guess you can find a better name for this.)
Here with the Parallel.For you try to create as many blocking parallel task as many the loadSize value. If you have 100 Tasks for 8 CPU cores then it is inevitable to have context-switches. Again your current implementation is highly CPU-bound even though you try to perform massive I/O operations.
A better alternative:
private static async Task RunLoad(int loadSize)
{
    var clients = new List<Task>();
    for (int j = 0; j < loadSize; j++)
    {
        clients.Add(RunTasks());
    }

    await Task.WhenAll(clients);
}

In this way all your client's all requests might run in parallel if your network driver supports that many outgoing requests.
This WhenAll will be finished when all operation has finished. If you want to monitor them in "real-time" when any of them finished then you can rewrite your method in the following way:
static async Task Main(string[] args)
{
    Console.WriteLine("Press any key to start...");
    Console.ReadKey();
    Console.WriteLine();

    await foreach (var test in RunTests(10))
    {
        //NOOP
    }

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
}

private static async IAsyncEnumerable<Task> RunTests(int loadSize)
{
    var requests = new List<Task>();
    for (int j = 0; j < loadSize; j++)
    {
        requests.Add(GetLoanByLoanId("7000002050"));
        requests.Add(GetEnvelopesForLoan("7000002077"));
        requests.Add(GetLoanDataByLoanId("7000002072"));
    }

    while (requests.Any())
    {
        var finishedRequest = await Task.WhenAny(requests);
        requests.Remove(finishedRequest);
        yield return finishedRequest;
    }
}


Mapping from string "aa=bb" to Dictionary

Why not to use regular expression? Your task can be solved with this code:

var dictionary = Regex.Matches(tmp, "(?<key>.+)=(?<value>.+)")
                      .OfType<Match>()
                      .Where(m => m.Success)
                      .ToDictionary(m => m.Groups["key"].Value.Trim(),
                                    m => m.Groups["value"].Value.Trim());


I think if you generalize the problem to having multiple choices instead of just 2, it would make things a lot simpler. It gives the added flexibility of adding more choices later on if needed, but most importantly, you can cut down explicit references to element A, or element B, or audio A, or audio B, throughout your codebase.

Doing so would mean that you tweak the HTML slightly, and instead of referring to DOM elements directly by their id such as choiceA, or choiceB, you rely on their position or index. The HTML of all choices may then look something like,

..

..

Keeping that in mind, here are the changes I would suggest. Create an object that represents an audio to avoid worrying about passing mp3/ogg variables all over.

function AudioFile(fileName) {
    var root = "../../Content/Audio/";
    this.mp3 = root + fileName + '.mp3';
    this.ogg = root + fileName + '.ogg';
}

Your playAudio1 and playAudio2 functions are identical. They can accept the AudioFile object, and be combined into one.

function playAudio(audio) {
    var player = $('#jquery_jplayer');
    player.jPlayer('setMedia', {
        oga: audio.ogg,
        mp3: audio.mp3
    });
    player.jPlayer('play');
}

By getting away from two choices, you can treat the number of choices as an array, and attach the required event handler for each item in the array alike. Also it seems like you are rebinding the live events after each AJAX call. That's just a waste of resources. You could explicitly bind after each AJAX call, or attach live handlers on document load or something. Here's the revamped getNewWords and attachMouseEnter methods.

function getNewWords() {
    var Category = "animals";
    var BaseURL = "http://localhost:61741/VocabGame/play?cat=";
    var URL = BaseURL + Category;

    $.getJSON(URL, didGetNewWords);

    var containers = $('.choice');

    function didGetNewWords(data) {
        data.nouns.forEach(function(noun, index) {
            var container = containers.get(index);
            container.html(noun.Pinyin);
            var audio = new AudioFile(noun.Audio1);
            attachMouseEnter(container, audio);
        });

        // Pick a random answer by index
        var answerIndex = Math.floor(Math.random() * data.nouns.length);
        correctAnswer = containers.get(answerIndex).id;
        Search(data.nouns[answerIndex].English);
    }
}

// Play this audio when this element is hovered over
function attachMouseEnter(element, audio) {
    $(element).bind('mouseenter', function() {
        playAudio(audio);
    });
}


Compute the square root of a positive integer using binary search

Your comments on  the elif / else part are too long to be just after the statements
Don't use semicolons (;) in Python.
This is a refactored version of the code

import math

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int

        Returns floor(sqrt(x))
        """
        low = 0
        high = x//2 + 1

        """
        It is proved that 0 <= sqrt(x) <= x/2, so
        we run a dichotomic in [0, x/2] to find floor(sqrt(x))

        Loop analysis:
        * Initialization: low = 0 and high = x/2 + 1
        * Termination: |high-low| is reduced each iteration,
          as shown in lines high = mid - 1 and low = mid + 1.
        * Invariant: low <= floor(sqrt(x)) <= high.
          Let mid be (low + high)/2.
            - If mid^2 <= x < (mid+1)^2,
              then mid is floor(sqrt(x)) and just return it.
            - If mid^2 > x, search for values smaller than mid.
            - Otherwise, if mid^2 < x, search within higher values.
        """
        while (low <= high):
            mid = (low + high) // 2
            sq = mid * mid
            sq_next = (mid+1)*(mid+1)
            if (sq <= x < sq_next):
                return mid
            elif (sq > x):
                high = mid - 1
            else:
                low = mid + 1

for i in range(1, 26):
  assert(math.floor(math.sqrt(i)) == Solution().mySqrt(i))


Dynamically loading jQuery when it's not available or version isn't high enough

Before actually diving into creating a jQuery checker (nice idea by the way), you might really want to check some cases before building the code. There are several issues with your script here:

Your script assumes that there is jQuery. What if there's no jQuery at all? How would your script work? I suggest you stick to vanilla JS instead.
Documentation too long, didn't read, developer loaded your script first. It will break. You can't detect scripts because they are parsed in order. If your script came first, it cannot see the scripts loaded after it at the point of execution.
But what if a plugin already initialized with the version that came with the page? jQuery carries an internal cache for data, event handlers etc. If you switch jQuery now, they will break.
Dynamically loading a script is an async operation. You can't pause it right there. JS will continue. Therefore, while your script is loading a more recent version, plugins on your page might have already initialized using the one in your page.
Some plugins require a specific version of jQuery (like some prefer 1.4, or 1.6). Developers intentionally use them because some of these plugins use already deprecated API and weren't updated. If you load a newer version, they break.
If you really wanted IE support, why not just load the 1.x version rather than doing 2.x? This removes the need to detect IE. That's why there's a 1.x and 2.x version in the first place.


Unfortunately, I don't have time for a proper review, so I'll stick to the more obvious points:

Indentation in Ruby is 2 spaces, not 4.
Not only is your use of semicolons inconsistent (sometimes you use them, sometimes you don't), every single one of those you do have is superfluous. Leave them out. You can use either newline or semicolon as "statement" separator, using both is not necessary.
The same applies to your usage of the then keyword: sometimes you use it, sometimes you don't, and all uses are superfluous. Leave them out. You can use either the then keyword or a "statement" separator (newline or semicolon) to separate the condition from the then body, using both is not necessary.
There is a large number of superfluous newlines. You'd generally have one before a new class, module or method definition, but not within – if your method is so long that it needs to be broken down in sections, consider refactoring it.
You can save yourself a lot of trouble escaping all the double quotes in the giant string by using either some other delimiter (e.g. backuped = ssh.exec!(%Q[ … ]) or a heredoc.
Leave out empty parameter lists, e.g. def backup instead of def backup().
By convention, variable names that start with an underscore _ are used for variables that are ignored. So, you would really only use them for multiple assignment or unused block parameters. In fact, it is more than just a convention: Ruby will warn you about unused local variables, but these warnings are suppressed for variables starting with an underscore, because they are intended as "ignored" variables.
You should prefer public_send over send. The latter circumvents access protection, the former honors it.
Prefer &&/|| over and/or. The former actually have the precedence you would expect from them, the latter don't.
For the string inside the interpolation within your raft_backup_file string, you could use single quotes instead of double quotes. Personally, I always use single quotes unless I actually need to do interpolation or use escape sequences (or there is a single quote in the string). This makes it clear just when looking at the beginning of the string whether or not there is going to be interpolation.

Note that since you use a class variable to store part of your state (@@host), it is impossible to create more than one instance of your class, so it doesn't make sense to have a class at all.

#!/usr/bin/env ruby

require 'net/ssh'

$me = File.basename(__FILE__)

class CheckIn
  USER = 'knife'
  RSA_KEY = 'ssh/id_rsa'

  def initialize(host)
    @@host = host

    if File.exist?(RSA_KEY)
      File.chmod(0600, RSA_KEY)
    else
      abort "[#$me] ERROR: no RSA file #{RSA_KEY} found. Exit.\n"
    end
  end
end

class BackupRestore < CheckIn
  def backup
    consul_raft_db = '/opt/consul/data/raft/raft.db'
    root_backup_dir = '/root/vaul_devops_kdbx/backups'
    raft_backup_file = "#{Time.now.strftime('%H_%M_%S_%d_%m_%y')}_bkp_raft.db"

    Net::SSH.start(@@host, USER, keys: RSA_KEY) do |ssh|
      backuped = ssh.exec!(%Q[
        if test -e #{consul_raft_db}; then
            echo ""
            echo "OK: Consul DB found - #{consul_raft_db}."
            echo ""
        else
            echo "ERROR: no #{consul_raft_db} file found. Exit."
            exit 1
        fi

        if sudo [ -d #{root_backup_dir} ]; then
            echo "OK: #{root_backup_dir} found."
            echo ""
        else
            echo "ERROR: no #{root_backup_dir} directory found. Exit."
            exit 1
        fi

        if sudo cp #{consul_raft_db} #{root_backup_dir}/#{raft_backup_file}; then
            echo "OK: backup created:"
            echo ""
            sudo ls -l #{root_backup_dir}/#{raft_backup_file}
            echo ""
            echo "All backups present on the #@@host in the #{root_backup_dir}:"
            echo ""
            sudo ls -l #{root_backup_dir}
            echo ""
        else
            echo ""
            echo "ERROR: can not complete backup from #{consul_raft_db} to #{root_backup_dir}/#{raft_backup_file}. Exit."
            exit 1
        fi
      ])

      puts backuped
    end
  end

  def restore
    puts "\nRestore will be here\n\n"
  end
end

if __FILE__ == $0
  puts "\n[#$me] Consul backup/restore started.\n"

  if ARGV.length == 2 && (ARGV[1] == 'backup' || ARGV[1] == 'restore')
    host = ARGV[0]
    mode = ARGV[1]

    puts "\n[#$me] Working on the #{host} in #{mode} mode."

    run = BackupRestore.new(host)
    run.public_send(mode)
  else
    abort "\n[#$me] ERROR: HOST must be specified as first argument and MODE (backup or restore) - as second one. Exit..\n"
  end

  puts "[#$me] Consul backup/restore finished.\n\n"
end


Overall, this is pretty good code for a beginner's solution to a relatively complex problem.

But your code does have me a little lost.  For one, I'm not quite sure why you're using recursion here.  It seems like that will be a lot more memory intensive than it needs to be for a straightforward problem.  It also confused me for a good ten minutes why you were checking for isSum45 to return that the problem is solved, when the sum for the entire board is actually 405.

I would rewrite this as an iterative solution rather than a recursive solution.  I think the recursion adds a lot of unnecessary complexity to the code and flow.  I don't have the time at the moment to rewrite it as such, so I'll just give some other general comments on your code.

solve(array);
System.out.println("Solution is ");
for (int row = 0; row < 9; row++) {
    for (int col = 0; col < 9; col++) {
        System.out.print(" " + array[row][col] + " ");
    }
    System.out.println();
}

I'm not a big fan of the above implementation because it relies on the solve() method modifying the original array in place.  It also makes your paradigm of returning a boolean from the solve() method irrelevant; you never compare or check for it.  I think it would be a better design if you preserve the original board and create a new int[][] solved variable which you return from the method.

for (int row = 0; row < 9; row++) {
    for (int col = 0; col < 9; col++) {
        if (array[row][col] == 0) {
            for (int num = 1; num <= 9; num++) {
                if (noConflict(array, row, col, num)) {
                    array[row][col] = num;
                    if (solve(array)) {
                        return true;
                    }
                }
                array[row][col] = 0;
            }
            return false;
        }
    }
}

On a positive note, I really like that you named your loop variables row and col versus i and j as so many people do.  It makes your code much more readable.  But one of the principles of good code design is to avoid this kind of intense nesting as much as possible.  You can do this like the following:

for(int row = 0; row < array.length; row++) {
    for(int column = 0; column < array[row].length; column++) {
        if(array[row][column] != 0) continue;
        for(int num = 1; num <= 9; num++) {
            if(!noConflict(array, row, column, num)) continue;
            array[row][column] = num;
            if(solve(array)) return true;
            array[row][column] = 0
        }
        return false;
    }
}

This makes your code a bit less complex and a bit more readable.  I completely avoid your if(solve(array)) block by simply returning the boolean directly from the recursive method call (EDITED: As David Harkness says in the comments below, this actually changes how the method functions, so I've removed that bit.).  Also note that it my loops I compare row and column to array.length and array[row].length, respectively.  This isn't a huge deal if you always know you're going to be handling boards which are 9x9, however when you're designing code you should always try to make your code as flexible as possible.  The more flexible it is and the more scenarios it can handle, the more powerful it is.

public static boolean noConflict(int[][] array, int row, int col, int num) {

This is just general nitpicking, but you should only expose methods as public which actually need to be public.  The solve method makes sense as a public method because it's the part of the API that you will want to use in other parts of the application.  This method, however, is purely internal and thus should be private.  Also, method names should pretty much always be verbs or verb phrases.  I might rename this method to something like noConflictExists or isNoConflict.  Actually, because of the nature of how I rewrote your loops above, I would change it to conflictExists or isConflict that way my usage of it is more intuitive.  These notes also apply to your isSum45 method, which is public and might use a more intuitive name for code readability.

Also, in those two methods, what happened to your beautiful variable names?!?  Why did you suddenly move to using single letters instead of something more descriptive?


Slicing a string into three pieces, and also controlling/manipulating through loops

I concur with @200_success, looping three times and doing something different every loop is totally pointless. Regardless, if I had to use a loop for it, I would use for i in range(3) and not a while loop to do it.
I do not agree with your if (len(quote.split(' '))) >= 2:. For me this is a totally legit quote:

Awesome!
-- Barney Stinson, How I Met Your Mother

Also, the split is done twice here, at least do it before the check.
And actually, all of your code does not care if the length is 1 or even 0:
# Length 1
>>> "Awesome!".split()
["Awesome!"]
>>> " ".join(["Awesome!"])
"Awesome!"
#Length 0
>>> "".split()
[]
>>> " ".join([])
''

Note that str.split splits on white-space by default, so there is no need to do split(" "), unless you specifically do not want to also split on newlines. Incidentally, I would consider this a bug in your code. The quote Awesome\nSuit! would be recognized as one word by your code.
The only part where it is not obvious that a length 0 quote is fine is
ccString = ""
for j in range(0, len(splitQuote)):
     ccString += splitQuote[j]
print("Concatinate: ", ccString)

But range(0, 0) returns [] and a for loop over an empty list does nothing. So this is also safe. And I would suggest a different approach here, anyways.
This code is equivalent to print("Concatinate: ", "".join(splitQuote). But that's really boring and just a special case of the next loop, with an empty character. I think using random.sample would be slightly more interesting:
import random
...
print("Concatinate: ", "".join(random.sample(splitQuote, len(splitQuote))`

To improve maintainability and readability, I would put the two assignments into separate functions, where the docstring describes what the assignment was. Then I would add:
if __name__ == '__main__':
    assignment1()
    assignment2()

Last, but not least, you should have a look at PEP8, Python's official style-guide. One thing it recommends is using lower_case for variables (and functions) and not camelCase.


How do I make this simple addition code less verbose?

You may want to take a look at Pythy.

What you want seems a lot like:

PYTHY(add, x, y) (
    return x + y;
)

Make sure to read this part of the article, as pointed out by Konrad:

  It appears that we are derefencing a null pointer. Remember in C++
  when dereferencing a null pointer, undefined behavior occurs when
  there is an rvalue-to-lvalue conversion. However, since a
  non-capturing lambda closure is almost always implemented as an object
  with no members, undefined behavior never occurs, since it won't
  access any of its members. Its highly unlikely that a non-capturing
  lambda closure could be implemented another way since it must be
  convertible to a function pointer. But perhaps not?


Compare data within an interval and draw rectangles accordingly

This can be rewritten using a single map statement.

We just have normalize the data by making the first and last intervals consistent with the other intervals, which are defined by two points.  We use Infinity to do this.

The final solution will work with an arbitrary number of test intervals.

Rewrite:

function inIntervals(val, intervals) {
  var intervals = intervals.slice(0),    // this makes a copy, so we don't disturb the original array
      last      = intervals.length - 1;

  intervals[0]    = [-Infinity      , intervals[0]];  // here we normalize the first and last intervals
  intervals[last] = [intervals[last], Infinity    ];

  return intervals.map(x => val >= x[0] && val < x[1] ? 1 : 0)
}

var test = [[1], [1,3], [3,5], [5,7], [7,9], [9]];
console.log(inIntervals(1.5, test));
// [ 0, 1, 0, 0, 0, 0 ]

Update

To transform from a single element array to the format in your example:

x = [1,3,5,7,9]
var first = [x[0]];
x = x.map((x,i,a) => a[i+1] === undefined ? [x] : [x, a[i+1]])
x = [first].concat(x);


Design

Rather than bury a magic filename, consider passing it in.

//t_conf          *get_conf(void) {
//  ...
//    if (ini_parse("settings.ini", handler, conf) < 0)

t_conf *get_conf(const char *ini_file_name) {
  ...
  if (ini_parse(ini_file_name, handler, conf) < 0)

Maybe add before the if()

  if (ini_file_name == NULL) {
    ini_file_name = "settings.ini";
  }

Devoid of overall comments

Consider comments to at least convey the coding goals.

Allocate to the size of the de-referenced object

... rather than allocate to the size of the type - easier to code right, review and maintain.  Cast not needed.

//if (!(conf = (t_conf*)malloc(sizeof(t_conf))))
//            return (NULL);
conf = malloc(sizeof *conf);
if (conf == NULL) {
  return NULL;
}

// like-wise
// memset(conf, '\0', sizeof(t_conf));
memset(conf, 0, sizeof *conf);

Use auto formatting

Life is too short for manual formatting. Find and use an auto formatter - customized as needed.

Comments of typedefs not needed

As is now, this code has comments that is not required to match what is truly in "project.h" and as time goes on, can diverge.  For code posting here, post a portion of "project.h" instead.

Invalid code

include "project.h" should be #include "project.h"

Hiding objects here is bad

# define MATCH(n) (strcmp(name, n) == 0) brings in name, but not obvious from the call if (MATCH("ip")).

Alternative:

static bool streq(const char *a, const char *b) {
  return strcmp(a,b) == 0;
}
...
if (streq(name, "ip"))

Naked magic number

Buried in code is

conf->db->port = 3306;

Better to have

// near top of code
#define PORT_DEFAULT 3306

// later on
conf->db->port = PORT_DEFAULT;

Unneeded if

Just call free().  free(NULL) is OK.

//if (conf->db)
//            free(conf->db);
free(conf->db);

Like free(), I'd expect clear_conf(NULL) to not error

void clear_conf(t_conf *conf) {
  if (conf) { // add

() not needed in return and others

Many places

// return (conf);
return conf;

// conf->db->host = (strdup(value));
conf->db->host = strdup(value);

Non-standard C

Note: strdup() is not standard, yet ubiquitous.

Missing #include <>

Do not rely on "project.h" to provide them unless that is clearly a project rule.

NULL as name

Given the potential generic use of handler, I'd guard against NULL.

// printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", name, value, section);
if (name === NULL || value == NULL || section == NULL) {
  tbd();
} else {
  printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", name, value, section);
}

Further I'd bracket such strings to help detect leading/trailing white spaces in them

  printf("Le nom du champ est \"%s\", la valeur est \"%s\" (La section est \"%s\")\n",
      name, value, section);

Lack of error checking

// what if `value` is "", "abc", "123xyz", "12345678901234567890", ...?
conf->server->port = atoi(value);

// what if allocation returns NULL?
conf->server->ip = strdup(value);

Respect presentation width

        printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", name, value, section)
;

vs.

        printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n",
            name, value, section);

Another reason for an auto formatter.

Curious dual language

I'd expect one.

printf("Le nom du champ est %s, la valeur est %s (La section est %s)\n", ...
printf("Unable to load configuration\n");

Conversion changes sign-ness

unsigned port;
...
conf->server->port = atoi(value);

Perhaps a helper function

// return error status
bool to_unsigned(unsigned *u, const char *s) {
  if (s == NULL) {
    return true;
  }
  char *endptr;
  errno = 0;
  unsigned long = strtoul(s, &endptr, 10);
  if (errno || s == endptr || *endptr || value > UINT_MAX) {
    return true;
  }

  if (u) {
    *u = (unsigned) value;
  }
  return false;
}

if (to_unsigned(&conf->server->port, value)) {
  hanlde_oops();
}


Is this code likely to stand the test of time? (Add select box to DOM with JS)

To answer your question in the title: no
For multiple reasons. One being that the things we use today could be out-dated in a few years. who knows
One question/remark:
sel_obj.options[i]=new Option(op_array[i], i);
sel_obj.options[i].value=op_array[i];

is there a reason why you are setting the value twice? (once in the new Option call and once on the next rule)
My suggestions are:
Separation of concerns
You have one file with html, javascript and php all interweaved with each other. So debugging won't make it any easier. Alsog reusing a part of that script is nearly impossible since everything is hard coded.
Overuse of javascript
Is there a reason why you are building the html with javascript? Because this has some drawbacks: Screenreaders will not be able to see the selectlist items since they don't parse javascript. Serach engines will not know about the select-options.
Instead you should use PHP to create the html for the select items.
Hard to read code
The code is very hard to read, the function and variable names don't clearly tell what they are or have typehinting in the names. For instance op_array variable. Words as Array, String, int,.. should  be banned from variable names. Simply call it options. Now by simply reading it I allready know that is has multiple values and that it are the options. Where as op_array tells me that it is an array of 'op'.
Also for future enhancements. If for some reason you are going to change the way options are passed in, you will also have to change the name of the variable...
Also be more consistent in your naming. populateList() needs a select and options. But no list. This is confusing.
Personally I never use the onClick attributes inhtml. Not because they are bad. But because if you do use them, javascript will be hidden in the html and tightly coupled with it whereas if you EvntListners it is very easy to change the html without having to bother about the javascript. this is also better for sepperation of concerns


A simple error messaging and logging system via macro(s) in C++

You’ve already noted that this could be done better without macros, so I won’t belabour the point. I will note, though, that your goal—“to refresh [your] skills at writing good solid macros”—makes about as much sense as refreshing your skills at writing code on punch cards. You are exercising an archaic practice that is dying out, and is unwelcome in any modern project.
enum MsgTy {
    OK = 0,
    WARNING,
    ERROR,
    CRITICAL,
};

In modern C++, you should use a strong enum—an enum class. That way your enumerators won’t pollute the namespace.
Speaking of polluting the namespace, the almost universal convention in C++ is that all-caps identifiers are used for preprocessor defines. By using them in this case, you run the risk of someone else’s macro definitions fuggering up your enum. And given that having a macro named something like ERROR is highly likely in large enough projects, you’re really cruising for a bruising here. (Actually, POSIX reserves everything starting with E followed by a digit or uppercase letter… so you’re REALLY asking for trouble with that in particular.)
I’m also not keen on the name MsgTy. Seems a little ugly and obtuse. I get that you want it to be short but… this seems a bit much.
class FileWriter {
    std::string filename_;
    std::ostringstream msg_;
public:
    FileWriter(const std::string& filename, std::ostringstream& msg)
      : filename_{ filename } {
        operator()(msg);
    }

    void operator()(std::ostringstream& msg) {
        std::ofstream out("log.txt", std::ios::app);
        out << msg.str();
    }
};

Oi, this class is….
First off… what is the point of the data members? You don’t use either of them.
Second… what’s the point of the function call operator? You could just as well do all the work in the constructor. You never use the function call operator anywhere else.
Third… what’s the point of taking the argument as a string stream when you just go ahead and re-format it through a file stream? You’re double-formatting it.
This entire class could boil down to:
struct FileWriter
{
    FileWriter(std::string_view filename, std::string_view msg)
    {
        auto out = std::ofstream{filename, std::ios_base::app};
        out << msg;
    }
};

But even then, I’m not sure this is a great idea, because you’re reopening the file every time you’re writing a new log line, then closing it after. That doesn’t seem like a great idea, efficiency-wise.
A better idea would be to open the file once, and keep it open. Then just syncronize your writes (assuming you care about concurrency, which it sure doesn’t look like it), and flush after every log line. Normally std::endl is a terrible idea… but flushing after every line is exactly the singular use case it’s actually intended for.
static std::map<MsgTy, std::string> msg_id{
    {MsgTy::OK, {"OK: "}},
    {MsgTy::WARNING, {"WARNING: "}},
    {MsgTy::ERROR, {"ERROR: "}},
    {MsgTy::CRITICAL, {"CRITICAL: "}}
};

As far as mapping enumerators to strings, this isn’t really the best way to go about it. It’s astoundingly inefficient and clunky for what should be a trivial task. A std::map is a heavyweight object… using it for literally 4 elements is… not a good usage.
A better solution is to either implement a to_string() function:
constexpr auto to_string(MsgTy mt)
{
    using namespace std::string_view_literals;

    switch (mt)
    {
    case MsgTy::OK:
        return "OK"sv;
    case MsgTy::WARNING:
        return "WARNING"sv;
    case MsgTy::ERROR:
        return "ERROR"sv;
    case MsgTy::CRITICAL:
        return "CRITICAL"sv;
    }
}

or to implement a stream inserter for the type:
template <typename CharT, typename Traits>
auto operator<<(std::basic_ostream<CharT, Traits>& o, MsgTy mt)
    -> std::basic_ostream<CharT, Traits>&
{
    switch (mt)
    {
    case MsgTy::OK:
        o << "OK";
    case MsgTy::WARNING:
        o << "WARNING";
    case MsgTy::ERROR:
        o << "ERROR";
    case MsgTy::CRITICAL:
        o << "CRITICAL";
    }

    return o;
}

or both.
Either option will be hundreds, if not thousands of times faster than using a std::map.
#define messaging(MsgTy, msg, log2file)

Okay, this is where the meat of the code is, and this is what you really want the focus to be on. Unfortunately, this is all wrong. This is exactly the way you should NEVER write a macro.
First let’s get the initial stuff out of the way. As I mentioned above, the convention in C++ (and even in C) is that macros should be in all caps. That’s not just for style, it’s because the unconstrained text replacement of the preprocessor is so dangerous. messaging isn’t exactly an uncommon word; it’s quite likely that it could be used for another identifer… with disastrous consequences. Using all caps accomplishes two things:

it alerts people to what they’re messing with; and
the only way it could every be used again is via a redefinition… which will trigger at least a warning.

The other problem with this preamble is that you’re using the message type enumeration’s type name as the parameter name. I can’t imagine why you’d think that’s a good idea. The only reason it works in this case is that you’re using an old-style enum. If you tried using a modern enum class, this whole macro would break.
There’s another issue buried in there: if the message type is ERROR or CRITICAL, you throw an exception. Okay, but the problem is the exception you throw is a std::string. If you run your program, it’s going to crash, because you catch a std::exception… but a std::string is not a std::exception. You probably want to either throw a std::runtime_error or, better, a custom exception type depending on whether it’s a ERROR or CRITICAL message.
Finally, you’ve made a critical macro error: you have repeated the argument(s). You have correctly wrapped them in parentheses, which helps prevent unexpected interactions with the surrounding code when expanded… but doesn’t help with the fact they they’re expanded multiple times. If you use an expression that changes the first argument in particular, who knows what could happen.
Overall, this is a terrible macro, for a number of reasons. First of all, it’s needlessly long. It injects almost 30 lines of code every time it’s used! In your main(), that try block that looks like it only has 4 lines in fact expands to well over 100 lines. That’s just ridiculous.
It’s also absurdly complex. Putting control flow in a macro is not just a “eh, it’s a thing you do”… it’s an absolute last resort. That’s really the golden rule of macros: keep them as simple as possible. That’s because they’re not only so hard to debug, but also because they’re expanded everywhere. They’re also exceptionally dangerous, so they should be written as simple as possible to avoid the need to ever tweak it in the future… as it is now, any time the requirements for how to log change, you have to mess with the macro code… which is playing with fire.
And a macro this complex just destroys your performance. Firstly, it will just absolutely trash your cache because all that machine code gets dumped everywhere the macro is used. (Although, if you’re lucky, and the macro is always used as you demonstrate, the compiler can probably remove most of those ifs.) But also, there are other side effects, too: for example, if messaging() were a function, profile-guided optimization would almost certainly mark the OK path as the hot path, and optimize the code accordingly… but that’s because there’s one if in one place; as a macro, that if gets repeated everywhere the macro is used, and it’s a different if every time, so PGO won’t help you much.
As it is, the macro’s code is in dire need of a rewrite, because it’s so repetitive, and there’s so much hard-coded in there (specifically the file name, over and over and over). But screwing with a macro is always a dangerous proposition; it’s MUCH riskier than refactoring a function. (It’s also sometimes much more frustrating, because the moment you touch a macro, you have to recompile everything, whereas a function can (sometimes!) be tweaked in isolation.)
And not only is it dodgy to use, hard to maintain, and inefficient… it’s also a terrible interface! Why is it necessary to specify whether you want the message written to the file or not on EVERY call? Isn’t assuming true a good default? With a function you could use an overload or a defaulted parameter for that, no problem.
At a bare minimum, to improve this macro, you should refactor as much as possible into functions:
#define MESSAGING(mt, msg, log_to_file) do { \
    auto const mt_ = (mt);

    if (mt_ == MsgTy::ok) \
        messaging_ok((msg), (log_to_file)); \
    else if (mt_ == MsgTy::warning) \
        messaging_warning((msg), (log_to_file)); \
    else if (mt_ == MsgTy::error) \
        messaging_error((msg), (log_to_file)); \
    else if (mt_ == MsgTy::critical) \
        messaging_critical((msg), (log_to_file)); \
} while (false)

Now you can fuss with the logic of each option safely.
Even better would be use static dispatch for this kind of thing. You could create a few types (ok_t, warning_t) and instances of those types (ok, warning), and then dispatch based on those:
struct ok_t {};
inline constexpr auto ok = ok_t{};
// etc. for the other message types

auto messaging(ok_t, std::string_view msg, bool log_to_file = true)
{
    std::cout << "OK: " << msg << std::endl; // endl to flush

    if (log_to_file)
    {
        auto out = std::ofstream{"log.txt", std::ios_base::app};
        out << "OK: " << msg;

        // or better yet, have a class that keeps the log file open
        // and just appends to it, rather than opening and closing
        // it repeatedly.
    }
}
// etc. for the other message types

messaging(ok, "Everything is good!");
messaging(warning, "Something isn't quite right!", false);
messaging(error, "Something went wrong!");
messaging(critical, "Something horribly went wrong!");

But that’s just one of dozens of techniques you can use to AVOID the use of macros… which is a much more useful skill to have in 2020.
In other words, all this has brought us back to the original point I wasn’t going to belabour. The best macro is the one you don’t write.
Questions
Are there any apparent issues with how I implemented the macro?
Yes, it is needlessly long and complex. Even for a non macro function, this is unnecessarily long and complex. It should be refactored into smaller functions for each of the four different behaviours.
Can there be any improvements made to it?
The best way to write a macro is: don’t.
I can’t conceive of why anyone would want to write a macro in 2020. Macros were a dirty hack when they were first created back in the 1970s. There may be a few very rare cases where you still need them, but by and large, if you can possibly solve a problem without macro, then THAT is the skill you should be exercising.
Is the intent clear on its usage?
Eeeh? Not really.
Is this the intended usage:
messaging(MsgTy::OK, 42, true);

Is this:
// won't work, but is it intended to?
messaging(MsgTy::OK, "a" << "b" << "c", true);

I'm also interested in any other feedback.
Don’t waste your time honing skills that nobody wants. Macros are old tech that are only, at best, tolerated, and only when there is absolutely no other option. The best skills you can learn regarding macros are ways to NOT use them. A programmer who is a master at writing macros, but because they don’t know all the ways they can avoid them always falls back to writing them, is less than useless to me on my projects.
Bottom line: Don’t waste your time. Getting good at writing macros helps no one. Instead, learn the techniques for AVOIDING macros. THOSE are skills that are actually useful in 2020 and beyond.


Python unit testing for a Stack data structure

There are certainly some good tests here. In a related question for Java, the answer by Phil Wright states:

  Here are some tests I'd perform at the very least. There may be more
  you'd want:

  Create an empty Stack. Test that its size is 0.
  Push an element onto the stack. Test that its size is now 1.
  Push another element onto the stack. Test that its size is now 2.
  Pop an element from the stack. Test that it matches the 2nd pushed value. Check that the size of the stack is now 1.
  Pop an element from the stack. Test that it matches the 1st pushed value. Check that the size of the stack is 0.
  Attempt to pop an element from the stack. You should receive an ArrayIndexOutOfBounds exception.

At a quick glance, you do most (if not all of these tests). So in some sense the coverage is good.

The amount of testing may be overkill. You have to realize you can't test every possible thing. With that in mind your tests should:

Find current issues with your code.
Nip likely future issues.
Prevent errors you've had in the past from coming back.

The past, present, and future. So for example, your function test_peek_push3_pop1 may have a good reason for being there. Maybe you had designed a stack before and had issues with pushing 3, popping 1, and then peeking. I've never personally had such an issue. It seems like a weird test case I wouldn't consider it, but maybe you have. If you have a compelling reason to have that test you should explain your reasoning in a comment so I can understand the purpose of the test. Ultimately:

  Think and comment WHY you have a test.


The trouble is that your check can fail.  Before you can call the children method you need to be sure that you are dealing with an object (that provides the children method).  This is actually what your fatal error is telling you ($current->AttributeSets is a non-object).  You get this in your if statement within your isset call.

The trouble with fatal errors is that they are fatal.  There is no way to recover from them.  The PHP engine is about to shutdown.  You can read more about handling errors in an answer I wrote here.  The only way is to avoid fatal errors.  Don't call functions that don't exist, or methods on something that is NULL.

Possibly the reason you have this problem is breaking the Law of Demeter.  I don't know how the XML objects you are working with are built, etc.

You could solve it by checking each component.

Unfortunately you can't do this because isset can't use a function's return value:

// THIS WON'T WORK
isset($current->AttributeSets,
      $current->AttributeSets->children('ns2', true)) // Function Return Value

However as mseancole commented you can set the components as variables.

if (isset($current->AttributeSets))
{
    $children = $current->AttributeSets->children('ns2', true);

    if (isset($children,
              $children->ItemAttributes,
              $children->ItemAttributes->ListPrice, // etc.


The code is mostly fine, however there are some problems:
SET(BOOST_ROOT "C:/Program Files (x86)/boost/boost_1_74_0")

^ This is wrong, because other developers may have Boost installed into different directory. Remove this line and let the user set BOOST_ROOT during configuration.
include_directories(${BOOST_ROOT})
include_directories(${BOOST_ROOT}/stage/lib)

^ Why is this required? The later find_package(Boost ...) call should set all required directories for you, which you can use in include_directories. This actually shouldn't be required at all, because linking to Boost using target_link_libraries should also set correct include directories.
add_executable(Odin ...
)

add_library(Engine ...
)

^ This looks wrong. First, you can remove code duplication by placing source files list into a variable:
set(SRCS ...
)

add_executable(Odin ${SRCS})
add_library(Engine ${SRCS})

Second, it looks strange that both library and executable consist of same source files. You probably want to keep most files being a part of the library and then link the library to executable. This is achieved by the same target_link_libraries command.
set(CMAKE_MODULE_PATH "${doctest_SOURCE_DIR}/scripts/cmake"
        ${CMAKE_MODULE_PATH})

^ Use list(APPEND ...), just like you did earlier in the code.


Comparing arrays with source questions and user answers

This is not much of a code review answer, but I don't have time for more right now :(

Here's a stripped down version using only arrays for answers, with indexes (zero to four) as the question numbers. Essentially, it seems like much of your object structures aren't needed at all.

const correctAnswers = [1,4,2,1,3]

const userAnswers = [1,1,1,1,1]

const countRightAnswers = answers => answers.filter((a, i) => a == correctAnswers[i]).length

const indexOfRightAnswers = answers => answers.map((a, i) => a == correctAnswers[i] ? i : -1).filter(i => i > -1)

console.log(countRightAnswers(userAnswers))
console.log(indexOfRightAnswers(userAnswers))

Try it online!


AnimationFrameController: requestAnimationFrame made easy

What about two AnimationFrameControllers

That will work just fine?

As a games/visualisation programmer I would not use your  AnimationFrameController. It is just a callback stack, with ugly bits and would be difficult to use (you are catching my throws), GC unfriendly, carries a bad bug if I use  AnimationFrameController.pause = false; and should be a singleton

A breakdown of your code.

Don't use class, its is really bad and makes it so hard to write good javascript.
AND
You will only ever need one instance of AnimationFrameControler so it should be a singleton.

class AnimationFrameController {
  constructor( autostart = true ){
    this.autostart = true;
    this.paused = true;
    this.time = 0;
    this.fps = 0;

callees & calleesTime do not need to be exposed, programmers will just side step your add/remove function trying to take short-cuts then if you ever change the behaviour you will have a list of upset emails. "Why your code break?" Don't expose what should not be exposed.

Also why keep two arrays, why not just a simple object added to callees array {callback : callback, time : time}

    this.callees = [];
    this.calleesTime = [];
  }

Just bad a function call to get a exposed value. Use get to get abstract values not object properties.

  get time(){
    return this._time;
  }

  set time(v){
    this.fps = (v - this.time) / 1000;
    this._time = v;
    return this._time;
  }

Again pause is a property of AnimationFrameController why force a function call to get its value.

  get paused(){
    return this._paused;
  }

BUG: This function is will generate additional requestAnimationFrame loops on top of the current loops.

  set paused(v){
    this._paused = v;
    if( this._paused === false ){ // if not paused
      this.loop( this.time );     // call loop which on the 3rd line requests an animation fame without checking if
                                  // there is one currently pending..
    }
  }

  add( ...handlers ){
    handlers.forEach( handler => {
      if(handler instanceof Function){
        this.callees.unshift( handler );
        this.calleesTime.unshift( this.time );
      }
    });

Bad style this code would not pass a linter without a pile of opt outs. Always add { }

    if(this.callees.length && this.autostart && this.paused) this.paused = false;
  }
  remove( ...handlers ){
    handlers.forEach( handler => {

Why let for a function scope? Incorrect scope declaration can lead to bugs, use var if the variable is function scoped.

      let index = -1;
      while((index = this.callees.lastIndexOf( handler )) >= 0){
        this.callees.splice( index, 1 );
        this.calleesTime.splice( index, 1 );
      }
    });

Missing {}

    if(this.callees.length <= 0) this.paused = true;
  }
  loop( time ){

This try catch would be very annoying during development, completely unacceptable in release code.

You are not responsible for the functions you call and you should not attempt to circumvent any error handling system they have in  place by adding a cover all try catch. If there is a potential error to be thrown by your code then check for it and handle it. Don't use try catch unless you are at the application level.

try {

  if( !this.paused ){

    window.requestAnimationFrame( this.loop.bind(this) );

Is there any particular reason you use let here???

    let delta = time - this.time;
    this.time = time;

The next section is just wrong for way too many reasons. This is an animation controller, the number one enemy of animations is GC and you are just creating dead memory for no reason. Also forEach is SLOW SLOW SLOW just use a standard for loop it is much more efficient.

    this.callees.map(( handler, index ) => {
      let progress = time - this.calleesTime[index];
      return handler( delta, progress ) === false ? handler : true;
    }).forEach(handler => {
      return handler !== true ? this.remove(handler) : 0;
    });

Above code rewrite. The following will not use up memory, and be an order of magnitude quicker.

    var i; // << hoist
    for (i = 0; i < callees.length; i += 1) {
        if (callees[i]( delta, time - this.calleesTime[i] ) === false) {
            this.remove(callees[i]);
            i--; // so you don`t skip a item
        }
    }

  }

} catch(e) {
  this.paused = true;
  console.warn('An error has occurred while running the AnimationFrame.', e);

}


DAL Returns a collection of business objects in MVP

You don't want to pull the entire Employee table unless necessary.

public IEnumerable<Employee>  GetNewEmployees()
{
    string selectStatement = "SELECT Employee.Emp_ID, Employee.Initials + ' ' + Employee.Surname AS Name,...";

    using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
    {
        using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
        {
            sqlConnection.Open();
            using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    yield return new EpfEtfMaster(){
                        EmployeeID = (int) dataReader ["emp_id"],
                        EmployeeName = (string) dataReader ["Name"],
                        AppointmentDate = (DateTime) dataReader["appointment_date"],
                    };
                }
            }
        }
    }
}

By switching to IEnumerable and yield return, when you call GetNewEmployees().First(), only the first row is read.

The names like sqlCommand, sqlConnection and dataReader can be shortened to command, connection and reader without affecting the reader.
Try to not repeat yourself with SomeThing someThing = new SomeThing(...);. The first class name can be replaced by using var.

Result :

using (var connection = new SqlConnection(db.GetConnectionString))

new SqlConnection(db.GetConnectionString)

Use verb for method and noun for field/properties. Here GetX suggest it is a method but is used like a property, you can rename it to ConnectionString.


keep track of friends and number of days not spoken to, dynamic memory location

First of all the "growArray" function will never be called since you put it inside an if block that runs only once. when the if statement is evaluated your size is 10 and your next_element+1 is 1 and you never check for (size == next_element+1) again.


More efficient way to loop through an object

Indeed there is! Use prepared statements instead of manually escaping and inserting into your query!

  Please, don't use mysql_* functions in new
  code. They are no longer maintained and are
  officially deprecated. See the red
  box? Learn about prepared
  statements instead, and use
  PDO or MySQLi - this
  article will help you decide which. If you choose
  PDO, here is a good tutorial.

//mysqli connection somewhere around here...

if (!empty($school_details_new)) {
    $stmt = mysqli_prepare($conn, "INSERT INTO `SchoolDetails` (`personID`, `School`, `Type`, `End_Date`, `Degree`, `Notes`) VALUES (?, ?, ?, ?, ?, ?)";
    foreach ($school_details as $school) {
        mysqli_stmt_bind_param($stmt, "isssss", $id, $school["school"], $school["qualification"], $school["date_grad"], $school["course"], $school["notes"]);
        mysqli_stmt_execute($stmt);
    }
}


Watch for CRUD state changes and make sure only one is active at once

I assume that when you say that you want your code to be "dried" up, you want your code to be more DRY, right?

Well right now, you are doing quite a bit of repeating: you've created individual conditional statements for each property of an object.

Your code would be much more DRY if you iterated through the object and checked the properties as you iterated.

Since we are handling an object, let's use a for/in loop:

for(var i in $scope.actions) {

}

In every conditional statement that you wrote, you checked to see if a property was equal to true.

That should be the first thing we check here:

for(var i in $scope.actions) {
    if($scope.actions[i])

    }
}

Notice how there is no === true at the end of the conditional? JavaScript already checks to see if the conditional reduces to true automatically.

Now we have to find a way to set the other two values in the object to false in a DRY way.

I think it would be best to create a function that takes in one argument that is the name of the property that should not be set to false, and then the function sets the other properties to false

That would look like this:

function setPropertiesToFalse(obj, except) {
    for(var i in obj) {
        if(i != except) {
            obj[i] = false;
        }
    }
}

Now the main code would look like this:

for(var i in $scope.actions) {
    if($scope.actions[i]) {
        setPropertiesToFalse($scope.actions, i);
        break;
    }
}

I added a break statement into your code because the original code uses if/else, so if a conditional were to pass, the rest would not be checked.


Note that I am completely unfamiliar with the american(?) grade system and GPAs -- I am reviewing the coding style and approach, not whether or not the solution is correct.

General notes:

Your GPA class is not really a class. It's actually just a function. It could just as well be implemented as double calculateGPA(std::vector<std::pair<char, unsigned>>). Beware of the golden hammer, especially when it comes to classes.
You can use std::tolower() to halve the size of your switch.
vector comes after utility in the alphabet :-)
C++11 allows writing >> in nested templates.
Your program won't compile: totalGradePoints is called sumGradePoints.
You can probably use float instead of double.
Make the local variables in calculateGPA() floating point numbers from the start, and drop the cast.
obj should be called gpa or something like that.
Write unit tests.

  Are plain types okay for the letter grades and credit hours, or could they be public typedefs?

Either is fine. Using a typedef makes the intent of a variable a bit clearer. This added distinction between types could help the developer realizing he or she is making a mistake. However, a typedef is sadly just a type alias and does not create a new type! In other words, you do not get any type-safety benefits of doing so.

To get full type safety, you would need to create a (templated) wrapper class around the types in question. Doing so would be a nice exercise when you start to learn about templates.

  Should operator<< need to call calculateGPA(), or should I create a private accessor and have that called?  In order to maintain encapsulation, I'll need to keep operator<< as a friend.

I would cache the result of calculateGPA and provide an accessor to it. Have operator<< call that accessor. This means that your class would need to invalidate the cached value whenever grades is modified.

  Is the for-loop in calculateGPA() ideal for this purpose, or are there one or more STL functions that can do the same thing but more cleanly?

The for loop is sufficiently short and sweet, and makes just a single pass (unlike most other solutions I can think of). You could always use std::accumulate and a lambda, but you would have to do so for both sumCreditPoints and sumGradeHours.

Am I guilty of converting you to the const& style? :-)


Ricochet Challenge: Robust IO and working with different types of numbers in Haskell

You can reduce the fromIntegral spam like this:

ricochet :: (Integral a, Fractional b) => a -> a -> a -> a -> b -> (Corner, a, b)
ricochet h w m n v
    = (c,b,fromIntegral d / v)

    where
    h' = h - m
    w' = w - n
    d  = lcm w' h'

The return value of functions like - and lcm is of the same type as their arguments, so the types of h' and the like can be inferred. You do need to write fromIntegral d / v because the compiler doesn't perform automatically the conversion required for the division operator. It's frequent to have these conversions functions at "type cast" boundaries.

But what if you want to keep the explicit signatures, for clarity? You can use "explicit forall" along with the ScopedTypeVariables extension, which allow you to say "this type here is the exact same type as the type in the top-level signature".

{-# LANGUAGE ScopedTypeVariables #-}
module Main
    ( Corner(..)
    , ricochet
    , main
    ) where

data Corner = UL | UR | LR | LL deriving (Show, Eq)

ricochet :: forall a b. (Integral a, Fractional b)
         => a -> a -> a -> a -> b -> (Corner, a, b)
ricochet h w m n v
    = (c,b,fromIntegral d / v)

    where
    h', w', d :: a
    h' = h - m
    w' = w - n
    d  = lcm w' h'


Assign monthly interest rate based on credit card input

Watch your scope - in your class you keep your data in two places - local variables, and static members. I cannot see any thought behind choosing where to put them - you pass some around in your method signatures, but then you use the others in the same methods... The most acute case is in calculateMinPayment where you pass the static member newBalance as a parameter and use it inside the method, while totally ignoring (and overriding) the parameter...

In the use-case above, in the name of encapsulation, I believe the correct way is to only keep the state as local variables, passing the needed data to the stateless helper methods, rather than keeping anything in the static state.

Comments - I personally think that comments are a code smell. When the code is clean and readable - comments are superfluous. You've got a lot of comments, and some are more confusing than helpful, since you put them in the wrong location:

// make sure that the number entered is a double and if so read it in.
// if not, use a default value of zero. No error message to the user.
System.out.print("Type the balance: ");
priorBalance = keyboard.nextDouble();

if (keyboard.hasNextDouble() == true) {
    interestRate = 0.0;
} else {
    interestRate = 0.02;
}

The above comments should be placed after setting priorBalance, since they describe interestRate... They are more confusing, since the code does not do what the comment say - it sets the interestRate at either 0.0 or 0.02, then totally ignores the given information, and tries to get nextDouble() even if the last statement returned false.

BTW - don't use if (keyboard.hasNextDouble() == true) - if (keyboard.hasNextDouble()) does exactly the same, and is more readable.

// make sure that the number entered is a double and if so read it in.
// if not, use a default value of zero.  No error message to the user.
System.out.print("\nType the new charge amount: ");
addtlCharges = keyboard.nextDouble();

Was that a result of an unfortunate copy+paste? Again - comment is not helpful, only confuses.

I also believe the prompt Type the new charge amount will appear only after the user entered it, since you check hasNextDouble() before you print the prompt.

// first create a stub and get the input and output working
// then replace the stub later on with the calculation

I don't even begin to understand what this means, and what it has to do with the code it describes... not the second time either...

Naming - give variables and methods names which imply their role in your code - what does this line do?

newBalance = calculateInterest(priorBalance, addtlCharges);

Calculates interest or the new balance?

Also, don't be lazy say - additionalCharges - there are no fines for long names.


Upload a directory, in parallel, to an artifact repository

I think you'll find that inotify has problems of its own and that you're already on the right path.

The approach I'd use: get this working the way you want, then run it in a loop while your wget runs, removing successful files as it goes.

If you're concerned about polling overhead (I wouldn't be: the size of the directory should remain manageable so long as you're uploading/deleting along the way), have the wget process emit filenames into a log file or a named pipe, while the curl process consumes them.

You can attack the resource problem in a couple of ways. One, use exec to launch curl so that there isn't an intermediate bash process sitting around waiting for curl to exit.  Two, keep count of the number of children, and reap them when the number gets too high.  Three, check ulimit -u and consider increasing that number.

In the code below I've made a few lesser edits:

content-types in an associative array with sensible default
use [[ ]] instead of [ ] (the former is a bash builtin)
clean up the find command line a little.  I've guessed that the sed invocation is meant to remove $local_repo?
omit forked echo and curl-HEAD; rely on exit status instead
use curl's -w to get a useful line of output on success
store pids in an associative array with filenames as values, to allow meaningful response to outcomes
"Content-type" has a lowercase t
run upload in infinite loop, keep count of files found, exit when no more files are found

There may be some bugs, since I don't have your environment to test.  Proceed accordingly.

#!/usr/bin/env bash
reap() {
    for pid in ${!pid2fn[@]}
    do
        local fn=${pid2fn[$pid]}
        if wait ${pid}
        then
            echo successful upload of $fn
            # rm $fn
        else
            echo $fn upload failed with status $?
        fi
        unset pid2fn[$pid]
    done
}
upload() {
    local local_repo="${1:?no resource directory supplied}"
    local remote_repo="${2:?no destination repository supplied}"
    local default_ct=application/octet-stream
    local user=${3:-${USER:-$(read -p "Username: "  user && [[ -n $user ]] && echo $user) }}
    local pwd=$(read -s -p "Password: "  pwd && [[ -n $pwd ]] && echo $pwd )
    local max_children=100
    local found=0
    declare -A pid2fn
    declare -A types=(
        [jar]=application/java-archive
        [md5]=application/x-checksum
        [pom]=application/x-maven-pom+xml
        [sha1]=application/x-checksum
        [txt]=text/plain
        [xml]=application/xml
    )
    for art in $( find "$local_repo" -type f -name "[^.]*" -not -name index.html | sed s,^$local_repo/*,, )
    do
        let found=found+1
        local ct=${types[${art##*.}]:-$default_ct}
        local dest="$remote_repo/$art"
        local status="$art -> $dest | response %{http_code} sent %{size_upload} bytes\n"
        exec curl -u "$user:$pwd" -X PUT -d "@$art" -H "Content-type: $ct" -w "$status" "$dest" 2>&1 &
        pid2fn[$!]=$art
        [[ ${#pid2fn[@]} -ge $max_children ]] && reap
    done
    reap
    [[ $found -gt 0 ]]
}
while upload "$@"; do :; done


The answer really depends on what you're building. For example, if you're building a grid of labels and entry widgets then a simple data structure and loop is all you need. For example:

fields = [
    {"id": "sys_desc", "label": "System description", "default_value": ""},
    {"id": "model", "label": "Model", "default_value": ""},
    ...
]
self.labels = {}
self.entries = {}
for field in fields:
    label = tk.Label(self, field["label"], ...)
    entry = tk.Entry(self, ...)
    entry.insert("end", field["default_value"])

    self.label[field["id"]] = label
    self.entry[field["id"] = entry

self.label["sys_desc"].grid(...)
self.entry["sys_desc"].grid(...)
...

Another solution is to create a helper class or helper function so that your code looks something like this:

self.add_widget(self, "sys_desc", "System Description", "default value...", row=1)
self.add_widget(self, "model", "Model", "default model", row=2)
self.add_widget(self, "serial", "Serial Number", "default serial value", row=3)
...

Or with classes:

self.sys_desc = LabelEntry(self, "System Description", ...)
self.model = LabelEntry(self, "Model", ...)
self.serial = LabelEntry(self, ...)
...

There is no single answer for all layouts. Complex layouts require complex code, simple layouts can be built with simple code. The bottom line is to look for patterns, and make helpers to help reduce repetitive code.


William Fractal technical indicator implementation

Looks good, just a few ideas:

Since the function only returns two series, you can save some overhead by removing the copy() and just working with series.

np.logical_and.reduce() allows you to build the shifted series in a comprehension (and also seems slightly faster than chaining & & &, based on some rough testing).

Instead of testing shift(2) against 4,3,1,0, I find it more intuitive to test the unshifted series against -2,-1,1,2.

def wilFractal(df):
    periods = (-2, -1, 1, 2)

    bear_fractal = pd.Series(np.logical_and.reduce([
        df['high'] > df['high'].shift(period) for period in periods
    ]), index=df.index)

    bull_fractal = pd.Series(np.logical_and.reduce([
        df['low'] < df['low'].shift(period) for period in periods
    ]), index=df.index)

    return bear_fractal, bull_fractal

An alternative idea is to use Series.rolling() with a window size of 5 and check if the center value in each window is the max (bear) or min (bull):
def roll(df):
    bear_fractal = df['high'].rolling(5, center=True).apply(lambda x: x[2] == max(x), raw=True)
    bull_fractal = df['low'].rolling(5, center=True).apply(lambda x: x[2] == min(x), raw=True)
    return bear_fractal, bull_fractal

The rolling() code is more concise, but it turns out your shift() version scales better (memory permitting)!


Create two random teams from a list of players

Review

Don't use the main entry point to implement an algorithm. Create a method instead.
Think about how to allow this method to be usable for all kinds of types, not just integers. You have implemented the algorithm for integers, yet you show an example with strings.
When creating an algorithm, surely you have made some unit tests, at least for the happy paths. Feel free to include them in the question.
Use clear variable names, and stick to one written language.
Don't mix algorithm logic with Console output.

A possible method signature could be:

public static IEnumerable<IEnumerable<T>> SplitRandom<T>(
    this IEnumerable<T> source, int targetCount)
{
    // .. algorithm implementation
}

Called as..

var names = new [] { "John", "Mike", "Alice", "Bob" };
var teams = names.SplitRandom(2);

Or as..

var numbers = Enumrable.Range(1, 10);
var numberGroups = numbers.SplitRandom(2);


How to improve the way I handle greping in this script

Use more quotes, as the saying goes.

I find while true is more clear, but the idiomatic while : is also popular.

You might want to use an array for the patterns, then you can simply loop over it (for pattern in "${patterns[@]}") instead of using seq and the if statement.

Uppercase variables are usually used for exports; that is, stuff which is relevant outside your script.

You should avoid cluttering ~; use tmp_dir="$(mktemp -d)" instead.


After your comment, the only change i could say is to change

private void jump(){ // called every frame
    if(jumping){
        if(y >= -jumpHeight){
            y -= jumpSpeed;
        }else{
            jumping = false;
            falling = true;
        }
    }

    if(falling){

to

private void jump(){ // called every frame
    if(jumping){
        if(y >= -jumpHeight){
            y -= jumpSpeed;
        }else{
            jumping = false;
            falling = true;
        }
    }

    else if(falling){

To avoid to check falling too if it's jumping. But its a macro optimization (useless too maybe in this case.)
But really, this code is perfect how it is. So go ahead!

Just got this idea in my mind: you could define a "PlayerStatus" enum with: Falling, Jumping but it will affect the logic of your game, change it only if you think you will need more status and maintain two boolean variables (or more if you add more conditions) will be hard. If you need only one turned on and others off.. it's a great way to do it:

enum PlayerStatus
{
    FALLING,
    JUMPING
}

and use the enum to change the status..

PlayerStatus status;
status = PlayerStatus.FALLING;


Although you used a Validator class, this is not really object orientated. Actually I'm missing a Rule class. Your rules are applied by comparing strings right now, which is error prone and really ugly if you need to refactor it. Extending your code with new rules also requires changing the Validator itself.

class Rule {
     /**
      * @return bool
      */
     abstract function check($value);
     /**
      * @return string
      */
     abstract function getErrorMessage($value)
}

class BetweenRule extends Rule{ //Maybe there is also an IntegerRule to collect some operations.
     private $min;
     private $max;

     public function __construct ($min,$max) {...}

     public check($value)
     {
          return this->min<=$value && $this->max>=$value;
     }

     public function getErrorMessage($value) { return $valus." is not between ..." ;}
}
...

And the usage:

$v = new Validator();
$r=new RequiredRule();

$v->setRule('email', [$r, new BetweenRule(5,255), new EmailRule()]);
$v->setRule('password', [$r]);

if (!$v->getErrors()) {  //either as a list of string or list of map fields and rules
     ...
} else {
     ...
}

As you can't type hint the content of an array, you might also want to replace setRule by addRule and append new rules to the existing ones, instead setting the array of rules.

$v = new Validator();
$v->addRule('email', new RequiredRule());
$v->addRule('email', new BetweenRule(5,255));
$v->addRule('email', new EmailRule());


Haskell functions to extract and reverse integers hiding in strings

Let's take one function at a time, until we're all done.

sepInt

sepInt n = if n >= 10
            then  ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])
            else n `mod` 10 : []

First things first: you'll definitely want to learn a bit about precedence! Normally I'm in favor of adding some unnecessary parentheses if it helps disambiguate a strange situation or if the operators involved aren't often mixed, but too many of them can get in the way of readability. Also, take advantage of that sweet syntactic sugar for lists that the language provides! So iteration one of this function is

sepInt n = if n >= 10
            then sepInt (n `div` 10) ++ [n `mod` 10]
            else [n `mod` 10]

Now, as we all know, building up a linked list by repeatedly appending to the end is a bit inefficient. Probably for such small lists as you'll be using in test cases here it won't matter, but it's a good idea to get in the habit of paying attention to some of the easiest stuff, so let's try to improve this a bit. We have a choice here: either we can keep the interface of this function as-is, that is, always output a list in the right order, or we can choose to change the interface, and change all the call-sites of this function. I think for this case we can keep the interface. The idea we'll take is to build up the list backwards, then reverse it at the very end. The name go is traditional for local workers.

sepInt = reverse . go where
    go n = if n >= 10
            then [n `mod` 10] ++ go (n `div` 10)
            else [n `mod` 10]

There's something a bit funny about this base case to me. It seems like it's not the most basic one you could choose. If we let the "loop" run one more time...

sepInt = reverse . go where
    go n = if n > 0
            then [n `mod` 10] ++ go (n `div` 10)
            else []

There's a few things I find more satisfying about this: our base-case input is 0, a common base for Integers; our base-case output is [], a common base for []s; and there's no duplicated code in the two branches of the if. Finally, I think I'd choose to replace the if-then-else with a pattern match, noting however that this function has a slightly different behavior for negative numbers. Since we were never really doing the right thing for negative numbers, this doesn't bother me too much.

sepInt = reverse . go where
    go 0 = []
    go n = [n `mod` 10] ++ go (n `div` 10)

If we're feeling fancy, we can choose to use divMod instead of two separate calls to div and mod; and we can unroll the definition of (++); but I think neither of these is terribly important. Nevertheless, they're idiomatic, so:

sepInt = reverse . go where
    go 0 = []
    go n = let (d, m) = n `divMod` 10 in m : go d

Okay, let's check our work. We already know that the final thing works differently for negative numbers, so let's only check non-negative ones.

*Main Test.QuickCheck> quickCheck (\(NonNegative n) -> sepInt n == sepInt' n)
*** Failed! Falsifiable (after 2 tests):
NonNegative {getNonNegative = 0}

Whoa, whoops! Can you figure out which refactoring above was the culprit? =)

Now we have to decide whether we like the old behavior better or the new one. I think in this particular case we should like the old behavior better, since the goal is to show a number, and we'd like 0 to show up as "0" rather than as "". It's a bit ugly, but we can special-case it. Since we like our future selves, we'll leave ourselves a note about this, too.

-- special case for a human-readable 0
sepInt 0 = [0]
sepInt n = reverse . go $ n where
    go 0 = []
    go n = let (d, m) = n `divMod` 10 in m : go d

Now the test passes:

*Main Test.QuickCheck> quickCheck (\(NonNegative n) -> sepInt n == sepInt' n)
+++ OK, passed 100 tests.

getStuff

getStuff (x:xs) = if isJust x || null xs
                    then fromJust x
                    else getStuff xs

This name sure leaves something to be desired! And it leaves another important thing to be desired, too: there's lots of inputs where it just crashes. Nasty! It turns out that you never call it on inputs of that form later, but totality is another good habit that you should get yourself into. It's just another tool in the mature programmer's defensive programming toolbelt. In our case, we'll want to handle cases like [], or [Nothing], or [Nothing, Nothing], etc. where there's no good answer to return. What should we return if that happens?

One simple and quite common choice is to change our type from

getStuff :: [Maybe a] -> a

to

getStuff :: [Maybe a] -> Maybe a

but I think that's a bit short-sighted. Ignoring for the moment the inputs we know we're going to call this thing on, we've observed already that there's times when there's no good answer to return, and there's times when there is a good answer to return, so Maybe a seems like a good start, but there's also times when there are two good answers -- or more! So let's use a type that reflects this scenario instead:

getStuff :: [Maybe a] -> [a]

It's not too hard to fix up the code. First we'll just fix the type errors:

getStuff (x:xs) = if isJust x || null xs
                   then [fromJust x]
                   else getStuff xs

This isn't obviously better, since it still fails in all the same situations it used to fail, and it never returns multiple answers. So we should differentiate the two cases that lead us to the then branch:

getStuff (x:xs) = if isJust x
                   then fromJust x : if null xs
                         then []
                         else getStuff xs
                   else getStuff xs

Now, we have this if null xs branch primarily because getStuff still isn't total (it can't handle an empty input list). Instead of protecting ourselves from calling getStuff in this case, we should just let getStuff deal with empty lists correctly. So:

getStuff [] = []
getStuff (x:xs) = if isJust x
                   then fromJust x : getStuff xs
                   else getStuff xs

Actually, using isJust and fromJust is also a code smell, for the same reason as the rest of the changes so far: fromJust is partial. Instead of protecting ourselves from calling fromJust on inputs it can't handle, we should write our code in a way that avoids partial functions. Here's how:

getStuff [] = []
getStuff (Just x  : xs) = x : getStuff xs
getStuff (Nothing : xs) =     getStuff xs

(I've added a little creative whitespace to show parallels between the branches.) The only thing I'd change now is to pick a better name. For example, catMaybes might be an okay name for this. I'll mention one more thing, which is that this can also be implemented quite beautifully as a list comprehension:

catMaybes xs = [x | Just x <- xs]

By the way, this function is available from Data.Maybe.

base10IntTOstring

base10IntTOstring num =
                 let chars = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (0, '0') ]
                     numbahs = sepInt num in
                     map getStuff ( map (\a -> (map (\(x,y) -> if a == x then Just y else Nothing ) chars ) ) numbahs )

There are better ways to construct that lookup table! For example, I might choose

chars = zip [0..9] ['0'..'9']

(If you haven't seen zip before, I encourage you to try to code it up yourself! Then check the Report and compare answers.) Additionally, we're going to have to change things up a little, since we've changed how getStuff works and base10IntTOstring calls getStuff. Before, we had getStuff :: [Maybe a] -> a and hence map getStuff :: [[Maybe a]] -> [a]. Now, we have catMaybes :: [Maybe a] -> [a] and hence map catMaybes :: [[Maybe a]] -> [[a]]. Since we expect each of the lists in the output of that to be singleton lists, we can smash them all together with concat:

base10IntTOstring num =
                 let chars = zip [0..9] ['0'..'9']
                     numbahs = sepInt num in
                     concat (map catMaybes ( map (\a -> (map (\(x,y) -> if a == x then Just y else Nothing ) chars ) ) numbahs ))

Actually, this whole process at the very end is quite roundabout! If you squint, it looks like what we're really trying to implement here is a little function

lookupList :: Eq k => [(k, v)] -> k -> [v]

which we can use to index into our lookup table with the digits of our integer. So let's try to write this directly! Taking a cue from the final implementation of catMaybes above, we can write

lookupList table k = [v | (k', v) <- table, k == k']

Now our implementation can look like this:

base10IntTOstring num =
                 let chars = zip [0..9] ['0'..'9']
                     numbahs = sepInt num in
                     concat (map (lookupList chars) numbahs)

In fact, there's even a function concatMap that squashes those two things together. Veteran Haskellers will prefer to spell this function in its infix, polymorphic form as (>>=)

base10IntTOstring num =
                 let chars = zip [0..9] ['0'..'9']
                     numbahs = sepInt num in
                     numbahs >>= lookupList chars

though this spelling is optional. In fact, everything is short enough now that I would even feel comfortable inlining the definitions:

base10IntTOstring num = sepInt num >>= lookupList (zip [0..9] ['0'..'9'])

My only complaint now is the name, for two reasons. The first is that string isn't capitalized, which is inconsistent with the naming of the remainder of the file. The other one is more of a philosophical one: our input is an integer, not a base-ten integer. If anything, the base-ten-ness is being imposed on the output. So:

intTOBase10String num = sepInt num >>= lookupList (zip [0..9] ['0'..'9'])

Let's test it:

*Main Test.QuickCheck> quickCheck (\n -> base10IntTOstring n == intTOBase10String n)
+++ OK, passed 100 tests.

(By the way, a variant of lookupList that I have always felt has the wrong type, lookup, is available from Prelude.)

Finally, I would be remiss without pointing out that there are several good functions that already exist for doing conversions like this:

*Main Test.QuickCheck> let checkPosBase10 f = quickCheck (\(NonNegative n) -> f n == intTOBase10String n)
*Main Test.QuickCheck> checkPosBase10 show
+++ OK, passed 100 tests.
*Main Test.QuickCheck Numeric Data.Char> checkPosBase10 (\n -> showIntAtBase 10 intToDigit n "")
+++ OK, passed 100 tests.

The difference here is that showIntAtBase can be used for any base, and show is specific to base 10.

charTOBase10Int

charTOBase10Int char =
                 let chars = [ ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('0', 0) ] in
                     let charslist = ( map (\(a,x) -> if char == a then Just x else Nothing) chars ) in
                         getStuff charslist

Actually, most of the changes we made to base10IntTOstring can be done here, as well. In the interest of totality, we'll change the type, too; it will return a [Char] (which we happen to know will be a singleton list, if anything) instead of a Char.

base10CharTOInt char = lookupList (zip ['0'..'9'] [0..9]) char

It's common in cases like this where the trailing arguments to the function you're defining are also trailing arguments to a function in the definition to omit the arguments entirely. The technical term for this is eta reduction, I think. Whether you choose to do this yourself is primarily a stylistic choice.

base10CharTOInt = lookupList (zip ['0'..'9'] [0..9])

The test for this one is a bit complicated; since the old implementation is partial, we have to restrict ourselves to those inputs that work.

*Main Test.QuickCheck> quickCheck (\n -> n >= '0' && n <= '9' ==> [charTOBase10Int n] == base10CharTOInt n)
*** Gave up! Passed only 67 tests.

The report here says that it passed the test, but that QuickCheck didn't run as many tests as it wanted to because most of the random inputs it generated weren't in the desired range. (In fact, perhaps it's questionable to use QuickCheck at all for this, since there's only ten inputs of interest anyway!)

By the way, this function (a partial version! boooo) exists also in Data.Char:

*Main Test.QuickCheck Data.Char> quickCheck (\n -> n >= '0' && n <= '9' ==> charTOBase10Int n == digitToInt n)
*** Gave up! Passed only 54 tests.

stringTOBase10Int

stringTOBase10Int string =
    let integers = ( map charTOBase10Int string ) in
        let multByBase i (x:xs) = if null xs
                                   then (10^i)*x
                                   else (10^i)*x + multByBase ( i-1 ) xs
        in multByBase ( (length integers)-1 ) integers

We first need to fix up some typing issues, since we've changed the interface to base10CharTOInt and this is a caller. As before, we can do that just by putting in a concat; as before, we'll spell the combination of concat and map as (>>=).

stringTOBase10Int string =
    let integers = string >>= base10CharTOInt in
        let multByBase i (x:xs) = if null xs
                                   then (10^i)*x
                                   else (10^i)*x + multByBase ( i-1 ) xs
        in multByBase ( (length integers)-1 ) integers

As with sepInt waaaay back at the beginning, I find the choice of base case a bit odd. Let's try the trick from before of letting the "loop" run one more iteration (and this time hopefully the refactoring isn't wrong!).

stringTOBase10Int string =
    let integers = string >>= base10CharTOInt in
        let multByBase i [] = 0
            multByBase i (x:xs) = (10^i)*x + multByBase ( i-1 ) xs
        in multByBase ( (length integers)-1 ) integers

Also, let's eliminate unnecessary parentheses.

stringTOBase10Int string =
    let integers = string >>= base10CharTOInt in
        let multByBase i [] = 0
            multByBase i (x:xs) = 10^i*x + multByBase (i-1) xs
        in multByBase (length integers-1) integers

Now, I wonder whether recomputing the power of ten each time is really the right thing to do. One thing we could do is to use 10^(length integers - 1) and divide by 10 in each recursion. But division is slow, so let's take another plan: instead of computing the length of the list explicitly, let's do it implicitly by having multByBase also compute the appropriate power of ten.

stringTOBase10Int string =
    let integers = string >>= base10CharTOInt in
        let multByBase [] = (1, 0)
            multByBase (x:xs) = let (pow, n) = multByBase xs in (pow*10, pow*x+n)
        in snd (multByBase integers)

This now has the magical special form of recursion that can be turned into a foldr. Let's do so! See if you can spot where each piece of code from the above ends up in the below.

stringTOBase10Int string =
    let integers = string >>= base10CharTOInt in
    snd (foldr (\x (pow, n) -> (pow*10, pow*x+n)) (1, 0) integers)

Personally, I often prefer where to let, and the foldr is complicated enough that I feel like it should be named, so I'd write it as follows. But this is an aesthetic choice that you may or may not agree with.

stringTOBase10Int string = snd (go integers) where
    integers = string >>= base10CharTOInt
    go = foldr (\x (pow, n) -> (pow*10, pow*x+n)) (1, 0)

And finally, fix up the name:

base10StringTOInt string = snd (go integers) where
    integers = string >>= base10CharTOInt
    go = foldr (\x (pow, n) -> (pow*10, pow*x+n)) (1, 0)

As usual, the tests. Since the old function was pretty partial, we'll arrange to have inputs it knows how to handle, though our new one tries to give an answer even when you feed it garbage.

*Main Test.QuickCheck> quickCheck (\(NonNegative n) -> base10StringTOInt (show n) == stringTOBase10Int (show n))
+++ OK, passed 100 tests.

By the way, there are functions for this available, too; take a look at reads from Prelude (base-10 specific) and readInt from Numeric (pick your favorite base). I won't try to write tests here, because the types of these functions are more informative (and more correct in many ways).

Final result

Barring the reuse of already-written functions, here's the final versions of all the functions.

sepInt 0 = [0]
sepInt n = reverse . go $ n where
    go 0 = []
    go n = let (d, m) = n `divMod` 10 in m : go d

lookupList table k = [v | (k', v) <- table, k == k']
intTOBase10String num = sepInt num >>= lookupList (zip [0..9] ['0'..'9'])

base10CharTOInt = lookupList (zip ['0'..'9'] [0..9])
base10StringTOInt string = snd (go integers) where
    integers = string >>= base10CharTOInt
    go = foldr (\x (pow, n) -> (pow*10, pow*x+n)) (1, 0)

Keep at it; I look forward to many more questions from you!