Main points to improve:

Memory leaks: C++ is not garbage collected. Every new must be deleted at some point. This is one of the reasons why C++ has destructors, so that we can perform this and other kinds of cleanup. In modern C++, smart pointers and standard containers are preferable, over manual memory management, since forgetting to delete a pointer is a very easy to make mistake, thus manual memory management being a major source of bugs and memory leaks.
Unusual data initialization style in constructors:

TNode<E>(){
    this->value = NULL;
    this->leftChild = NULL;
    this->rightChild = NULL;
}

The following is the correct way to initialize members. You should use the constructor initialization list. Also, prefixing the variables with a this-> in something we rarely do in C++:

TNode()
    : value(NULL)
    , leftChild(NULL)
    , rightChild(NULL)
{ }

Other tidbits:

Inside the body of a template class, such as in TNode, you should omit the template parameter in the name. Writing TNode<E> everywhere is too verbose and unnecessary.
Template parameter name for types is by convention called T instead of E.
NULL is deprecated since C++11 in favor of the better nullptr.
Integer return codes are quite error prone. Returning a bool true or false, when the function has only two possible outcomes, is a lot nicer.
You didn't follow your camelCase notation in the create_tree() method.


Yes, your code is correct, although I would recommend adding comments, and following the style guidelines of PEP8. Here are a few tips I have.

You should specify what type of error you want to except. If you just type except:, other errors could go un-noticed.
Typing exit() really isn't needed here. The program will terminate either way.
You don't need to put parentheses around conditionals in if statements.
It seems also that you're using Python2, so no parentheses are needed for print.
You could make this into a function that returns the grade.

Here's my re-factored version of the code.

def return_grade(user_input):
    """
    Return the user's grade based on the following table.
    Score  | Grade
    -------+------
    >= 0.9 | A
    >= 0.8 | B
    >= 0.7 | C
    >= 0.6 | D
    < 0.6 | F
    """
    try:
        user_score = float(user_input)
        if user_score > 1.0:
            return "Please enter a number between 0.0 and 1.0"

        elif user_score >= 0.9:
            return "Grade: A"

        elif user_score >= 0.8:
            return "Grade: B"

        elif user_score >= 0.7:
            return "Grade: C"

        elif user_score >= 0.6:
            return "Grade: D"

        elif user_score < 0.6 and user_score >= 0.0:
            return "Grade F"
    except ValueError:
        print("Please enter a number.")

print return_grade(raw_input("Enter a number between 0.0 and 1.0"))


Localization manager based on ReactiveCocoa

Excerpts from answers to my question on RAC repo:

For the first question -

  Subjects are naturally multicasted, so you could replace the multicast connection property with @property RACReplaySubject *localeSubject and subscribe directly to that in place of localeSignal.

So there's no need to use connection here.

For the second part - it's enough to have RACSignal in interface and RAC(Replay)Subject in the implementation.


Print Bootstrap 3 Tabs Component using only one foreach Loop

One way would be to build the value of the tab contents in a variable during the first loop, and just print it once the loop ends.  I have not written PHP in a while nor tested this code, so use as reference.

<?php $panels = rwmb_meta("ssc_tabpanels") ?>
<?php $tabContentHtm = ''; ?>
<?php if( !empty($panels) ): ?>

        <?php
        //build the tabs
        foreach($panels as $i => $p):
        ?>

            <a href="#tab-<?php echo $i ?>" data-toggle="tab"><?php echo $p['title'] ?>

        <?php
        // build content displayed on click of each tab
        $tabContentHtm .= '
'. $p['content'] .'
\r\n';
        endforeach;
        ?>

        <?php echo $tabContentHtm; ?>

<?php endif; ?>

The rendered code should look something like this

            Title 1

            Title 2

Lorem Ipsum of Title 1

Lorem Ipsum of Title 2


You do need to include <string>.  Your platform seems to bring it in as a side-effect of other includes, but you can't portably rely on that.

If there's no need to modify the contents of the string, prefer to pass by reference, to reduce copying:

bool string_contains_integer(const std::string& str)
//                           ^^^^^            ^

Instead of looping with indexes, learn to use iterators.  If you really must use indexes, use the correct type (std::string::size_type, not unsigned long long).

We don't need to write our own loop by hand, as there's a standard algorithm that will do that for us; we just need to supply the correct predicate function:

#include <algorithm>
#include <iostream>
#include <string>

bool string_contains_integer(const std::string& str)
/*
    This function iterates through an array of chars,
    and checks each character to be a digit;
    optionally including a starting "+/-" sign.

    Returns true if the string contains a number (string of digits);
    Returns false if the string contains any other character(s).

    Starting "+/-" gets ignored, as we accept all integer numbers.
*/
{
    auto from = str.begin();
    auto to = str.end();

    if (from == to) {
        return false;
    }

    if (*from == '+' || *from == '-') {
        ++from;
    }

    return from != to
        && std::all_of(from, to,
                       [](unsigned char c){ return std::isdigit(c); });
}


This isn't quite true:

  sends eight images per second

The 125ms sleep means that your code will sit around blocking a thread for about ~1/8th of a second (Thread.Sleep shouldn't be use for accurate timing ever) after it sends every image. This means that the time between images is ~125ms plus the time to actually send an image (i.e. no more than ~8 images per second, could be much fewer). This pretty much guarantees that you will drop a frame now and then.

You say that getImage() may or may not be providing a new image, and there is no nice way to check if a new image is available; however, you might consider interrogating the image received and checking if it is the same the one you last sent (and then don't send it); you can do this cheaply enough by taking a hash of the data stream. If getImage() itself isn't too expensive, then this would enable a quicker response rate, and ensure 8fps, rather than the 7-or-8 fps that a method like this will give you (assuming sending the image data is reasonably fast). If this makes sense will depend on the resource available, and how much you care about receiving every frame.

It would also be nice if you could avoid locking up a whole thread, as that sort of methodology does not scale (you run out of threads). An asynchronous HandleServer/HandleImage combination which makes use of Task.Delay() to schedule work might be a good solution, and would not significantly increase the complexity of the implementation.

Don't leave comments to rot:

// Save to memory using the bmp format
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

Such a comment is probably not worth the space it consumes, and it's unhelpful when it is out of date like this.

Calling HandleServer() within HandleImage() means that every exception will consume a little more of the stack frame, until eventually the program crashes. You might consider putting the logic for handling exceptions outside of both of these methods, and putting it in a loop; for example, something like:

while (keepRunning)
{
    try
    {
        HandleServer();
    }
    catch (Exception ex)
    {
        // do whatever
    }
}

Not only will this save slowly filling the stack, but it means that HandleImage can focus on handling images and not restarting the server when it goes wrong.

The difficulty with this is that you currently print some information when catching an exception, to which this alternative does not lend itself. (you could catch the expcetion, print everything out, and then throw it again: this way HandleImage is still only concerned with sending lots of images, and the code above it takes the role of deciding how to deal with other failures (e.g. network errors)).

You include the exception in your catch clause, but you don't report anything about it. It would be much better to print out the exception rather than the assumption that it is a network error: that way, when something goes wrong in production there is some hope of debugging it.

This code needlessly allocates an extra byte[].

byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);

It can be simplified to this:

byte[] dataSize = BitConverter.GetBytes(size);

Your code to send the data to the server is suspect: when sending the size-data, you don't check the return value, but you have a corresponding loop to send the image data. I'm not sure how socket and TCP get along, but if you don't trust data to send in one go, you should be giving sizeData the same treatment (you can put the loop in it's own method to keep it simple).

Consider using the using statement (as suggested by Jesse C. Slicer in the comments) to ensure proper disposal of disposables. For example, in HandleImage:

byte[] bmpBytes;

using (Image bmp = getImage())
using (MemoryStream ms = new MemoryStream())
{
    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    bmpBytes = ms.ToArray();
}

This will dispose the resources in the event that an exception if thrown in there somehow, and moves the released resources into a different scope, which means they can't be misused as easily (you can't forget to dispose them, and you can't use once when are disposed).

It's generally a good idea to define variables as close to their usage as possible. sent in HandleImage, for example, is declared on the first line of the method, but only used inside the while loop; it's purpose would be clearer if it was defined and assigned on the same line, and it would be impossible to use outside of its meaningful scope. total in SendVarData is also initialised first thing, but has no role in first piece of logic in the method.

These methods would really benefit from some inline-documentation (///) explaining what their role and behaviour is: I would not assume a method called HandleImage() could ever start a TCP server, so this needs to be written down somewhere (though ideally that would be changed, either as suggested above or through some other refactoring).

Small things:

Your 'bytes sent' reporting doesn't include the 4 bytes sent for the length-prefix.
The past-participle of 'catch' is 'caught', rather than 'catched'.
The variable data in HandleServer is never used.
Be consistent with your use of white-space (e.g. the gaps between methods, and indentation in HandleServer, etc.)
You might consider reusing the memory stream; we don't know how large the files are, but taking a new memory stream for each image may ruin your program's memory characteristics, and will necessarily degrade performance to some extent.
static void HandleServer() is missing an accessibility modifier (which are otherwise present)
double totalSize = 0; should not be a double (64bit float-point); did you mean long (64-bit integer)?


Naming things
Naming things is one of the hard things in computer science. You should make sure names of functions and variables are clear and concise. In general, use nouns for variable names and verbs for function names. Looking at your choices of names in more detail:

LATTICE is not a lattice, it is the size of the lattice. So call it LATTICE_SIZE.
SWEEPS is the number of sweeps to perform, so maybe it is better to call it N_SWEEPS (N is a commonly used prefix meaning "number of").
rates() is a function, so use a verb for the function name, for example calculate_rates().
rho_avg() is a function again, so use a verb for that as well, like calculate_rho_avg().

You should also be consistent in how you name things. Is it rho or density? Pick one and stick with it. I would also write beta instead of b, to match how you write down other greek letters like rho and theta.
Use array indexing notation where appropriate
In rates(), you are using pointer arithmetic when you could just have used standard array notation:
   for(int i = 0; i < LATTICE; i++)
   {
        theta = rho[i] * (2 * b - rho[i]);
        death_rate[i] = exp(-LATTICE * theta);
   }

Similarly, in revive(), write:
    for(n = 0; cumsum <= u_rand; n++)
    {
        cumsum += (double)distribution[n] / (double)norm;
    }

    return n - 1;

Terminology
Death rates? Revive? That sounds very morbid! Unless you are simulating some system that predicts cell death or pandemics, this is not terminology normally used in Monte Carlo simulations. Your code looks like it implements the Metropolis algorithm, where your death_rate would be equivalent to the transition probability, although I'm not sure what the equivalent of revive() would be. If it is the Metropolis algorithm you are implementing, then it doesn't look like you have detailed balance. What system are you simulating exactly? It might help to document that in the code as well.
Avoid global variables
It is good practice to avoid using global variables. That makes it easier if your program grows and becomes part of something larger. Or perhaps you want to run multiple simulations at the same time using threads. This should be easy; you already have the arrays distribution[] and death_rate[] inside monte_carlo(), just move rho[] there as well and pasas a pointer to rho to rates().
You might want to do this in a more organized way, and create a struct to hold all the information relevant to your simulation:
struct simulation_parameters {
    unsigned long long distribution[LATTICE];
    double death_rate[LATTICE];
    double rho[LATTICE];
};

...

double monte_carlo(float beta) {
    struct simulation_parameters params = {0}; // sets everything in params to zero
    calculate_rho(params.rho); // should do what initialize() did
    calculate_death_rates(params.death_rate, beta);

    for (unsinged long long i = 1; i <= SWEEPS; i++) {
        distribution[n]++;
        if (uniform_rand() < params.death_rate[n]) {
            n--;
            if (n == -1)
                n = revive(params.distribution, i);
        }
    }

    return calculate_rho_avg(distribution, SWEEPS);
}

int main(void) {
    srand(time(0)); // srand() should only be called once, so do it in main()
    printf("Average density is %lf\n", monte_carlo(BETA));
}


Is Refactoring with different class casting and property calling possible ?

This should work if you don't want to change anything in your classes:

var rows = new Dictionary<string, Func<DataRow, ShowReport>>
       {
          {"BillOfMaterial", dr => ((MISheetDataSet.BillOfMaterialRow)dr).mi1_BillOfMaterial},
          {"LayerBuildUp", dr => ((MISheetDataSet.LayerRow)dr).mi1_LayerBuildUp},
          {"Construction", dr => ((MISheetDataSet.ConstructionRow)dr).mi2_Construction},
       };

foreach (var row in rows)
{
    var dataRow = pObjDataset.Tables[row.Key].Rows[0];
    var showReportExtractor = row.Value;
    var showReport = showReportExtractor(dataRow);
    if (showReport == ShowReport.False)
        pObjDataset.Tables[row.Key].Clear();
}

(Don't forget to give meaningful names to variables)

But I would consider refactoring classes to allow more straightforward extraction of these mi1_BillOfMaterial, mi1_LayerBuildUp, mi2_Construction members. You have three classes here, each of them has ShowReport property but with different name. The idea is to extract a base class which will have this property, in this case we won't need to know the exact type of the row:

public abstract class RowBase
{
    public abstract ShowReport ShowReport { get; }
}

public class BillOfMaterialRow : RowBase
{
    public override ShowReport ShowReport { get { return mi1_BillOfMaterial; } }
}

// Two other classes implemented in the same way

And then your method will be as simple as:

var rows = new []
       {
          "BillOfMaterial",
          "LayerBuildUp",
          "Construction",
       };

foreach (var tableName in rows)
{
    var row = (RowBase)pObjDataset.Tables[tableName].Rows[0];
    if (row.ShowReport == ShowReport.False)
        pObjDataset.Tables[tableName].Clear();
}


You've written 40 lines of code to test 2-3 assignment statements and possibly one if statement. You've also tighly coupled your test to the implementation. This does not seem like a good tradeoff to me.

Read this before you continue with the rest of the review.

Your test is very much in the solitary category and I think that's a problem.

Get rid of the service mocks. Use the real implementations of services and instead inject test doubles at the repository level. Then don't write any tests specifically for your services, unless you consider their implementation particulary tricky (and therefore need more direct feedback while implementing them).

In the article I linked Fowler did not really go into the benefits of sociable unit tests so let me expand upon that. A solitary test does only support refactorings inside the tested class. In my experience most problems with code do not come from the implementation of a single class but rather from poor choices when it comes to what constitutes a class and from the dependencies between classes. A sociable test allows you to perform much larger refactorings.

Note that a solitary test will not only not aid you in performing a larger refactoring, but it will actually get in your way as you will have to rewrite the test.

Also note that replacing remote services with test doubles is fine not only because those services are slow and introduce non-determinism, but also because refactorings across remote services are very rare (and probably shouldn't be called refactorings anymore).

Finally, I acknowledge that in this small piece of code this may not seem as a major issue. But in a large project this is the difference between an unmaintanable pile of shit and something I'd happily work on.


First, you should separate a process of parsing your input from your business logic. So, your first step is to convert your holidays input to a structure you'll be working with. So, let's say you have a List<Holiday> where

public struct Holiday
{
    public readonly int Month;
    public readonly int Day;

    public Holiday(int month, int day)
    {
        Month = month;
        Day = day;
    }
}

Now, in your place I'd start with implementation of something that enumerates working days like so:

static IEnumerable<DateTime> GetWorkingDays(DateTime startDate, List<Holiday> holidays)
{
    var date = startDate;

    for (;;date = date.AddDays(1))
    {
        if (date.DayOfWeek != DayOfWeek.Saturday &&
            date.DayOfWeek != DayOfWeek.Sunday &&
            holidays.All(holiday => holiday.Day != date.Day ||
                                    holiday.Month != date.Month))
        {
            yield return date;
        }
    }
}

Note that this iterator is endless, so you should be cautious enumerating it.

Now, your problem can be solved with just one line

var result = GetWorkingDays(orderDate, holidays).Skip(workingDays).First();

Complete example here: https://dotnetfiddle.net/W3dalr


The one red flag is uTreeCount. This should not be a global, and in fact it is easy to rephrase your countUnivSubT to be fully re-entrant: have it return an integer, and do addition within the body, something like
unsigned countUnivSubT(stTree *Node)
{
    unsigned int uTreeCount = isTreeUniv(Node);

    if (Node->left)
        uTreeCount += countUnivSubT(Node->left);

    if (Node->right)
        uTreeCout += countUnivSubT(Node->right);

    return uTreeCount;
}

That said, you have an inner null check, so this can actually reduce to
unsigned countUnivSubT(stTree *Node)
{
    if (!Node) return 0;

    return isTreeUniv(Node)
        + countUnivSubT(Node->left)
        + countUnivSubT(Node->right);
}


You should take advantage of what is already available. For example, the json module. Instead of putting the string together manually, use json.dumps.  Python doesn't have a SQLAlchemy library built-in, but you can get one on PyPI, just pip install SQLAlchemy. Using this, you can browse https://stackoverflow.com/q/5022066/5827958 to see some simple ways of converting SQLAlchemy to JSON.

You define files = [] in get_modules(). That's unnecessary. Python does not need you to declare variables before using them. Just save yourself that tiny bit of processing time, and take it out.

You can also make use of os.path, a built-in pointer to an OS-specific filesystem path module. In get_modules(), you can simplify down to:

def get_modules():
    return glob.glob(os.path.join(PATH, "*.py"))

Since that now returns an absolute path instead of a relative one, you can now use merely input_filename instead of PATH+input_filename in get_fields().

I would also define get_modules as taking an argument for its path. That way, an importing module can use it for whatever path it wants, but your if __name__ == '__main__' block will give it sys.argv[1]. Since I just changed your function to using absolute paths, get_fields() doesn't need to know about PATH at all. On the side, you shouldn't be reading sys.argv unless __name__ == '__main__' anyway.

The purpose of your file is to convert, but an importing module has no access to the conversion code. I would suggest defining a function for the conversion, and then let the if __name__ == "__main__" block call that function with sys.argv[1] as an argument.

I'm glad that you use a with block in get_fields(), but I see you aren't in your main code. This could cause unexpected problems if something unexpected happened. You should open a file without a with block only in very rare cases.


Longest palindrome in a given string using LINQ

Well, I think your algorithm is correct, but the code is quite bloat. Your code suggest that the longest palindrome size can be calculated by sum of n / 2 * 2 where n is the count of distinct alphabet that exists more than once in the string, and plus 1 if there are any "oddCounts". So you can reduce the code to

    private static int GetLongestPalindrome(string value) {
        var map = value.GroupBy(c => c);
        int result = map.Sum(r => r.Count() / 2 * 2);
        if (map.Any(r => r.Count() % 2 != 0))
        {
            result++;
        }
        return result;
    }

n / 2 * 2 is the way to calculate for the nearest even number toward zero, and it equals to n - 1 where n is positive odd number.


Expanding a working query without adding multiple join statements?

At first glance, there are some alarm bells ringing.

You have t_users_settings.t_sid IS NOT NULL AND t_users_settings.t_uid IS NOT NULL. The first seems to imply you might have NULL values in your t_users_settings.t_sid column. The second seems to defeat the purpose of doing a left join to t_users_settings in the first place.
A second concern is that you're over-generalising.
Notice that you're unable to choose a specific type for your t_users_settings.value column. This means you have to roll your own custom type checking or do without.
Yes your design allows you to add new settings "without code changes". But in reality, those settings would be meaningless without code changes to make use of them in the first place.

You could probably solve your current problems quite easily by defining your settings table with a separate column for each possible setting, and doing the minimal work of adding columns as you add new settings.

However, that said here's a suggestion based on your current design.

First you want to get all permutations of settings and users. For that you need a cross join.

SELECT  u.*, s.*
FROM    t_users u
        CROSS JOIN t_settings s

That gives all combinations with their defaults. Now you want a left outer join to find out which defaults have been overridden for each user.

SELECT  u.*, s.*
FROM    t_users u
        CROSS JOIN t_settings s
        LEFT JOIN t_users_settings us ON
            us.uid = u.uid
        AND us.t_sid = s.t_sid

Finally, cleanup it up with explicit column selection, and you can even derive the actual users_value with a COALESCE, ISNULL or CASE statement.

SELECT  u.uid,
        u.name,
        u.email,
        s.t_sid,
        s.name,
        s.default_value,
        COALESCE(us.value, s.default_value) AS users_value
FROM    t_users u
        CROSS JOIN t_settings s
        LEFT JOIN t_users_settings us ON
            us.uid = u.uid
        AND us.t_sid = s.t_sid


Take input of delimited file of integers and output result

This is a good start. You created two functions to separate parts of the logic but there is more that can be refactored. The HalloNumbers sub is too big and does too much. Let's try to improve.

First the path shouldn't be hardcoded inside it so we pass it as parameter:

Sub Main()
    HelloNumbers("c:\temp\test.txt")
End Sub

Now we take parts of the big HalloNumbers and move them into fuctions that do only one thing - we always strive for this because it's easier to maintain when you only have to care about one thing at a time (see SRP).

Private Sub HelloNumbers(ByVal inputFile As String)
    Dim numbers As Integer() = ReadNumbers(inputFile)
    Dim multipliedNumbers = numbers.Select(Function(number) MultiplyEvenNumbers(number))
    PrintNumbers(multipliedNumbers)
End Sub

So we can extract the following functions:

We need to read the numbers. They are in a file. So let's require a path and after reading them we convert each number-string into an Integer with linq:

Private Function ReadNumbers(ByVal inputFile As String) As IEnumerable(Of Integer)
    ReadNumbers = Split(File.ReadAllText(inputFile)).Select(Function(s, i) CInt(s))
End Function

Then we need to multiply them. This one was already there so we leave it as is.

Private Function MultiplyEvenNumbers(ByVal inputNumber As Integer) As Integer
    If inputNumber Mod 2 = 0 Then inputNumber = inputNumber * 2
    MultiplyEvenNumbers = inputNumber
End Function

Finaly you want to print the results. Let's do it in PrintNumbers. If you decide to write the output to the console you now just have to adjust this small function.

Private Sub PrintNumbers(ByVal numbers As IEnumerable(Of Integer))
    For Each number As Integer In numbers
        If number Mod 2 = 0 Then
            MsgBox(String.Format("{0} was multiplied by two for {1}", number, number / 2))
        Else : MsgBox(String.Format("{0} is original", number))
        End If
    Next
End Sub


There are a few points about this that seem open to improvement (at least to me).

Don't compare bools to true or false, just use their value directly, so

placeholder_mode == false

becomes:

!placeholder_mode

likewise:

if(placeholder_mode == true)

becomes:

if (placeholder_mode)

You have basically everything in one giant function. This makes the code more difficult to understand, analyze, etc.
Some of the checks don't seem to accomplish much (if anything)--preventing leading zeros, for one obvious example.
Like most parsers, this is basically a state machine. As in many cases, it would probably be somewhat clearer if the state machine were a little more explicit.

I'd probably start with something like this:

enum states { COPYING, START_PLACEHOLDER, READ_PLACEHOLDER, END_PLACEHOLDER, ERROR };

states state;

while (it != fmt.end()) {
switch (state) {
case COPYING:
    if (*it == '{') state = START_PLACEHOLDER;
    else output.push_back(*it);
    break;
case START_PLACEHOLDER:
    if (*it == '0') state = ERROR;
    else state = READ_PLACEHOLDER;
    // intentional fall-through
case READ_PLACEHOLDER:
        num = std::stoi(it);
        check_range(num, 0, arg_count);
        output.push_back(args[num]);

...and so on. This structure can help clarify what happens in what states, and the conditions under which you progress from one state to another.


Fetch data from database either with a stored procedure or a query

My C# is quite rusty, so take everything I'm saying with a grain of salt; I stand by the general principles of what I'm writing, but the syntax/style might be a little off.

The first problem is that the two branches of your function are identical except for the SqlCommand being used. You should factor out how you create the SqlCommand and then do the rest the same way. For example,

private SqlCommand GetSqlCommandFromTableIfExists(string table, int? start, int? end, SqlConnection conn, string default)
{
    SqlCommand cmd;
    if (_sqlToRun.ContainsKey(table))
    {
        string sql = _sqlToRun[table];
        cmd = new SqlCommand(sql, conn) { CommandType = CommandType.StoredProcedure };

        var startParam = new SqlParameter
        {
            ParameterName = "@startRowNum",
            Value = start,
            SqlDbType = SqlDbType.Int
        };

        cmd.Parameters.Add(startParam);

        var endParam = new SqlParameter
        {
            ParameterName = "@endRowNum",
            Value = end,
            SqlDbType = SqlDbType.Int
        };

        cmd.Parameters.Add(endParam);
        var outputParam = cmd.Parameters.Add("@recordCount", SqlDbType.Int);
        outputParam.Direction = ParameterDirection.Output;
    }
    else
    {
        // You could easily not make the default a parameter if you prefer
        cmd = new SqlCommand(default, conn);
    }

    return cmd;
}

Then your function becomes

private async Task<Response> GetDataAsync(string table, int? start, int? end)
{

    var data = new List<Dictionary<string, object>>();
    var resp = new Response();

    using (var conn = new SqlConnection(_ConnectionString))
    {
        var cmd = GetSqlCommandFromTableIfExists(table, start, end, conn, "SELECT * FROM " + table);
        await conn.OpenAsync();
        using (var rdr = await cmd.ExecuteReaderAsync())
        {
            while (await rdr.ReadAsync())
            {
                var dictionary = new Dictionary<string, object>();
                foreach (var i in Enumerable.Range(0, rdr.FieldCount))
                {
                    var dbValue = string.IsNullOrWhiteSpace(rdr.GetValue(i).ToString()) == true
                        ? string.Empty
                        : rdr.GetValue(i);

                    dictionary.Add(rdr.GetName(i), dbValue);
                }

                data.Add(dictionary);
            }
        }

        Int32.TryParse(cmd.Parameters["@recordCount"].Value.ToString(), out var recordCount);
        resp.Data = data;
        resp.RecordCount = recordCount;
    }

    return resp;
}

Type unsafety is bad

Right now you're using a raw object as the value-type in your dictionary and Response - why? I assume its because this is a general function that is independent of the data you're grabbing, but it means you're losing out on what data you're adding and any kind of type safety. I think making the function and your Response type generic, and tweaking your implementation, you can ensure type-safety.

Don't make some random data object; just use resp.Data.


O(N) vs O(N * N) for Word Frequency Algorithm

First of all, there's a bug: You're relying on the properties in wordObj being iterated in ascending order when creating wordArray. I.e. wordObj['1'] is handled before wordObj['3'] and so on. This behavior is not guaranteed!

Objects are unordered in JS. Some engines do order them, but you cannot rely on it. Even engines that do order properties are under no obligation to sort them in any particular way. They might be in descending order, or sorted lexicographically (which would make sense since keys are strings, but it'd sort 10 before 2), or something else entirely.

Secondly, it just seems like you're working too hard here.

If there's a "tie" between to words (say "foo" and "bar" both appear 3 times), you return all of them on one line. The problem description does not explicitly require you to handle ties in any particular way. However, your solution basically means that you're not actually returning N words. A line of words separated by spaces is not "a word", but if it was, there'd be more than N words in total.

So I'd simply leave that out.

Besides, it's simpler to use reduce, sort and slice. You can also use a || "failover" instead of ternaries.

function freq(str, n) {
  var words = str.split(/\s+/);

  // Count occurrences
  var counts = words.reduce(function (memo, word) {
    memo[word] = (memo[word] || 0) + 1;
    return memo;
  }, {});

  // Sort by count (descending)
  var sorted = Object.keys(counts).sort(function (a, b) {
    return counts[b] - counts[a];
  });

  // Return the first n words, separated by linebreaks
  return sorted.slice(0, n).join("\n");
}

Edit: As rolfl points out, the input should probably be trimmed before anything else, or you might get empty strings in your words array. However, to avoid empty strings being counted as words, without changing the code above too much, you can do this:

var counts = words.reduce(function (memo, word) {
  if(word) { // ignore empty strings
    memo[word] = (memo[word] || 0) + 1;
  }
  return memo;
}, {});

Edit: As was pointed out, the above isn't actually O(n) due to its use of sort. Bummer. This one should be closer, although not as elegant. It's closer to the original code in some ways, but still avoids assuming that object properties are ordered.

function freq(str, n) {
  var words = str.split(/\s+/);

  // Count words (same as before)
  var wordCounts = words.reduce(function (memo, word) {
    if(word) {
      memo[word] = (memo[word] || 0) + 1;
    }
    return memo;
  }, {});

  // Group words into nested arrays that are, in turn,
  // indexed by the word count. I.e. wordsIndexedByCount[3]
  // will be a nested array of all the words that occurred
  // 3 times.
  // Also keep track of the highest index we use (maxCount).
  var wordsIndexedByCount = [],
      maxCount = 0;

  for(var word in wordCounts) {
    var count = wordCounts[word];
    maxCount = count > maxCount ? count : maxCount;
    wordsIndexedByCount[count] = wordsIndexedByCount[count] || [];
    wordsIndexedByCount[count].push(word);
  }

  // Flatten the array from above, starting with the most
  // often occurring word(s) - i.e. the highest index.
  var sorted = [];
  for(var i = maxCount; i > 0; i--) {
    // Skip "holes" in the array (not that it's necessary; the
    // code works without this check, since push.apply ignores
    // an undefined argument)
    if(!wordsIndexedByCount[i]) {
      continue;
    }
    [].push.apply(sorted, wordsIndexedByCount[i]);
    if(sorted.length >= n) {
      break; // if we've got enough to return, there's no reason to keep going
    }
  }

  return sorted.slice(0, n).join("\n");
}


I think the biggest thing here is that you need to create some functions and encapsulate stuff.

Big Points

Use reusable functions, especially when you find yourself copy-and-pasting code.
Don't hardcode anything; use constants rather than "magic numbers".
Don't use global variables.
Wrap it in a main().

Specifics

The minimum and maximum can be constants.

MINIMUM = 0
MAXIMUM = 1000

... Then, all you have to do is change these variables if you want to modify the game in the future:

number = random.randint(MINIMUM, MAXIMUM)
player_guess = input('\nPlayer: ')
computer_guess = random.randint(MINIMUM, MAXIMUM)

Break up the big multi-line message at the beginning rather than having it stretch on for 200 characters.  (Purists will still say that the implemenation below has the second line too long, as the Python standard is to have no line exceeding 80 characters, but you get the idea.)

print 'Welcome to the guessing game!'
print 'A number will be randomly chosen from ' + str(MINIMUM) + ' to ' + str(MAXIMUM)
print 'The player will make a guess, and then the computer will guess.'
print 'Whoever is closest wins that round!'
print 'First to 5 wins!'

You can have run_again directly store whether or not to run again (i.e., a boolean value) rather than a character.  This lets you check directly against it:

run_again = True
// ... then, elsewhere ...
if run_again:
    //do stuff

You can encapsulate the entire "guessing round" of the game into its own function which then returns whether or not the player won.  This will let you have a bit more control over your code structure:

def perform_guessing(number):
    player_guess = input('\nPlayer: ')
    computer_guess = random.randint(MINIMUM, MAXIMUM)
    print 'Computer: ' + str(computer_guess)
    print 'Number: ' + str(number)
    player_score = math.fabs(player_guess - number)
    computer_score = math.fabs(computer_guess - number)
    return player_score < computer_score

This will now return True if the player has won the round, so we can use it as such:

while run_again:
    if perform_guessing(random.randint(MINIMUM, MAXIMUM)):
        player_wins += 1
        console.set_color(0.00, 0.00, 1.00)
        print 'You won that round'
        console.set_color(0.00, 0.00, 0.00)
    else:
        computer_wins += 1
        console.set_color(1.00, 0.00, 0.00)
        print 'You lost that round'
        console.set_color(0.00, 0.00, 0.00)

(Note that in your code, it's actually impossible for a draw to occur, since you check both of the winning conditions with <= and >=, meaning that the == condition will be caught in one of those.  This may be a bug in your program. :) )

I might even make a color_print function to avoid some copy-and-pasting:

def color_print(text, r, g, b):
    console.set_color(r, g, b)
    print text
    console.set_color(0.00, 0.00, 0.00)

This would reduce our code above to:

while run_again:
    if perform_guessing(random.randint(MINIMUM, MAXIMUM)):
        player_wins += 1
        color_print('You won that round!', 0.0, 0.0, 1.0)
    else:
        computer_wins += 1
        color_print('You lost that round.', 1.0, 0.0, 0.0)

(I don't actually know what the three decimal values represent when you're setting the console color.  If they're not RGB, you can rename them accordingly.  But you get the idea.)

Finally, it's standard to encapsulate your functionality into a def main() and call it like so:

if __name__ == '__main__':
    main()

This lets you load you import things from this file into another file later without it actually executing.

Putting it all together, we get something that looks like this.  If it were me, I'd probably further specify the color_print function so that you could pass in something like Color.RED or Color.YELLOW rather than the three decimals, but that can be for a future release, haha.  There's some further encapsulation you could do to make the code still more elegant and readable, but I leave that as an exercise to the reader.

import random
import math
import console

MINIMUM = 0
MAXIMUM = 1000
FONT = 'Arial-BoldMT'
FONT_SIZE = 15

def perform_guessing(number):
    player_guess = input('\nPlayer: ')
    computer_guess = random.randint(MINIMUM, MAXIMUM)
    print 'Computer: ' + str(computer_guess)
    print 'Number: ' + str(number)
    player_score = math.fabs(player_guess - number)
    computer_score = math.fabs(computer_guess - number)
    return player_score < computer_score

def color_print(text, r, g, b):
    console.set_color(r, g, b)
    print text
    console.set_color(0.00, 0.00, 0.00)

def main():
    console.set_font(FONT, FONT_SIZE)
    print 'Welcome to the guessing game!'
    print 'A number will be randomly chosen from ' + str(MINIMUM) + ' to ' + str(MAXIMUM)
    print 'The player will make a guess, and then the computer will guess.'
    print 'Whoever is closest wins that round!'
    print 'First to 5 wins!'
    run_again = True
    player_wins = 0
    computer_wins = 0
    rounds = 0
    while run_again:
        rounds += 1
        if perform_guessing(random.randint(MINIMUM, MAXIMUM)):
            player_wins += 1
            color_print('You won that round!', 0.0, 0.0, 1.0)
        else:
            computer_wins += 1
            color_print('You lost that round.', 1.0, 0.0, 0.0)
        if rounds == 5:
            if player_wins > computer_wins:
                color_print('YOU WON THE GAME!', 0.0, 0.0, 1.0)
            else:
                color_print('YOU LOST THE GAME', 1.0, 0.0, 0.0)
            rounds = 0
            player_wins = 0
            computer_wins = 0

if __name__ == '__main__':
    main()


Trigger Updating another table - Baseball Database

at first glance I found a couple of things that might give you issues

IF Strike = 1
BEGIN
    SET @Strikes = 1;
    SET @Balls = 0;
END
ELSE
BEGIN
    SET @Strikes = 0;
    SET @Balls = 1;
END

IIRC, you can perform 4 foul hits before you are considered "out", and that a foul hit on the first and second pitch are also counted as "Strikes" but not the third foul hit. going through this logic will give you a false "ball" count because it is a foul but not a strike.

I also noticed

IF Contact = 0
BEGIN
    SET @Contact = 1;
END
ELSE
BEGIN
    SET @Contact = 0;
END

I assumed that @Contact was your "hits" but I tried to go through the logic and I am a bit confused.  If Contact = 0 means to me that there wasn't a hit, but you set the variable to true (SET @Contact = 1;)

Again IIRC, not every contact with the ball counts as a "hit"


Devise a program that counts the number of characters in its input up to the end of file

Well, it doesn't do much. But it is not bad. A few issues:

main() should have parameters
excess blank lines (lines 5, 12, 16, 18) spoil the appearance
no \n on the last printf
the spec doesn't say 'printable' characters, just characters.
"please" needs a capital p and "resault" should be "result"


There is not enough information to give a real review.
If you fill in all the type information and make it a compilable function I will review your algorithm, but based on the available code the only thing I can review is the style.

C and C++ are two completely different languages.

Pick one and learn it.
The syntax may be superficially the same but how you use it will not be.
I will make my comments assuming you are trying to write C++ not C.

Your layout is so horrible that it is practically unreadable.

Pick one of the common indenting style
If this is a problem with cut and paste then learn how to use your editor so that you can cut/paste without tabs onto a website.

Review

while (TRUE)

C++ has it's own boolean types. true/false

        {

Horrible formatting. The above '{' is indented way to far especially  in relation to the line it is encapsulating.

  *string = &stringEntries[mid = (bottom + top) / 2];

Assignment inside the [] is allowed but makes the code hard to read.
Prefer not to do that it is much more readable to split that into two lines.
You are not being paid to write compact code you are being paid to write easy to maintain code.

   if (!(diff = strcmp(pID, (*string)->ID)))
           diff = len - strlen((*string)->ID);

Your naming of variables here makes this code unreadable.
Make your variable names obvious.
Don't re-use variables. In the above code it looks like diff is being used for two different purposes (or is it not?). Let the compiler optimize out the extra space you should be making the code clear.

   if (bottom == top) {
          if (diff > 0)
                 (*string)++;  //ignore this bit - i need it later on
                 return NOT_PRESENT;

Absolute fail.
The indention suggests that we return when (diff > 0) but the code is not going to do that, as only the first statement after the if statement belongs to the if block. Always prefer to use statement blocks after control structures. Even if they are one liners (some people still use multi-line macro's that will break your code if you don't place it in '{' '}'

   if (diff > 0){
          if (bottom == mid) bottom++;
          else  bottom = mid;
   }
   else        top = mid;

More barely readable code.
A nice alignment would be good. There are also other constructs that will help:

  if (diff > 0)
  {
      bottom = ( bottom == mid) ? bottom + 1 : mid;
  }
  else
  {
      top    = mid;
  }


Optimal string literal tokenizing algorithm

A rule of thumb for performance in C# is to avoid allocations. In this case, we should try to remove buffer.ToString ().TrimEnd ('\\'), as well as the calls to Substring and Replace that appear at the end.

Of course you need to set performance goals and profile the code yourself on realistic input.  Single line strings can reasonably be expected to be quite short (say 200 chars?), so what you have already might be performant enough, but I'll illustrate an alternative way.

First let's make this a static method so it will be easier to unit test. As I mentioned in the comments, there's a bug in the code -- unit testing can help you catch such bugs.

private static string ReadSingleLineStringLiteral(TextReader reader)

And a convenience method for testing

private static string ReadSingleLineStringLiteral(string line)
{
    using (var reader = new StringReader(line))
    {
        return ReadSingleLineStringLiteral(reader);
    }
}

Now let's just handle the simple case, where there are no escape characters. Let's write some unit tests

Assert.AreEqual("", ReadSingleLineStringLiteral("\""));
Assert.AreEqual("jo dude", ReadSingleLineStringLiteral("jo dude\""));
Assert.Throws<ArgumentException>(() => ReadSingleLineStringLiteral(""));

And write the simplest thing that gets them to pass

var sb = new StringBuilder();
for (var c = reader.Read(); c != -1; c = reader.Read())
{
    switch (c)
    {
    case '"':
        return sb.ToString();
    default:
        sb.Append((char)c);
        break;
    }
}

throw new ArgumentException("Unexpected end of input");

Single line strings shouldn't contain new lines, so let's add a new test case

Assert.Throws<ArgumentException>(() => ReadSingleLineStringLiteral("\n\""));

And a matching case to our method

    switch (c)
    {
    case '"':
        return sb.ToString();
    case '\n':
        throw new ArgumentException("Single line string contains new line");
    default:
        sb.Append((char)c);
        break;
    }

Now let's move on to escape sequences.

Assert.AreEqual("jo \"dude\"", ReadSingleLineStringLiteral("jo \\\"dude\\\"\""));
Assert.AreEqual("this is a backslash \\ token", ReadSingleLineStringLiteral("this is a backslash \\\\ token\""));
Assert.AreEqual("this is a carriage return \r\nthis is next line", ReadSingleLineStringLiteral("this is a carriage return \\r\\nthis is next line\""));

We add another case

    switch (c)
    {
    case '"':
        return sb.ToString();
    case '\\':
        AppendEscapeCharacter(reader, sb);
        break;
    case '\n':
        throw new ArgumentException("Single line string contains new line");
    default:
        sb.Append((char)c);
        break;
    }

And the corresponding method

private static void AppendEscapeCharacter(TextReader reader, StringBuilder sb)
{
    var c = reader.Read();
    switch (c)
    {
    case -1:
        throw new ArgumentException("Unexpected end of input");
    case '"':
    case '\'':
    case '\\':
        sb.Append((char)c);
        break;
    case 'n':
        sb.Append('\n');
        break;
    case 'r':
        sb.Append('\r');
        break;
    default:
        throw new ArgumentException(string.Format("Invalid escape sequence '\\{0}'", (char)c));
    }
}

There are more cases to handle, but this should be enough to get you started.


Compare 2 dynamic jagged arrays of doubles and arrays of doubles

Nice question, and I am inspired to answer it, even though I don't use C#. I know enough about the algorithmic side to see a better way.

First though, the multitude of 1-liner if-conditions are bad practice. You should consider using braces even for these values.

The second thing, is the bitwise-XOR ^ operator you are doing in two places... this is conceptually broken, and unnecessary. A simple logical OR || comparison will be fine, since the previous check would return true if both values were null.

if (a == null || b == null)
{
     return false;
}

Now, about your algorithm.

The recursive system you have is a good option, but, if you change the 'recurse' point of the recursion, you will be able to do things in a more concise way. At the moment you are doing a number of the tests twice.

Have a look at the following:

public static bool ArraysEqual(dynamic a, dynamic b)
{
    // Same objects or both null
    if (ReferenceEquals(a, b))
    {
        return true;
    }

    // Just one object is null
    if (a == null || b == null)
    {
        return false;
    }

    if (a.GetType().IsArray && b.GetType().IsArray)
    {
        if (a.Length == b.Length)
        {
            for (int i = 0; i < a.Length; i++)
            {
                if (!ArraysEqual(a[i], b[i]))
                {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    // fall back to simple value compare
    return a == b;
}

Notice how, by doing the above, there is only one instance of each type of check.


C++ is not my normal haunt,  but there are a few significant observations on an algorithmic level that can be made here.

Bugs

The first obvious bug is that your code does not run multiple times. You need to reset the j variable in the outside loop, because the system will otherwise never start again from the beginning.
Your code enters an infinite loop if the user inputs 1. The code is supposed to output the result There are no solutions for 1.. Instead, since all 5-digit numbers are less than 100000 and since helper will never be more than 5 digits, the helper * 1 < 100000 exit condition for the while loop will never fail.

This leads on to a number of code-style problems...

Style

Namespaces:

using namespace std;

Don't do that. It is too easy to have issues with pollution in your namespace.
Variable declarations:

Declare variables in the scope they are used. This would have solved the bug, for the record. The j variable is declared outside it's use-scope. This is how you declare j:

int j = 0;
int a1,a2,a3,a4,a5;
while (cin >> n)
{
    while(j < 10)
    {
        i[j] = j;
        j++;
    }

But this is how it should be declared:

int a1,a2,a3,a4,a5;
while (cin >> n)
{
    int j = 0;
    while(j < 10)
    {
        i[j] = j;
        j++;
    }

Bracing C++ styles generally recommend the brace at line end: e.g. Google C++ style guide Local standards override this, though, so if your local dev team has a standard they follow, that's the one that should be followed.

Algorithm

First, this problem is a 2-part problem. The first is that you have to find all 5-digit numbers that do not have the same digit twice. The second is that you have to find the right multiple of that number that uses the other digits.

Your solution is pretty poor.... you use all combinations of essentially all 10 digits to find the numbers, and you skip many, many combinations. Consider this:

while (a1 == i[0] && a2 == i[1] && a3 == i[2] && a4 == i[3] && a5 == i[4])
    next_permutation(i,i+10);

Here you have taken a copy of the i array, and put it in the a array. Then you calculate all permutations of the remaining 5 digits, until the head-5-digits of the number change. I calculate millions of iterations in that loop that are wasted.

A better solution will use some mathematical properties to limit the problem significantly. For example, the basic formula you have, is:

$$
A \times N = B
$$

where A and B are both 5-digit numbers, and N is an integer. Additionally, none of the digits in A are in B. Using this, we know that:

the largest B can be is 98765
the largest A can be is 98765 / N
the smallest N can be is 2 (N == 1 is impossible because then A == B and we know they cannot have the same digits).

A smarter algorithm will be:

obtain N
find the maximum limit of A (98765 / N)
find all combinations of unique digits less than (or equal to) the A limit.
find the N'th multiple (B) of that digit.
determine whether the digits in B are unique (when combined with A).

Working code example:

#include <iostream>

bool digitsUnique(long value) {
  int count[10] = {};
  // Move 0 digits to the end
  while (value < 10000) {
    value *= 10;
  }
  while (value > 0) {
    if (count[value % 10]++ > 0) {
      return false;
    }
    value /= 10;
  }
  return true;
}

bool combinedUnique(long low, long high) {
  int count[10] = {};
  // Move 0 digits to the end
  while (low < 10000) {
    low *= 10;
  }
  while (high < 10000) {
    high *= 10;
  }
  while (low > 0) {
    if (count[low % 10]++ > 0) {
      return false;
    }
    low /= 10;
  }
  while (high > 0) {
    if (count[high % 10]++ > 0) {
      return false;
    }
    high /= 10;
  }
  return true;
}

void compute(int mult) {
  int count = 0;
  // 10 will require releating digits,
  // and more than 10 requires multiple 0 digits
  if (mult > 1 && mult < 10) {
    long limit = 98765 / mult;
    for (long low = 1234; low <= limit; low++) {
      if (digitsUnique(low)) {
        long high = low * mult;
        if (combinedUnique(low, high)) {
          count++;
          std::cout << high << "/" << low << " = " << mult << "\n";
        }
      }
    }
  }
  if (count == 0) {
    std::cout << "There are no solutions for " << mult << ".\n";
  }
}

int main() {
  int n;
  // std::cout << "Enter Multiple: ";
  while (std::cin >> n) {
    compute(n);
    // std::cout << "Enter Multiple: ";
  }
  return 0;
}

Note, when I run your solution on my computer, and use the input values 2 through 11 like:

time ./nfact < inputs

I get the time result of:

.....
97524/10836
There are no solutions for 10.
There are no solutions for 11.

real    0m0.815s
user    0m0.808s
sys     0m0.008s

When I run my version above, I get:

95823/10647 = 9
97524/10836 = 9
There are no solutions for 10.
There are no solutions for 11.

real    0m0.019s
user    0m0.016s
sys     0m0.000s

Note that it is about 42 times faster.... I like 42.


In general
Whenever you try to implement an application try to use sentences to describe the desired behavior. After that ask yourself: "Can it be further refined?" If so, then write new sentences to detail your plan in a more fine-grained level.
Let me show you what I mean:
The view from 10 000 feet

The application can perform basic operations between two operands.

What can be further refined?

What does it mean basic operation?
What did we mean by two operands?

High-level view

The application can perform basic operations between two operands.

It allows addition, subtraction, multiplication and division.

User can provide two numbers and the desired operation.
The application will perform it on the user's behalf.

What can be further refined?

How can an user provide numbers?

Fine-grained problem decomposition

The application can perform basic operations between two operands.

It allows addition, subtraction, multiplication and division.

User can provide two numbers and the desired operation.

The application receives an input from the user then it perform a preliminary check.

If it is valid then it goes to the next statement.
If it is invalid then it ask the user again to provide a valid input.

The application will perform it on the user's behalf.

Let's put together the skeleton
Now, we can translate each sentence into instructions.
This problem decomposition also helps us to well-organize our code:
///
/// The application can perform basic operations between two operands.
///
public static void Main()
{

}

///
/// User can provide two numbers and the desired operation.
///
private static void AskForInputs()
{

}

///
/// The application receives an input from the user then it perform a preliminary check.
/// <list type="bullet">
/// <item>
/// <description>If it is valid then it goes to the next statement.</description>
/// </item>
/// <item>
/// <description>If it is invalid then it ask the user again to provide a valid input.</description>
/// </item>
/// </list>
///
///
private static int AskForNumber()
{

}

///
/// The application receives an input from the user then it perform a preliminary check. <para />
/// It allows addition, subtraction, multiplication and division.
///
private static char AskForOperation()
{

}

///
/// The application will perform it on the users behalf.
///
private static void PerformRequestedOperation()
{

}

Observations about your implementation
The implementation is bit naive, because:

It does not handle those cases when the user provides malformed input

For example: instead of 3 (s)he provides three

It does not handle under- or overflow cases

For example: int.MaxValue + 100

It does not handle zero division case

For example: 100 / 0

It does not handle properly a division where the result is a floating number

For example: 10 / 3

etc.

In your switch statement you repeat the following two statement in each case:
Console.WriteLine(answer);
Console.ReadKey();

An alternative implementation could be:
switch (operation)
{
    case "+":
        answer = firstNumber + secondNumber;
    break;
    case "-":
        answer = firstNumber - secondNumber;
    break;
    case "*":
        answer = firstNumber * secondNumber;
    break;
    case "/":
        answer = firstNumber / secondNumber;
    break;
}

Console.WriteLine(answer);
Console.ReadKey();

This can be easily enhanced to include all the above validations as well:
switch (operation)
{
    case "+":
        answer = PerformAddition(lhs, rhs);
    break;
    case "-":
        answer = PerformSubtraction(lhs, rhs);
    break;
    case "*":
        answer = PerformMultiplication(lhs, rhs);
    break;
    case "/":
        answer = PerformDivision(lhs, rhs);
    break;
}

Console.WriteLine(answer);
Console.ReadKey();

Now as you can see we have introduced 4 new functions to abstract away the complexity to deal with different edge cases and the main flow remained easy to follow.


Read files from a directory using Promises V2

First of all, async code is not a requirement for all Node.js code. It depends on the use case. Async code makes sense if you want to service multiple things concurrently (i.e. HTTP servers, test runners, etc.) but doesn't make sense for single-run script-y things (i.e. cli tool, scaffold generator, etc.).

The case above falls in the second category, a simple, single-run, non-concurrent, non-intensive operation. This means you can get away with the synchronous versions of the same operations, which will not require promises.

const { readdirSync, statSync, readFileSync, writeFileSync } = require('fs');

readdirSync('.')
  .slice(0, 1)
  .map(file => ({ stat: statSync(f), file }))
  // If you know it's not readable, just don't proceed.
  .filter(data => (data.stat.mode | fs.S_IRWXO))
  .map(data => readFileSync(data.file))
  .forEach(content => writeFileSync('test', content))

// If it made it all the way here, it worked. If something threw up,
// it should have halted the script somewhere in the middle.
console.log("It worked")

Now if you really want async code, Node supports async/await. It's essentially syntactic sugar to promises, where async functions return promises, values returned by async functions become the resolved value, errors throw become rejection values, and await makes code appear to wait for the promise to settle before proceeding. This means you can write the code much closer to the one above.

The one nice thing about async/await over regular promises is better scoping. You don't have to pass forward stuff from the previous then to the next then.

const { promisify } = require('util')
const fs = require('fs')
const readdir = promisify(fs.readdir)
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const stat = promisify(fs.stat)

async function op(){
  const files = await readdir('.')
  const file = files[0]
  const data = await stat(file)

  if (!(data.stat.mode | fs.S_IRWXO)) throw "Not Readable"

  const content = await readFile(file)

  await writeFile('Test', content)
}

// Needed, since Node will warn you about unhandled rejections.
// Otherwise, the code above could have been an async iife.
op().then(() => {
  console.log("It worked")
}, (e) => {
  console.log("Error: " + e)
})


Bernoulli trials using a condition in a vectorized operation

To initialize all entries of an array to the same value, np.repeat is probably not the fastest option, and definitely not what most people would expect to find. The more proper way would probably be:

baf = np.full((n.size,), fill_value=np.nan)

And for cases like this it is typically faster to use a boolean mask for indexing, skipping the call to np.where to extract the numerical indices. This should do the same faster:

mask = n >= 30
baf[mask] = np.random.binomial(n[mask], p[mask]).astype(float) / n[mask]


C++ is C++

A lot of this code is basically C. So let's C++ify it. <cstdio> is the C-style IO library. In C++, we have <iostream>, with cout. The biggie here is:

char message[500] = "The dog jumped up and down and ate chocolate, then he bit the cat";

C++ has a library for dealing with strings. It's called <string>, and is very useful:

std::string message = "The dog ...";

std::string manages its own memory and comes with a whole bunch of member functions. One of those is size():

size_t msg_length = message.size();
std::cout << message << '\n';
std::cout << "The message length before deleting the dupes is: "
          << msg_length << "\n\n";

Although if you want to stick with pointers, you still wouldn't need to write your own length function as there is strlen. But if you really insist on writing your own loop, please put the thing you're comparing on the left-hand side:

for (; array[i] != 0; ++i) ;

Or, since we're comparing against 0:

for (; array[i]; ++i) ;

Putting constants on the left-hand side is, frankly, terrible.

deleteDupes

The C++ standard library comes with a whole bunch of algorithms. The algorithms tend to be very useful, both in terms of code readability, performance, and correctness. For one thing, your loop has a bug (you have --i which presumably should be --j).

I would use the Erase-Remove idiom. That is:

void deleteDupes(std::string& message) {
    message.erase(
        std::remove_if(message.begin(), message.end(), ???),
        message.end()
        );
}

What do we put in the ???s? We need a predicate that will return true if this is a character we've seen before. Easy way of keeping track of that is an std::unordered_set and thanks to C++11, we can stick the predicate in-line:

void deleteDupes(std::string& message) {
    std::unordered_set<char> seen;
    message.erase(
        std::remove_if(message.begin(), message.end(), [&](char c){
            return !seen.insert(c).second;
        })
        message.end()
        );
}

Basically, insert will tell you if it succeeded or not (i.e. this is the first time you've seen c or not). If it's the first time, we return false (and insert into our set). Otherwise, we return true and the remove_if algorithm marks this character for deletion. We then erase all the dupes in one go.

Simple. Correct. Readable.


Efficiency of looping though a text map to draw objects

Well, for starters, you could reduce operations to \$O(n^2)\$ by skipping your third loop:

var levels = [
    ["##########",
     "#        #",
     "#        #",
     "#        #",
     "#        #",
     "#  #     #",
     "#       ##",
     "#     #  #",
     "#S  #    #",
     "##########"]
];

for(var i = 0; i < levels[0].length; i++){
    for(var j = 0; j < levels[0][i].length; j++){
        var symbol = levels[0][i][j];
        console.log(symbol);
    }
}

I changed levelOne to a levels array where you can refer to each level by index, since you probably want to add more levels later on.

jsFiddle

Why do you define symbol outside of the loop, and re-declare it inside?

Regarding your platforms:

var platforms = [];

platforms.add = function(xPosition, yPosition, width, height, colour) {
    platforms.push(new Block(xPosition, yPosition, width, height, colour) );
};

You are just declaring an add method for that specific array instance. It also creates an enumerable property on the array which isn't good if someone happens to use for..in to iterate the array (which I wouldn't recommend in the first place). Why not simply call push directly?

If you insist on creating your own add method, in my opinion, platforms should be either its own "type" (if you plan to create several instances):

function platform(){
    this.blocks = [];
}

platform.prototype.addBlock(function(block){
    this.blocks.push(block);
});

Or if you know that you'll only use one platform, create a "static" object:

var platform = {
    blocks: [],
    addBlock: function(block){
        this.blocks.push(block);
    }
};


Terminology

It's important to be able to understand (and describe) what's actually going on. Your program

converts from an integer decimal string representation to an integer using scanf. This integer is then represented as a binary number in the processor.
converts from that integer back into a string representation, but rather than it being decimal, it's binary.

So yes - it technically converts from "decimal to binary", but really it's "decimal string to integer to binary string".

Use const

void print_out_reversed(char string[])

doesn't modify string, so write const char string[].

Simplify your strlen usage

This:

int index = strlen(string);

while (string[index] != '\0')
    index--;

for (int i = index; i >= 0; i--)
    putchar(string[i]);

can be

for (int i = strlen(string)-1; i >= 0; i--)
    putchar(string[i]);

It seems that you don't trust what strlen is doing, which is why you have that intermediate while loop. But that loop won't have any effect, because the null terminator will always be where strlen says it is.

Use math instead of if

This:

    if (number % 2 == 0)
    {
        bits[index] = '0';
    }
    else
    {
        bits[index] = '1';
    }

can be

bits[index] = '0' + (number & 1);

Use combined operation and assignment

This:

number = number / 2;

should be

number /= 2;

or, for speed (which the compiler will do for you anyway)

number >>= 1;


You should make i a parameter of executeQuery :

private String[] listScript = {"Script1", "Script2", "Script3", "Script4"};

private void executeQueries() throws InterruptedException {

    ExecutorService threadPool = Executors.newFixedThreadPool(listScript.length);
    // submit jobs to be executing by the pool
    for (int i = 0; i < listScript.length; i++) {
        final int j = i;
        threadPool.submit(() -> executeQuery(j));
    }
    // once you've submitted your last job to the service it should be shut down
    threadPool.shutdown();
    // wait for the threads to finish if necessary
    threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

}

private void executeQuery(final int index) {
    System.out.println(listScript[index]);
}

I used lambda here as it's simply less verbose. j is needed as i must be final for the closure to work ;)

Also awaitTermination(Long.MAX_VALUE... isn't a very good idea.... It's over 10 millions years you know ? ^^


Creating a booking based on a POST request

If you are going to use a prepared statement (please do) then go the extra step of using placeholders and bound parameters. Your queries are not currently stable/secure.
If you don't truly need Property_No for anything, just return COUNT from your first query, and evaluate that value as a boolean (loose truthy comparison).  This is cleaner and more deliberate, I reckon.
Your code is suffering from excessive tabbing (aka "arrowhead" code). This increases the likelihood that you or future devs will need to tediously scroll horizontally to review/manage the code.
If all of the conditions must be true to reach the INSERT query, then just use one condition statement with the expressions separated by &&.


Attempt at solution for Dining Philosopher algorithm

Overall
Wow. Correct implementation.
Your the first person to post what I would call a proper implementation.
Good Job.
Code Review
Prefer NOT to use #define
#define P 5

Nearly every use of #define has a better alternative in C++ (unless you are really abstracting OS specific details).
In this case case you are  defining a constant integer. There is an explicit version of that for C++.
constexpr int globalConstantP = 5;  // More than 1 letter

While we are on P. A variable of length 1 is not very meaningful. Your code should be self documenting. This really means your variable names should be meaningful.
Avoid Platform specific includes.
#include <Windows.h>

This is the one place where #define comes in useful. Abstracting platfrom specific details. The Windows and Unix versions of sleep are different.
#if defiend(WIN32)

#include <Windows.h>
#define  doSleep(X)     Sleep(X)

#elif defined(__linux__)

#include <unistd.h>
#define  doSleep(X)     sleep(X * 1000)

#elif defined (__APPLE__) && defined (__MACH__)

#include <unistd.h>
#define  doSleep(X)     sleep(X * 1000)

#else

#error "Unsupported Platform"

#endif

Avoid using pointers
std::thread *threads[P];

In modern C++ you should never (or practically never) be calling new and delete. You should use automatic variables for all situations so that you can make sure the constructor/destructor and thus RAII kicks in to do the resource management. When you do need dynamically allocated objects they should be wrapped in smart pointers so that they can not leak.
Here you don't need pointers at all. Just use std::thread.
Avoid global variables
std::thread *threads[P];
std::mutex mtx[P]; //forks

Global mutable state is the bane of many problems in program. But especially testing. It is best to pass objects to functions (by reference) and manipulate them or even better to just manipulate the object by calling the member functions.
I would have created a class called Table that had the array of std::thread and std::mutex objects. Then your functions below become methods than manipulate the object.
cout!!!
std::mutex cout;

That is too easy to be confused with std::cout. Please put it in a namespace and the very least. I would actually create your own stream class (one that can be locked) and pass that as the output object to the constructor of your Table class.
Thinking should sleep
It take times to think.
It should also take time to think.
       if (pickUp(leftIndex, rightIndex)) {

            std::cout << "Philosopher " << philID << " eats.\n";

            doSleep(rand() % 20);

            // Don't put Down the forks until you have had time
            // time to do some eating. Remeber you are simulating work
            // after having obtained the resources. The work should
            // take none zero time.
            putDown(leftIndex, rightIndex);

        else {
            std::cout << "Philosopher " << philID << " thinks.\n";

            // When the philosopher is thinking the time should
            // also be none zero as you are simulating doing work
            // that is not related to the resource.
            doSleep(rand() % 20);
        }

Joinable
        if (threads[i - 1]->joinable())
            threads[i - 1]->join();

No need to test for joinable if you have never called detach on your thread.
Return 0
    return 0;

No need to return 0 at the end of main(). It does that automatically.
Normally you use return 0 to indicate there was a success BUT also to indicate that it could fail and there is another way to exit that could return a non zero value. When I see a return 0 I immediately start looking for alternative returns paths to see under what conditions the application will fail.
So if your application can not fail don't return anything (this is an indication that it can't fail). The compiler will add the return 0 if one was not provided.


Date picker consisting of three component pickers

So if I understand correctly, you want to create an instance of DatePicker which by default has 3 instances of ComponentPicker in an array called pickers? Then the following should work:

class DatePicker extends ComponentPicker{
  constructor(length) {
    this.pickers = data.map(component => new ComponentPicker(target, component));
  }


You were so close! So close to having re-entrant code. You declare buffer as a global, but also pass it into a function. It should be easy enough to just move it to main and keep your functions as-is.
You have two different pointer offset styles (right next to each other) that accomplish the exact same thing:
&tmp[tmp_offset],
buffer+buffer_offset

I prefer the latter, but pick one and stick with it.
This:
size_t buffer_size = strlen(buffer);
char tmp[buffer_size * 2];

leverages a feature of C, variable-length stack arrays, not offered until C99. It's not wrong, but it occupies the stack and I find that for any non-trivial amount of memory the heap is a safer bet.
re_sub and exit_with_error should be marked static.
I don't find this statement:
while ((rc = pcre_exec(re_compiled, NULL, buffer, strlen(buffer), buffer_offset, 0, offsets, OFFSETS_SIZE)) > 0) {

particularly nice to read; you'd be better-off avoiding combined assignment-predicate statements like this, and just separating it out. It will have no impact on your compiled code.


The code will work, so from that point of view, it is correct.

But there are also some issues with it:

I don't see any reason for the InnerJoinTables class to exist. You should just use List<InnerJoinTable> directly in the calling code. That's unless there's something else going on that you're not showing.
Public fields should not be used. Use a property instead.


x64 Assembly zeroing an array (8 bytes at a time)

Shave off a byte

    cmp  edx, 0
    jle  Finished            ; Check if count is 0

Using cmp is certainly not wrong, but the optimal way to check for any inappropriate counter value would be to use the test instruction.

    test edx, edx
    jle  Finished            ; Check if count is 0

Bypassing when the counter is zero is fine, but perhaps a negative counter value should rather be considered an error and handled accordingly?

Don't loose yourself in jumping around

    cmp  edx, 8
    jl   SetupLessThan8Bytes ; Check if counter is less than 8
    mov  r8d, edx            ; Storing the original count
    ...
    ...
SetupLessThan8Bytes:
    mov  r8d, edx
    jmp  SetFinalBytesLoop

When the counter in EDX is smaller than 8, you jump to SetupLessThan8Bytes where you just make a convenient copy of the counter and then jump again to SetFinalBytesLoop.
If you move the instruction that makes a copy of the original counter to right before where you compare the counter to 8, you can save yourself from writing 3 lines of code (a label, a mov, and a jmp). Moreover the program becomes clearer.

    mov  r8d, edx            ; Storing the original count
    cmp  edx, 8
    jl   SetFinalBytesLoop   ; Check if counter is less than 8

You don't even have to compare to 8 at all!

When you shift the counter in EDX 3 times to the right in order to find out how many qwords you have to process, you can look at the zero flag. If the ZF is set (meaning no qwords at all), you instantely know that the counter is in the range [1,7], and so the above snippet becomes:

    mov  r8d, edx            ; Storing the original count
    shr  edx, 3              ; Equal to dividing by 8
    jz   SetFinalBytesLoop   ; Jump if counter is less than 8

Easier calculation of leftovers

    mov  r9d, edx
    ...
    shl  r9d, 3
    sub  r8d, r9d
    je   Finished
SetFinalBytesLoop:

The way you find out about the number of left over bytes is too complicated. It's correct but needlessly involved. Basically all it takes is anding the original counter with 7 to extract the lowest 3 bits. Simpler, shorter, and using one register less which in future programs will always be handy:

    and  r8d, 7
    jz   Finished
SetFinalBytesLoop:

Smaller instructions are generally better

With the 32-bit immediate value, the mov instruction in the MainLoop is quite long (7 bytes). You can store the zero in RAX and move that to memory. This also eliminates the need for the mention "qword ptr ":

    xor  rax, rax            ; Equivalent to MOV EAX, 0
MainLoop:
    mov  [rcx], rax          ; Set the next 8 bytes (qword) to 0
    add  rcx, 8              ; Move pointer along the array by 8 bytes
    dec  edx                 ; Decrement the counter
    jnz  MainLoop            ; If counter is not equal to 0 jump to MainLoop

Your program with all the above applied

    xor  rax, rax
    test edx, edx
    jle  Finished            ; Check if count is LE 0
    mov  r8d, edx            ; Copy of the original count
    shr  edx, 3              ; Gives number of qwords
    jz   SetFinalBytesLoop   ; Jump if counter is less than 8
MainLoop:
    mov  [rcx], rax          ; RAX=0 Set the next 8 bytes (qword) to 0
    add  rcx, 8              ; Step per 8 bytes
    dec  edx                 ; Dec the counter
    jnz  MainLoop
    and  r8d, 7              ; Remainder from division by 8
    jz   Finished
SetFinalBytesLoop:
    mov  [rcx], al           ; AL=0 Sets the last bytes of the array to 0
    inc  rcx                 ; Step per 1 byte
    dec  r8d                 ; Dec counter
    jnz  SetFinalBytesLoop
Finished:
    ret

I've moved the xor rax, rax higher up in the code so SetFinalBytesLoop can benefit from using the register AL vs the immediate 0.

The optimization

The most important optimization that you can apply to your program is making sure that the qword value that you write is aligned on a qword boundary, so a memory address that is divisible by 8.
The extra alignment loop will at most iterate 7 times.

    xor  rax, rax
    test edx, edx
    jle  Finished            ; Check if count is LE 0

    jmp  TestAligned
AlignLoop:
    mov  [rcx], al
    inc  rcx
    dec  edx
    jz   Finished
TestAligned:
    test rcx, 7              ; Is this a qword aligned address?
    jnz  AlignLoop           ; Not yet!

    mov  r8d, edx            ; Copy of the (reduced) original count
    shr  edx, 3              ; Gives number of qwords
    jz   SetFinalBytesLoop   ; Jump if counter is less than 8
MainLoop:
    mov  [rcx], rax          ; RAX=0 Set the next 8 bytes (qword) to 0
    add  rcx, 8              ; Step per 8 bytes
    dec  edx                 ; Dec the counter
    jnz  MainLoop
    and  r8d, 7              ; Remainder from division by 8
    jz   Finished
SetFinalBytesLoop:
    mov  [rcx], al           ; AL=0 Sets the last bytes of the array to 0
    inc  rcx                 ; Step per 1 byte
    dec  r8d                 ; Dec counter
    jnz  SetFinalBytesLoop
Finished:
    ret


@Override
public String toString() {
    if(size == 0) {
        return "[]";
    }

    StringBuilder sb = new StringBuilder();
    QueueNode<T> cur = first;
    sb.append(cur.getValue() + "<-");

    while(cur.getNext() != null && !cur.equals(last)) {
        sb.append(cur.getNext().getValue() + "<-");
        cur = cur.getNext();
    }

    return sb.append("null").toString();
}

Empty stack prints "[]", stack with one element prints 1<-null. Where are the surrounding brackets? Also, you can use a do-while loop here to prevent needing to specify how to print twice:

@Override
public String toString() {
    if(size == 0) {
        return "[]";
    }

    StringBuilder sb = new StringBuilder();
    QueueNode<T> cur = first;

    do {
        sb.append(cur.getValue() + "<-");
        cur = cur.getNext();
    } while(cur != null);

    return sb.append("null").toString();
}

It also vastly simplifies the iteration.

public void offer(T val) {
    QueueNode<T> cur = new QueueNode(val);
    if(size == 0) {
        cur.setNext(first);
        first = cur;
        last = cur;
        size++;
        return;
    }

    last.setNext(cur);
    last = cur;
    size++;
}

This could be simplified to reduce duplication - step 1, making the else case explicit...

public void offer(T val) {
    QueueNode<T> cur = new QueueNode(val);
    if(size == 0) {
        cur.setNext(first);
        first = cur;
        last = cur;
        size++;
    } else {
        last.setNext(cur);
        last = cur;
        size++;
    }
}

Step two, moving similar instructions into the shared area.

public void offer(T val) {
    QueueNode<T> cur = new QueueNode(val);
    if(size == 0) {
        cur.setNext(first);
        first = cur;
    } else {
        last.setNext(cur);
    }
    last = cur;
    size++;
}

Additionally, you can make use of isEmpty() here for increased clarity.

public QueueNode<T> poll() {
    if(isEmpty()) {
        return null;
    }

    QueueNode<T> cur = first;
    first = first.getNext();
    size--;
    return cur;
}

poll() is returning internal nodes. You want to return the value instead. Don't expose your internal nodes. Use exceptions for indicating pulling from an empty queue.


Where you have your own bounds for rand, calculate them directly. Instead of

int nonZeroCoefficient(){
  int n = (rand()%(level+2) - (level));
  if ( n == 0 ){
  n++;
  }
  return n;
}

try

int nonZeroCoefficient(){
  int n = (rand()%(level+2) - (level)) + 1;
  return n;
    }

(modify the first part of the equation to suit). This also reduces a skew or bias in your randomness where anything <1 becomes one (i.e. the number 1 becomes over-represented in the random samples).

You also define your functions within your main(). This makes the code harder to read/understand and will make it harder to maintain. As a result, main() will only be:

int main() {
    do{
      ask();
      printf("\nDo you want to continue? (Y/N)");
      scanf (" %c", &ch);
    } while(ch == 'y'|| ch == 'Y');

}

As you don't return anything from main() or ask(), void will suffice. The following are the functions that should be defined separately from your main code

int nonZeroCoefficient() // noting the comment I made about about generating the random number
int nonZeroRand() // noting the comment I made about about generating the random number
int ask()

Both nonZeroCoefficient() and nonZeroRand() functions will be single line functions that could be replaced by a single function

int newRand(int f1, int f2){ //f1 could be level+2 or rand Max, F2 could be level or randMax
      int n = (rand()%(f1) - (f2)) + 1;
      return n;
}


Discovering words from letters in Clojure (Letterpress Solver)

The (distinct (combo/combinations letters %)) looks mighty troublesome to me. I don't know what the complexity function is for combinations offhand, but I'm going to guess it's got a factorial in it. Using distinct around it means that you will hold that entire set of combinations in memory. That's one of those things that works well for small numbers, then falls off a cliff.

I also think this is one of those kinds of problems that can benefit significantly from memoization if structured properly. (Although memoization creates a cache in memory, so you might want to build your own with a customized cache to avoid blowing the heap. This is pretty easy with core.memoize.)


A pair of style comments based on PEP 8:

It’s good that you sort your module imports alphabetically, but you should also split out third-party imports from standard library modules. Specifically, this means moving backports and tweepy into their own group. (Imports)
Wrap lines to 79 characters. (Maximum Line Length)

Now on to the meat of the program:

Get your secret information from the keychain, not the command line.

I’m not a big fan of passing in passwords or secret information over the command line. They’ll show up in your command history, and you probably need to copy/paste them from somewhere every time you use them (Twitter’s access tokens are not particularly easy to remember).

I prefer to use the keyring module, which stores and accesses passwords via the system keychain.

That’s how I store my secret tokens for Twitter, which I think is a bit more secure and more convenient. Here’s a snippet from my Twitter backup script which gets my tokens this way:

import keyring
import tweepy

def setup_api():
    """Authorise the use of the Twitter API."""
    a = {attr: keyring.get_password("twitter", attr) for attr in [
        'consumerKey',
        'consumerSecret',
        'token',
        'tokenSecret'
    ]}
    auth = tweepy.OAuthHandler(a['consumerKey'], a['consumerSecret'])
    auth.set_access_token(a['token'], a['tokenSecret'])
    return tweepy.API(auth)

and here’s how I would initially set the tokens:

import keyring

keyring.set_password("twitter", "consumerKey", 'abcdefg1234567')
# repeat for other secrets/tokens as appropriate

Tidy up your date handling code.

There are several things I’d change about this part:

Use a different name for the today variable. Not only is it incorrect (because the datetime object it creates points to yesterday), but it also has the potential for confusion with the today() method.
Add some comments to explain the purpose of this variable – what does it represent, and why are you doing it this way?
The today.replace() line has no effect on the program. The replace() method returns a new datetime object; it doesn’t modify in-place. Here’s a short snippet that demonstrates the difference:

mydate = datetime.datetime.today()
mydate.replace(hour=0, minute=0, second=0, microsecond=0)
print mydate  # 2015-04-29 19:29:54.572354

mydate2 = datetime.datetime.today()
mydate2 = mydate.replace(hour=0, minute=0, second=0, microsecond=0)
print mydate2 # 2015-04-29 00:00:00

You need to add today = to the start of the line.

(Although it’s not clear to me why you need this line, anyway. It means you’ll get links from the last 24 hours and a bit. If you’re not using it, remove this line from the script.)

Clarify the links_today() function.

You should add a docstring to the function to explain what it does, and what sort of input it expects. It’s not clear what link is supposed to be, or why you're taking the 0th index to get the time.
The name of the function suggests to me it might return a list of links from today. Instead it tells me whether a link was posted today. I’d give the function a more descriptive name, e.g. was_posted_today().

Don’t hard code the path to your csv.xz file halfway down the program. It would be better to put it as a global variable right at the top of the script: that way, if you ever want to change it, it’s easy to find.
It would be good to add some comments about the format of file, and what each line of the CSV looks like. That would help to explain the seemingly random indices of tweet that you take later.
For the status string, I would precompute the number of links and recipients, accompanied with a comment about why you take index 1 and 2, respectively. Otherwise these seem like magic numbers.

Also note that if either of these numbers are 1, you will have a pluralisation bug. Oops.
Wrap your code in a main() function.

Rather than have all your program code in the top-level, define a series of functions, concluding in main(), which is where your main program flow goes. Then put this at the end of your script:

if __name__ == '__main__':
    main()

Now, if the script is run as a standalone program, everything in main(), but you can import the functions from this script in another file as well. It makes it easier to reuse code.


Using a string for MOUNTPOINTS means you can't have any mount points with spaces of glob characters in the names. I realize you likely can't use an array if you want real portability but that's a severe limitation that you might want to check for.

I don't know what you can do (without using an array) that will allow directories like that to work but you can check the input arguments for compatibility and disallow any that don't fit those limitations.

As I said on some other question (of yours I believe) that shift in the while loop is incorrect. You are shifting off (an increasing number of arguments) during the getopts processing. You want to do that shift once and after getopts is done.

Try this and see what I mean:

$ cat test-getopts.sh
#!/bin/sh

while getopts ":dh" opt; do
    case $opt in
        d) echo DEBUG=true;;
        h) echo HELP;;
        \?) echo error;;
    esac
    printf 'Shifting %d\n' $((OPTIND - 1))
    shift $((OPTIND - 1))
done
$ /bin/sh go.sh -d -h -d -h -d -h -d -h -d -h -d -h
DEBUG=true
Shifting 1
DEBUG=true
Shifting 2
HELP
Shifting 3
HELP
Shifting 4

There is almost never a reason to pipe grep to awk or sed to awk or awk to sed. awk can  almost certainly do everything you need.

So the grep | awk | sed part of $(df ${MOUNT} | grep / | awk '{ print $5}' | sed 's/%//g') can be replaced by a single awk call:

`$(df "${MOUNT}" | awk '/\/{gsub(/%/, ""); print}')`

You'll also notice I quoted "${MOUNT}" there. In general you always want to quote shell variable expansions. In this case it can't actually matter since anything these quotes would protect will already have been expanded/word-split by the for MOUNT in ${MOUNTPOINTS} loop but it is the right thing to do anyway.

Also related to df if you are going to try to field-parse the output you want to use the -P/--portability option. It keeps df (at least from coreutils) from wrapping long lines to get columns to line up (and breaking field counts).

The syntax of if tests in the shell does not require wrapping parentheses. In fact, adding them spawns a sub-shell. So if ($DEBUG); then is running the value of $DEBUG as a command in a sub-shell. If you were to have set DEBUG=debug instead of DEBUG=true you'd have gotten an error from that because debug isn't a valid command. Drop them and use a non-empty or value checking test instead. Either if [ -n "$DEBUG" ]; or if [ "$DEBUG" = DEBUG ];.

You don't need to quote single quotes in a double quoted string so:

echo "Your ${MOUNT} partition\'s remaining space is critically low. Used: ${CURRENT}%"

should be echoing partition\'s out which probably isn't what you want.

for var in $@; do can be simplified to for var; do if you wanted and if you don't then you should use for var in "$@"; do though again given that spaces/glob characters are going to be a problem later this isn't as useful as it might be (though it does let you test for them correctly and avoid them as discussed above).

Also, if you haven't already, you should run your code through shellcheck.


Finding subsequences of vector from a vector

This is a really straightforward and simple solution that's easy to understand! I don't know that you could make it much simpler than it is. But here are some things I would change:
Variable Names
I think the naming could be improved. The names v1 and v2 don't exactly tell us what they're for. I recommend something like source or toSearch for v1 and subsequence or searchFor for v2. founds is also a really weird sounding name. I would name it results or subsequenceIndexes or something a little more descriptive.
Loops
You have 2 for loops that use old-school indexing. It would be better to use an iterator here since you need to pass one to search() anyway. Something like this:
for(auto nextIndex = v1.begin(); nextIndex < v1.end(); nextIndex++)
{
    auto it = search(nextIndex, v1.end(), v2.begin(), v2.end());
    // ... etc.
}

Likewise for the second for loop.
Errors
Also, is the code in the if correct? It seems wrong to me. It looks like you're trying to skip over the contents of the subsequence you just found and start at the element one past the end of the subsequence. There are 2 problems here. The first is that you're skipping too much. For example, if you subsequence is found at position 7, but the subsequence is only 3 characters long, you're adding 7 to the current position, so you're missing 4 characters that could contain another copy of the subsequence.
But beyond that, there's also the issue of overlapping copies of a subsequence. Let's say the sequence to search for is "1, 2, 1" and the string to search is "5, 8, 1, 2, 1, 2, 1, 2, 1". How many copies of the subsequence are there? If the answer is 2, then you were on the right track. But if the answer is 3, then your solution will miss one. (I'm seeing 3 at index 2, 4, and 6, but you could argue that you only want the ones at indexes 2 and 6.)


It's been a while since I've done Javascript, but I think that you want something that looks like this:

function set_video_on_mouseenter(suffix, video_ID, mp4_ID, ogg_ID, mp4_value, ogg_value) {
  $('#videolink-' + suffix).mouseenter(function(event) {
    //$(this).toggleClass('home-pager-hover');

    $('.top-clock').stop( true, true ).fadeOut();
    $('#'+video_ID).stop( true, true ).hide();

    $('#'+video_ID).stop( true, true ).get(0).pause();
    $('#'+mp4_ID).stop( true, true ).attr('src', mp4_value);
    $('#'+ogg_ID).stop( true, true ).attr('src', ogg_value);
    $('#'+video_ID).stop( true, true ).get(0).load();
    $('#'+video_ID).stop( true, true ).get(0).play();

    $('.top-clock').stop( true, true ).removeClass('top-clock--visible');
    $('.top-clock-' + suffix).stop( true, true ).addClass('top-clock--visible');

    $('#'+video_ID).stop( true, true ).delay('500').fadeIn();
    $('.top-clock-' + suffix).stop( true, true ).delay('500').fadeIn();
  });
}

set_video_on_mouseenter('sd', videoID, mp4ID, oggID, sdmp4, sdogg);
set_video_on_mouseenter('sk', videoID, mp4ID, oggID, skmp4, skogg);
set_video_on_mouseenter('rb', videoID, mp4ID, oggID, rbmp4, rbogg);

$('.home-pager li').mouseenter(function(event){
    $('.home-pager li').stop( true, true ).removeClass('home-pager-hover');
    $(this).stop( true, true ).addClass('home-pager-hover');
});

There isn't enough code here to actually run, so I didn't test.  If you post a link to a page that actually has the code working, I can try to do more.

I didn't try to make the code more elegant.  This is a very mechanical refactor.  I looked at what changed and extracted that as well as variable uses from the original code.  Then I just call my new function with the extracted parameters.  You could probably do this without extracting the three ID variables, but I think this is more reliable since I can't verify that the code works.


Correctness

The algorithm is actually quite tricky to implement correctly.  Your algorithm gives the wrong results for some examples in the Wikipedia article:

$$\begin{array}{l|l|l}
\textrm{Name} & \textrm{Correct Soundex} & \textrm{Your result} \\
\hline
\textrm{Ashcroft} & \textrm{A261} & \textrm{A226} \\
\textrm{Pfister} & \textrm{P236} & \textrm{P123} \\
\end{array}$$

Specifically, note the following rule:

  Two letters with the same number separated by 'h' or 'w' are coded as a single number, whereas such letters separated by a vowel are coded twice. This rule also applies to the first letter.

As a consequence, the code must…

… treat "H" and "W" differently from the vowels, so char `elem` "AEIOUHWY" = '0' is wrong.  I recommend using '0' to temporarily indicate the presence of a vowel, and dropping 'H' and 'W' unless it is in the initial position.
… lookup the digit for the first character too, to see if the next nonzero digit should be discarded.  Therefore, compr  = map (compress . toUpper) ame is wrong.

Style

ame and noDoub are pretty weird variable names.  For a clear and idiomatic function definition, I suggest

soundex name@(n:ns) = n : take 3 (noZero ++ "000")
  where
    …

Note that result should probably be eliminated.

remDoubles could be simplified to map head . group, using the group function from Data.List.  I would rename remDoubles to dedup.

compress is oddly named, as it maps one Char to exactly one Char.

I prefer imports to be more explicit about what functions are imported.

Suggested solution

import Data.Char (toUpper)
import Data.List (group)

soundex :: String -> String
soundex []   = []
soundex name = (toUpper $ head name) : nnn
  where
    dedup = map head . group
    nnn = take 3 $ (++ "000") $ filter (/= '0') $ tail $ dedup $ digitize name

digitize :: String -> String
digitize name = d : filter (/= '-') ds
  where
    digitFor c
      | c `elem` "AEIOUY"   = '0'
      | c `elem` "BFPV"     = '1'
      | c `elem` "CGJKQSXZ" = '2'
      | c `elem` "DT"       = '3'
      | c `elem` "L"        = '4'
      | c `elem` "MN"       = '5'
      | c `elem` "R"        = '6'
      | otherwise           = '-'   -- 'H', 'W', and punctuation
    (d:ds) = map (digitFor . toUpper) name

Note that the order of the chain of functions used to define nnn is critical.  Yours was closer to…

nnn = take 3 $ (++ "000") $ filter (/= '0') $ dedup $ digitize $ tail name

… which explains the "Pfister" bug.

To address the "Ashcroft" bug, I've rewritten compress as digitize, which can return a shorter string that drops output corresponding to a non-initial 'H' and 'W'.


The expressions Int(256 / (Max * 2)) and Int(256 / Max) have constant values inside the loop. It would be good to save them in a local variable before the loop and reuse.

The line where you set the cell color is too long, I have to scroll horizontally to see what's on the right hand side of the line. You could improve that by putting the red, green, blue values in variables. I would also rename the current red, green, blue variables to redBase, greenBase, blueBase, or similar.

The naming of the loop variables Row and col are inconsistent in capitalization. It would be better if they were either both lowercase or both starting with a capital letter. Similarly, it would be better to consistently capitalize all keywords, like you did For and Next.