Find the first common ancestor of 2 nodes in a binary tree

I see some things that may help you improve your code.

Provide complete code

This is really more about getting a good review rather than anything particularly wrong with your code, but as was mentioned in one of the comments, having complete code and a short example definitely helps people both understand your code and shows the intended context.  These are both useful for both clarity and completeness of your question.

Consider a different algorithm

There is a much simpler way to go about this than either the code currently implements or has been suggested by others.  First, consider a post-order traversal.  In a post-order traversal, we visit left nodes, then right nodes, then root nodes.  Consider the following tree:

In it, left nodes are green and right nodes are red.  They are just the names of the months in English (an in-order traversal would display the months in alphabetical order.)  Imagine that we wish to find the first common ancestor of the "February" and "November" nodes.  The algorithm works as follows:

traverse the tree in post-order looking for one of the target nodes
after one of the target nodes is found, keep track of the lowest tree level encountered until the other target node is found
continue the traversal until a node is encountered that is one level above the highest one recorded in step 2.  That node is the first common ancestor.

This requires, at worst case, exactly one traversal of the tree which makes it considerably more efficient that the current algorithm.  In fact, it should be obvious that for an unordered tree, there is no faster algorithm possible.

I've created the following version of a TreeNode structure for this demonstration.

struct TreeNode {
    TreeNode *left;
    TreeNode *right;
    std::string label;
};

The traversal code looks like this:

enum states { LOOKING_FOR_FIRST, LOOKING_FOR_LAST, FINISHING, DONE };

TreeNode *postOrder(TreeNode *n, int depth, TreeNode *t1, TreeNode *t2, states &state)
{
    static int highest;
    static TreeNode *answer;
    if(n != nullptr)
    {
        postOrder(n->left, depth+1, t1, t2, state);
        postOrder(n->right, depth+1, t1, t2, state);
        switch (state) {
            case LOOKING_FOR_FIRST:
                if (n == t1 || n == t2) {
                    state = LOOKING_FOR_LAST;
                    highest = depth;
                }
                answer = nullptr;
                break;
            case LOOKING_FOR_LAST:
                highest = std::min(highest, depth);
                if (n == t1 || n == t2) {
                    state = FINISHING;
                    --highest;
                }
                break;
            case FINISHING:
                if (depth == highest) {
                    state = DONE;
                    answer = n;
                }
                break;
            case DONE:
                return answer;
        }
    }
    return answer;
}

The equivalent to your routine could be written like this:

TreeNode *fca2(TreeNode * root, TreeNode * q, TreeNode * p)
{
    if (root == NULL || q == NULL || p == NULL) {
        return NULL;
    }
    states state = LOOKING_FOR_FIRST;
    return postOrder(root, 0, q, p, state);
}

Now for test code:

testancestor.cpp

#include <iostream>
#include <string>

// code above goes here

int main()
{
    TreeNode tree[]{
        {&tree[1],  &tree[2],  "March"},                //  0
        {&tree[3],  &tree[4],  "January"},              //  1
        {&tree[5],  &tree[6],  "October"},              //  2
        {&tree[7],  &tree[8],  "August"},               //  3
        {&tree[9],  nullptr,   "June"},                 //  4
        {nullptr,   &tree[10], "May"},                  //  5
        {nullptr,   nullptr,   "September"},            //  6
        {nullptr,   nullptr,   "April"},                //  7
        {&tree[11], nullptr,   "February"},             //  8
        {nullptr,   nullptr,   "July"},                 //  9
        {nullptr,   nullptr,   "November"},             // 10
        {nullptr,   nullptr,  "December"},              // 11
    };

    // What is the common node for February and November?
    TreeNode *root = &tree[0];
    TreeNode *a = &tree[8];
    TreeNode *b = &tree[10];
    TreeNode *answer = fca2(root, a, b);
    std::cout << "common node of " << a->label
              << " and " << b->label << " is "
              << answer->label << "\n";
    // What is the common node for February and July?
    b = &tree[9];
    answer = fca2(root, a, b);
    std::cout << "common node of " << a->label
              << " and " << b->label << " is "
              << answer->label << "\n";
}

Results

common node of February and November is March
common node of February and July is January

Possible enhancements

Note that this test code is not particularly great, but I'm hoping that it's clear enough to demonstrate the basic algorithm.  Improvements could be made.  For example, the code doesn't currently actually stop the traversal when the ancestor node is found, but it certainly could.  Also, the static data would prevent this from being used as-is in a multithreaded environment.  A better alternative would likely be to encapsulate this within a class to avoid both the static variable and the global states.


Since the end condition of the loop is always true, you can just omit it:

    for (int i = 1; ; i++)

The condition in the final else if(guess == number) is always true,
so you can use simply else.

There's no need to separate the declaration and initialization of the guess variable,
you can do int guess = input.nextInt() which is shorter.

The convention in Java is to put opening braces on the same line as the statement,
like this:

    for (int i = 1; ; i++) {
        int guess = input.nextInt();
        if (guess < number) {
            System.out.println("Du gissade för lågt");
        } else if(guess > number) {
            System.out.println("Du gissade för högt");
        } else {
            System.out.println("Antal gissningar: " + i);
            System.out.println("Grattis du gissade rätt!");
            break;
        }
    }


Split string with adding separator to substring

Review

You use very clean and strong names for all your variables so it's very easy to understand your code.
You too often go without {}. Especially the double for loops become very confusing.
You don't use good exception messages. In Arg_SeparatorEnumIllegalVal the Arg prefix is not necessary because the type of the exctpion is already telling me it's about an argument. You also formatted it like it was a variable with PascalCase but it's a message so it should be formatted like a normal sentence.

Alternative solution
There is a much shorter way to get the same results. You could use two different regexes:
var str = "-1-2+3+4-5-6";

Regex.Matches(str, "([-+]?[0-9]?)").Cast<Match>().Select(m => m.Value).Dump();
Regex.Matches(str, "([0-9]?[-+]?)").Cast<Match>().Select(m => m.Value).Dump();

which will respectively give you:
-1
-2
+3
+4
-5
-6
""

and
-
1-
2+
3+
4-
5-
6
""

Whether you want to keep the empty string or not is up to you.


Composing URLs for fetching passenger fares from multiple providers

You can definitely simplify some things. For example, determining the ages variable:

kid_age = ''
if len(pax['ages']) > 0:
    for age in pax['ages']:
        kid_age += str(age) + ','
    kid_age = kid_age[:-1]
ages = 0 if kid_age == '' else kid_age

can be done in a single line and str.join():

ages = ','.join(pax['ages']) if pax['ages'] else 0

Some other notes:

docstrings should be enclosed in triple double quotes, not single quotes
I would move create_link from out of the function to "helpers" or "libs"
define your format_url format strings as constants and move to the module level
follow lower_case_with_underscores variable and method naming convention
define your date format as a constant as well - this way, if it changes, you would make a change in a single place only


A short list of issues I've noticed after a first glance at your code:

Pokemon exception handling (gotta catch 'em all): wrapping everything in a huge try-catch block is considered bad practice. What makes your code stand out even more is the pointless second catch
pointless second catch: a PDOException is a custom exception class, which is to say: PDOException extends Exception, therefore, your catch (Exception $e) block will catch instances of PDOExceptions, too. As a result, the second catch block is obsolete. Pointless. Code-smell. Noise. Get rid of it.
clean_data is not great. It's bad even. I can understand the strip_tags call, but addslashes is really rather pointless here. And a possible source of bugs. If you forget to call addslashes when inserting a password, or in some other piece of code that handles login information, the passwords in the DB won't match, even though the user has filled out the form correctly. You're using prepared statements, no need to add slashes. If anything, it does more harm than good
From the variable name ($pdo), it's quite obvious what kind of class DbConnect is. And, like I've posted on this site so many times (links below): it's evil. PDO offers a clean, well balanced, easy to use and powerful, fully object oriented API. You can't wrap it into something and end up with a better tool. Far from it. The only thing that you can do with it is to use it as a base in a fully-fledged DBAL like doctrine. And since doctrine already exists, writing it yourself is, basically, reinventing the wheel.
Generally, I don't like PHP code that strings together markup. It's error prone, and hard to maintain. That's why I didn't pay much attention to the HTML bit, but as tim pointed out: $_SERVER['PHP_SELF'] is a bad idea. If the form should be processed by the same script (or on the same url) that spawned it, just don't specify an action attribute. The default behavior is to post the form back to the same url anyway.

Links to previous answers explaining why you shouldn't try to wrap PDO:

Class for reducing development time
OOP PDO Database Connection
A PDO connection classto initiate multiple connection and easy access
Extendable PDO Wrapper Class
Check my profile, I'm pretty sure there are a lot more answers that deal with the matter, but I can't be bothered to look for every single one of them.


Code looks fine - but it strikes me as somewhat unnecessary.

A promise can only be resolved/rejected once, so if you just keep the promise object itself around, its result is automatically cached within. I.e. if you call .then() on an already-resolved/already-rejected promise object, it'll just immediately invoke your handler(s) with whatever data it was originally resolved/rejected. It won't re-do whatever caused it to be resolved/rejected. So just keep the promise object itself around and you can use it whenever you want.

In order words, caching promise objects makes sense (e.g. caching web request promises), but caching promise results is built-in and happens automatically.

So to that end, it'd be smarter to add caching at a higher level. I.e. don't wrap generic promises, instead wrap specific tasks like network requests and such where caching the promise is desired and you can have more control over what keys to use, when to invalidate the cache etc..

I'd do something like this

// *specialized* function for, say, network requests,
// where caching is desired. In this case, we're caching
// promises by the URL they're fetching
var fetch = (function () {
  var cache = {};
  return function (url) {
    cache[url] = cache.hasOwnProperty(url) ? cache[url] : new Promise(/* request magic goes here */);
    return cache[url];
  };
});

(Obviously, you'll want a way to invalidate the cache etc., this is just to illustrate the point)


Doesn't work
The program doesn't work for me.  Example:
$ ./fibonacci
Please input the Nth index of the last sequence value.
Program will return entire Fibonacci Sequence up to and including Nth value.
10
1 1 2 3 1 0 1 1 2 3

The problem is that the array tempseq is a temporary local variable, which means that every time you call the function Fibonacci(), that variable becomes unitialized.  Your code is doing two things wrong:

It assumes that tempseq will contain the values that it had from previous invocations of the function Fibonacci().
It assumes that Fibonacci() will be called in a loop from 0 to n.  If you just called Fibonacci(10) directly, it would not work because it depends on the answers for 8 and 9 being precomputed.

Fixes

To fix problem #1, you can declare your tempseq array using the static keyword.  This makes the array persist across invocations.  You can think of it like if the static keyword made the tempseq variable into a global variable.

To fix problem #2, you should not assume that an entry in tempseq is necessarily valid.  You can do something like check if the entry is 0.  If it is zero, then the entry must be computed, otherwise it is valid to use.

Rewrite
I have rewritten your function with the two problems fixed:
#define FIBMAX        100

// Computes the Nth Fibonacci number.
unsigned int Fibonacci(unsigned int n)
{
    // FibResult is a persistent array of already computed values.
    // We initialize fibResult[0] and [1] to take care of special cases.
    static unsigned int fibResult[FIBMAX] = { 1, 1 };

    // Guard against bad input.
    if (n >= FIBMAX)
        return 0;

    if (fibResult[n] == 0) {
        // We have not previously computed this entry, so compute it now
        // using the recurrence relation.
        //
        // Note: calling Fibonacci(n-1) guarantees that fibResult[n-2] will
        // be set, so we just use that to avoid one function call.  We
        // could have written this and it would have worked just fine:
        //
        // fibResult[n] = Fibonacci(n-1) + Fibonacci(n-2);
        //
        fibResult[n] = Fibonacci(n-1) + fibResult[n-2];
    }

    return fibResult[n];
}

This rewrite also:

Replaces the magic number 100 with a defined constant and checks the input so that we don't have any buffer overflow problems.
Takes care of the special cases of n=0 and n=1 by filling in those entries in the fibResult array.

Simpler way
You might also want to consider a simpler function that doesn't use an array of precomputed values.  Calculating a fibonacci number can be done in a simple loop like this:
unsigned int Fibonacci(unsigned int n)
{
    unsigned int f1 = 1;
    unsigned int f2 = 1;

    for (unsigned int i = 0; i < n; i++) {
        f2 = f1 + f2;
        f1 = f2 - f1;
    }
    return f1;
}


BUGS
The function retrieveName() is doing the input of the name twice.

        if (fgets(name, buffersize, stdin) != NULL) {
            size_t nlcspn = strcspn(name, "\n");
            bool incomplete = name[nlcspn] == 0;
            name[nlcspn] = 0;
            if (incomplete) {                    int bufferclear;
                while ((bufferclear = getchar()) != '\n' && bufferclear != EOF);
            }
            if (name[0] == '\0' || !hasAlpha(name, buffersize)) {
                printf("Invalid name entered please try again...\n"
                       "USER NOTE: name cannot be empty and must contain at least one char\n");
            }
            else {
                return;
            }

Both fgets() and getchar() are getting input from stdin. The search you are
performing for end of line is failing because bufferclear should be EOF on the
first execution of the loop. What you should be doing is a search for end of line
on name.

Keep it Simple
Since you are reading from stdin, use gets() rather than fgets(), gets() has
the same semantics as fgets() but only reads from stdin. If you want
retrieveName() to be able to read from any file you should add another parameter
this is either the file name or a FILE pointer. If it is the file name than
retrieveName() will need to perform a fopen().

There is a software engineering/programming principle call KISS, or Keep it Simple.
_principle
The simpler you make the code the easier it is to write, maintain and debug.

Alignment
If name is going to be used in a struct at some point in the future, you should
consider the alignment of the fields in the struct to make the most efficient use
of memory. Computers implement strings in words of memory. A word is some power
of two bytes long, in the past this has been either 2 or 4 bytes, most computers
and compilers are going to use 8 bytes these days in a 64 bit architecture.
Therefore BUFFSIZE should be some multiple of 8 (8, 16, 24, 32). I'd suggest
as a minimum 16 because 8 may be too small.

Use Functions or Loops for Repetitive Code
In software engineering there is a programming principle called Don't Repeat Yourself.
Any time you have repeating code such as :

    printf("Enter Name: ");
    retrieveName(name, len);
    printf("Your name is: %s\n", name);

in main() you should consider either creating a loop or writing a function.
Generally I would recommend writing a function, but in this case a loop will
do just as well.


Django query_set filtering in the template

I'll refer you to a Stack Overflow post that pretty much nails the answer.

I assume that you want to display all recipes that have "Sub Featured Photos".

The call recipes = Recipe.objects.filter(recipephotos__type=3) will give you a queryset of recipes that have at least one photos with type 3. So far so good. Note, that this code is in the views.py file and not in the template. Like the StackOverflow post mentioned, you should put the filtering code in your view or model.

Personally I'd prefer writing a function for your model class:

class Recipe(models.Model):
    (...)
    def get_subfeature_photos(self):
        return self.recipephotos_set.filter(type="3")

And access it in the template like this:

{% for recipe in recipes %}
      {% for photo in recipe.get_subfeature_photos %}
            {{ photo.url }}
      {% endfor %}
      (...)
{% endfor %}

Please note that the function is using filter() for multiple items instead of get(), which only ever returns one item and throws a MultipleObjectsReturned exception if there are more.


Should this code be in the code behind or separate class?

Since you actually have a business layer, that's where I'd put it.  You should let the business layer handle the finding/creating of an organization, so all the WebForms code needs to do is ask for an IpasLogOnManagement.IpasOrganization object based on the name the user selected (lstOrganizations) or entered (txtOrganizationName).


Use of global should generally be avoided. You could create a class to hold the dictionary and the three functions would become methods.
Don't repeat yourself: use a variable for the file name so you don't have to change it in three places if it needs to change.
The save_score function assigns new_score = (name, score) for no reason at all. Using the two variables directly in the code that follows would improve readability.


Making EmployeeHistory ViewModel immutable as code analysis suggested

Nulls: What happens when someone asks for an EmployeeHistory without passing in an employee ID? It's hard for me to believe that the API for retrieving history will behave well, must less the call to db.Employees.Find(), and certainly not the cast (int)employeeID.

I would recommend either immediately checking this and bailing out (with an ArgumentNullException or an empty view, or whatever you think is best), if you aren't already doing so. Or, you could the signature to EmployeeHistory(int employeeID) - since without an employee ID there is very little you can do.

Names: You have an EmployeeHistory object, with three properties all named Employee-something. This is a bit redundant. Perhaps just ID, Name, and PositionsOverTime? Or PositionsHeld?

Although that would imply that that EmployeeHistory.ID is the ID of the history... But that raises the question to me, why copy these properties from the Employee object at all? Why not just hold a reference to the actual Employee?

In fact, perhaps it would make more sense to add the history of positions held to the Employee object. That does make more sense: "This employee has this history", rather than the other way around.

As a side note, I'll grant that abbreviations like emp, e, and empHist are easy enough to parse in this case. However, my preference would still be for complete words when possible. Remember that code is read far more often than it is written, so if a few extra keystrokes now save a few seconds of parsing later, that's a net win.

Encapsulation: You may have satisfied the requirement of a read-only collection in the eyes of your code analyzer, but you have not done so in fact. While a consumer of this class would not have the ability to swap out the entire list for one of their own, the IList<T> interface is permissive enough that they may as well. Here's a demo.

If you want to make this history truly read-only, you'll need to avoid handing out a direct reference to the list. List.AsReadonly() is good for this.

Another thing you may want to encapsulate is the order of the list. You have decided* that the history should be sorted with the most recent assignEffDateNext first. If you want to guarantee that histories are always ordered this way, the logic to do so belongs in the history's constructor.

*As a side note, I personally would not sort this list on the back end at all. Suppose a user wants to view the list in chronological order? Or sorted by position title? Javascript is perfectly capable of sorting arrays of the size you're likely to have. This gives your users flexibility while keeping (an admittedly very small) load off the server.

Robustness: "Be conservative in what you send, be liberal in what you accept." It's generally nice when functions only ask for what they need. As it stands, an EmployeeHistory cannot be constructed with a Collection of positions - even though just a simple IEnumerable ought to be sufficient. Save yourself future calls to .ToList(), and open up this constructor to be more permissive.

This same principle, in my mind, suggests that you should be as specific as possible about what you're returning. Making positions available as an IReadOnlyList is good, because it allows your users to access positions by index. For the same reason, I would also be more specific about what you're returning from the view. It is an ActionResult, yes... But more specifically it's a ViewResult. This may not have a big impact on your front end, but it could help with testability or refactoring down the line.

Here's how this code might look when you're done:

public class EmployeeHistory
{
    public Employee Employee { get; }
    public IReadonlyList<IDMSElementData> PositionsHeld { get; }

    public EmployeeHistory(
        Employee employee,
        IEnumerable<IDMSElementData> positions)
    {
        Employee = employee;

        PositionsHeld = positions
            .OrderByDescending(position => position.assignEffDateNext)
            .ToList()
            .AsReadOnly();
    }
}

public async Task<ViewResult> EmployeeHistory(int employeeID)
{
    var positions = GetPositionsFromSomeAPICall(employeeID);

    var employee = db.Employees.Find(employeeID);

    var history = new EmployeeHistory(employee, positions);

    return View("EmployeeHistory", history);
}


jQuery animations with only one callback

I'd say your approach is correct. Since your delay is less than the duration, you can't use a series approach, where one completed animation starts the next. So your setup is probably the simplest you can do.

To make it more readable, the simplest thing would be to split the code up a bit:

$(function () { // same as $(document).read(...)
  // declare some "constants"
  var animationDelay = 800,
      animationDuration = 1000;

  // setup all the animations
  var queue = $(".elm").each(function (i) {
    $(this).delay(i * animationDelay).animate({opacity: 0}, {duration: animationDuration});
  });

  // set up the callback for when they finish
  $.when(queue).then(function () {
    // all animations done
  });
});


Creating directory within Application Support, and preventing iCloud backup

File System Basics tells us:

  The contents of the Library directory (with the exception of the Caches subdirectory) are backed up by iTunes and iCloud.

And

  Put data cache files in the Library/Caches/ directory. Cache data can be used for any data that needs to persist longer than temporary data, but not as long as a support file. Generally speaking, the application does not require cache data to operate properly, but it can use cache data to improve performance. Examples of cache data include (but are not limited to) database cache files and transient, downloadable content. Note that the system may delete the Caches/ directory to free up disk space, so your app must be able to re-create or download these files as needed.

If this content is readily re-downloadable, Caches might actually be a reasonable idea. It makes your app a “good citizen”. If the user is running low on storage, it might be better to allow re-downloadable content to be removed rather than tempting the user, looking at their storage taken up by various apps, to contemplate removing your app because it’s taking up a lot of unreclaimable space.

If you want to ensure the content will never be deleted when the device runs low on space, then go ahead and put it in the Application Support directory, but manually exclude it from backups, like you have done.

Feel free to refer the iOS Storage Best Practices video (and that page has useful links).

You said:

  I think there's no guarantees about the lifetime of files in the Cache dir

Correct. In practice, when (a) the device runs low on space; and (b) your app is not running, the OS can purge this directory. It starts with apps that have been use less recently.

  Also, I want to make sure that those content files aren't backed up to iCloud or anywhere else; and that they're not accessible by the user or other apps.

By the way, whether it’s backed-up or not and whether it’s accessible by the user are two different questions. E.g., files in the Application Support directory are backed-up (other than, obviously, content of the Caches folder or those files explicitly designated to not be backed-up). But the contents are not visible to the user. Only user documents stored in Documents folder or iCloud Drive are visible to the end-user.

So, if your content is not readily re-downloadable, but you don’t want to expose them to the individual files, Application Support (without specifying NSURLIsExcludedFromBackupKey) might be prudent. It’s your call.


The reason why your epochs are so slow is because you are iterating over each example in the batch and calculating the gradients in a for loop. The key to speeding this up is realizing that you are performing the same operations over every example in the batch, and so you can stack your examples into a matrix and calculate the gradients for all examples in a single matrix operation.

Let's break that down. For a single example, you start with a feature vector of size (1000,) and that is linearly transformed by multiply it by a weight matrix of size (1000,900) resulting in a (900,1) vector that is then added with a bias vector of size (900,1). This is then non-linearly transformed, which does not affect the dimensions, to result in the first hidden layer of size (900,1).

This is 900 hidden nodes for the first example.

However, since we are performing the same operations to every example in the batch, we can stack the 100 examples to form a matrix of size (100,1000) instead of (1,1000) then take the dot product of this input matrix with the transpose of the weight matrix, (1000,900) for a resulting matrix of (100,900). Add the bias (1,900), which is broadcasted automatically in numpy to a matrix of size (100,900) (it's the same bias vector stacked 100 times) and apply the non-linear transform for a final matrix of size (100,900). This is 900 hidden nodes each for 100 examples.

This can be applied to each hidden layer in the network.

Factoring the original code:

for i in batch:
    # Feedforward
    a[0] = array([I[i]]).T
    for l in range(nn_size-1):
        z[l] = dot(W[l], a[l]) + b[l]
        a[l+1] = sigma(z[l])

    # Backpropagation
    delta = (a[nn_size-1]-array([y[i]]).T) * sigma_prime(z[nn_size-2])
    dW[nn_size-2] += dot(delta, a[nn_size-2].T)
    dW[nn_size-2] += delta.dot(a[nn_size-2].T)
    db[nn_size-2] += delta
    for l in reversed(range(nn_size-2)):
        delta = dot(W[l+1].T, delta) * sigma_prime(z[l])
        dW[l] += dot(delta, a[l].T)
        db[l] += delta

into matrix math form:

a[0] = I[batch]
for l in range(nn_size-1):
    z[l] = a[l].dot(W[l].T) + b[l].T
    a[l+1] = sigma(z[l])

delta = (a[nn_size-1] - y[batch]) * sigma_prime(z[nn_size-2])
dW[nn_size-2] += 2*delta.T.dot(a[nn_size-2])
db[nn_size-2] += np.sum(delta.T, axis=1, keepdims=True)

for l in reversed(range(nn_size-2)):
    delta = delta.dot(W[l+1]) * sigma_prime(z[l])
    dW[l] += a[l].T.dot(delta).T
    db[l] += np.sum(delta.T, axis=1, keepdims=True)

When calculating gradients over batches, taking the sum or average of the gradients over the examples both work, but Andrew Ng suggests using the average over the batch as explained in his course and here: https://stats.stackexchange.com/questions/183840/sum-or-average-of-gradients-in-mini-batch-gradient-decent

In this case, since you divide the gradients by batch size, you can just sum the gradients over the batch.

With the original for loop implementation over 10 epochs, each epoch takes anywhere between 1.75 - 2.25s with an average of 1.91s per epoch.

With the matrix implementation over 100 epochs, each epoch takes between 0.06 - 0.25s with an average of 0.08s per epoch.

Parallelizing sgd is also somewhat non-trivial as SGD is a sequential algorithm. For example, imagine that you are standing on the top of a hill and are trying to find the quickest way down (without being able to see it). The only way to make your way down the hill is by actually taking steps downwards and re-evaluating your options at each step. Even if there were multiple clones of you, all your clones would be standing at the same spot on the hill and so the information gain would be limited. Nevertheless, there are techniques for parallel sgd and so if you are determined on pursuing that, I would suggest you read some papers on the topic:

Cheng 2017: Weighted parallel SGD for distributed unbalanced-workload training system https://arxiv.org/abs/1708.04801

Zinkevich 2010: Parallelized Stochastic Gradient Descent http://martin.zinkevich.org/publications/nips2010.pdf

Or for a higher level overview:
http://blog.smola.org/post/977927287/parallel-stochastic-gradient-descent


Summing the prices from Transaction files

Nitpicks
There is a slight amount of inconsistency in your capitalization of keywords. SUM() / sum() and WHERE / where. Otherwise, it's pretty consistent throughout!

Aliases
You use the following aliases: B C T. There is no meaning or explanation of what those mean. You should use meaningful aliases, especially where your table names don't really help, such as in your case.

Old-style JOIN
This:
FROM
    TAD1D.ST_EUCM AS B,
    TAD1D.ST_DSA_TRAN  AS C,
    TAD1A.TIBHLD T
WHERE C.ST_TRAN_FILE=B.ST_TRAN_FILE
    AND C.ST_IND='Y'
    AND C.ST_SRC_SYS_CD='HANN'
    AND C.ST_TBL_NAME='ST_EUCM'
    AND B.PARTNUMB=T.ACCT_NUM
    AND B.FVSRVCCODE=T.SRV_CD

...is deprecated pre-ANSI-92 syntax. It should not be used, rather you should favor explicit JOIN syntax, like such:
FROM
    TAD1D.ST_EUCM AS B
INNER JOIN
    TAD1D.ST_DSA_TRAN  AS C
    ON C.ST_TRAN_FILE = B.ST_TRAN_FILE
INNER JOIN
    TAD1A.TIBHLD T
    ON B.PARTNUMB = T.ACCT_NUM
    AND B.FVSRVCCODE = T.SRV_CD
WHERE
    AND C.ST_IND = 'Y'
    AND C.ST_SRC_SYS_CD = 'HANN'
    AND C.ST_TBL_NAME = 'ST_EUCM'

Notice I added spaces around your = operators as it makes the code easier to read. You would also want to use similar JOIN syntax in your subquery.

Indexes
You stated:

There are no indexes on either table. Please provide a tip/solution in the event i am able to change the table structure or add an index (I may not).

And to that, I say resoundingly: YES! Add indexes!
But make sure even before you do that, look carefully at your query execution plan and look at where the most expensive steps are. That should give you a clue as to what is happening. I suspect there are a few nasty nested loops in there that are bogging it down, and depending on your RDBMS there are some optimizations available, and there may be ways to change the execution manually.


Check if object contains only empty nested objects

Some issues?

typeof is not a function. eg typeof(input) === 'object' is written typeof input === 'object'
null is an Object so when you test for an object using typeof you MUST make sure it is not null as well.
The test that you comment as // catch null or undefined object will catch any value that evaluates to a falsey, such as false, 0, ""

What is empty?

As it is unclear what you define as empty so I will make some assumptions, they are arbitrary and may or may not fit your needs.

An array is empty if it contains only empty items.
An object is empty if it is null or contains no own properties. If it has properties that are null or (defined as) undefined it is not empty.
A string is empty if it contains no characters
Empty items are null, undefined, {}, [], and ""

Examples

Empty

[],
{},
[undefined],
[null],
[[], [], []],
[{},,[],[[[null],[undefined]],[,,,,,]],
new Array(10),
null,
undefined,
""

Not empty

[0]
[{A:null}],
{A:undefined},
[,,,0],
[[], [], [1]],
[{},,[],[[[1],[]],[]],
(new Array(10))[1] = 0,
false,
true,
"  ",

Rewrite

With the above assumptions you can rewrite the code as a two functions.

As a non empty object mean we return false, and thus we do not need to iterate its values.

The entry point is isItemEmpty you would call it as you did isDeepEmpty

const isObjEmpty = obj => obj === null || Object.keys(obj).length === 0;
const isItemEmpty = item => item === undefined || item === "" ||
    (Array.isArray(item) && array.every(isItemEmpty)) ||
    (typeof item === "object" && isObjEmpty(item));

Usage

isItemEmpty([{},[],[[]]]);    // returns true
isItemEmpty([{A:0},[],[[]]]); // returns false
isItemEmpty("");              // returns true


In your if-else logic :

you can get rid of a few returns
if you have something like if (condition) { some_code(); some_more_code1(); } else { some_code(); some_more_code2(); }, you can write it by moving the common code : some_code() if (condition) { some_more_code1(); } else { some_more_code2(); } (assuming that the code doesn't affect the evaluation of the condition).
if you have a test with an empty then block, you can rewrite it with the negation to have a test with no else block.

Your CreateLeaf() seems to be something that could be done in a constructor.

Your updatevalue() seems to be something that could be done in the node class.

You can move the declaration of int x, y, z to a smaller scope.

Query should probably return a value instead of taking a reference.

Merge could take const references.

Using using namespace std is usually frowned upon.

Taking (most of) these comments (and some others) into account, I have :

#include <bits/stdc++.h>

#define _MAX (1<<17)
#define MAX (_MAX<<1)
using namespace std;

class Node
{
    public:
    Node(): tails(1), heads(0) {}

    void Merge(const Node &A,const Node &B) // Merge two Nodes
    {
        tails=A.tails+B.tails;
        heads=A.heads+B.heads;
    }
    /* Updates the value of a single Node.
   When we flip the coins, no. of heads and tails get swapped */
    void Swap()
    {
        swap(tails,heads);
    }
    int getNbHeads() { return heads; }
    private:
    int tails;
    int heads;
};

Node ST[MAX];   // Segment tree ST

/* res is the Node storing the result
   Information for range [l,r] is present in ST[idx]
   Query is required for range [u,v]  */

Node Query(int l,int r,int u,int v,int idx)
{
    if(l==u && r==v)
    {
        return ST[idx];
    }
    else
    {
        int mid=(l+r)/2;
        if(mid>=v)
            return Query(l,    mid,u,v,2*idx);
        else if(mid<u)
            return Query(mid+1,r,  u,v,2*idx+1);
        else{
            Node res;
            res.Merge(
                Query(l,    mid,u,    mid,2*idx), // left child is 2*idx
                Query(mid+1,r,  mid+1,v,  2*idx+1) // right child is 2*idx+1
            );
            return res;
        }
    }
}

void init(int idx,int l,int r) // initialises the tree
{
    if(l!=r)
    {
        int mid=(l+r)/2;
        init(2*idx,l,mid);
        init(2*idx+1,mid+1,r);
        ST[idx].Merge(ST[2*idx],ST[2*idx+1]);
    }
}

/* Updates the Node ST[idx] and all the Nodes descending the Node ST[idx]
   ST[idx] stores information for range [l,r]  */

void update(int l,int r,int idx)
{
    ST[idx].Swap();
    if(l!=r)
    {
        int mid=(l+r)/2;
        update(l,mid,2*idx); // Updates left child
        update(mid+1,r,2*idx+1); // Updates right child
    }
}

/* Range to be updated is [u,v]
   ST[idx] stores information for range [l,r] */

void UpdateRange(int l,int r,int u,int v,int idx)
{
    if(u<=l && r<=v)
    {
        // As soon as required Node is found, update the Node and all its descendant
        update(l,r,idx);
    }
    else
    {
        int mid=(l+r)/2;
        if(mid>=v)
            UpdateRange(l,    mid,u,v,2*idx);
        else if(mid<u)
            UpdateRange(mid+1,r,  u,v,2*idx+1);
        else
        {
            UpdateRange(l,    mid,u,    mid,2*idx);
            UpdateRange(mid+1,r,  mid+1,v,  2*idx+1);
        }
        ST[idx].Merge(ST[2*idx],ST[2*idx+1]);
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,q;
    cin>>n>>q;
    init(1,0,n-1); /* ST[1] stores information for [0,n-1] */
    while(q--)
    {
        int x, y, z;
        cin>>x>>y>>z;
        if(x==1)
        {
            cout<< Query(0,n-1,y,z,1).getNbHeads()<<"\n";
        }
        else
        {
            UpdateRange(0,n-1,y,z,1);
        }
    }
    return 0;
}

Also, I forgot to tell it but it would probably be worth encapsulating the logic around ST in some kind of class or at least pass the array as an argument as global variable can make things hard to track/maintain.


Find biggest palindrome which is the product of two 3-digit numbers

isPalindrome is ok here, no need to make it faster.
In functional programming functions are everywhere, even inside other functions and this is ok. Using ViewPatterns extension it is possible to rewrite is3x3 as:

is3x3 n = any cond [101..999]
    where
        cond (divMod n -> (d, 0)) = 99 < d && d <= 999
        cond _ = False

I don't know any readable way to rewrite cond2 without parenthesis.
Haskell is smart enough to calculate 999^2 and 999^2-1 at compile time. In terms of performance, if you don't specify end of the list there will be no checks for the end of the list at runtime (which is good in this case).

Using Integer is justified only for big numbers, in your case using Int is enough and could be a bit faster.

Here is another solution:

main = print $ maximum
  [ x * y :: Int
  | x <- [999, 998 .. 100]
  , y <- [x, x-1 .. 100]
  , (==) <*> reverse $ show $ x * y
  ]


Your code does have its share of C-isms, but we will be able to fix that.

But first, if you are learning Java in order to understand Object Oriented Programming, pick a better language. Java's OO primitives are classes, abstract classes, interfaces and single inheritance. Since Java was designed, the world has moved on, and trait-based OO (instead of interfaces) is all the rage. The Scala language isn't very C-like, but has a wonderful object system. Another interesting language for OO is Ruby with it's metaclasses.

I assume you already know about the difference of static and non-static fields and methods. Whatever is marked as static belongs to the class and is shared among all objects of that class. Your fillCharacters static method only operates on the class level, yet you call it in an object constructor. Instead of refilling the characters each time you make a new generator, initialize that array once.

A horrible C-ism is that you make your characters array fixed size, in the hope that it will be large enough. But you only fill it with 63 characters! This is the way bugs are born. Java has multiple collections (like LinkedLists or ArrayLists) that resize themselves if necessary. I would do something like this:

private static char[] characters = initCharacters();

private static char[] initCharacters() {
  final int initialCapacity = 63;
  // a vector is a variable-size array
  final List<Character> chars = new Vector<Character>(initialCapacity);

  // add digits 0–9
  for (char c = '0'; c <= '9'; c++) {
    chars.add(c);
  }

  // add uppercase A–Z and '@'
  for (char c = '@'; c <= 'Z'; c++) {
    chars.add(c);
  }

  // add lowercase a–z
  for (char c = 'a'; c <= 'z'; c++) {
    chars.add(c);
  }

  // Copy the chars over to a simple array, now that we know
  // the length. The .toArray method could have been used here,
  // but its usage is a pain.

  final char[] charArray = new char[chars.size()];

  for (int i = 0; i < chars.size(); i++) {
    charArray[i] = chars.get(i).charValue();
  }

  return charArray;
}

private static void showCharacters() {
  System.err.println("The following " + characters.length + " characters are available: " + new String(characters));
}

What was that characters.length? Yes, Java keeps book about the size of your arrays, so you don't have to! Keeping extra variables around for the size is error prone. Also note that I allocate various objects in the initCharacters method – the garbage collector will clean up after me.

Because our character array has no unused fields, we don't need the charactersSize and charactersCount variables any longer.

Something that C doesn't have is generics, i.e. parameterized polymorphism. The arguments in angled brackets are type names, which can only be classes. Java has primitive types like char and int. These have corresponding object types like Character and Integer.

Your get method is mostly allright. I'd call it nextPassword, and would rename rnd to random. The algorithm is fine.

One thing I'd do differently would be not using much object orientation for this problem. Creating a new PasswordGenerator for different sizes is silly. I'd rather use that functionality like

System.out.println(PasswordGenerator.nextPassword(passwordSize));

i.e. use the generation as a static method, and pass the requested size as a parameter.


Learn to love rustfmt:

Spaces go between comma-separated items:

-use std::io::{Read, Write,BufReader, BufRead};
+use std::io::{Read, Write, BufReader, BufRead};

-let response = format!("{}{}{}{}","HTTP/1.1 ",status," OK\n\n",res);
+let response = format!("{}{}{}{}", "HTTP/1.1 ", status, " OK\n\n", res);

Spaces go before braces:

-fn main(){
+fn main() {

-loop{
+loop {

Colons attach on the left side of type definitions:

-fn send_response(mut stream: TcpStream, res :&str, status :u32){
+fn send_response(mut stream: TcpStream, res: &str, status: u32) {

Pay attention to compiler warnings. One of the entire purposes of using a compiled language is to have the compiler watch your back. If you ignore it, then what good is it?

warning: unused result which must be used, #[warn(unused_must_use)] on by default
  --> src/main.rs:19:5
   |
19 |     reader.read_line(&mut lines);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

warning: unused result which must be used, #[warn(unused_must_use)] on by default
  --> src/main.rs:35:9
   |
35 |         file.read_to_string(&mut response);
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Introduce more functions to break up the distinct parts of read_request. From my inspection, there's a part that parses the request, a part that handles the request by reading a file, and a part that responds (which already exists). Note that doing this contrains the number of lines of code a variable is mutable and avoids the need to recover the inner TcpStream from the BufReader.
vec_line is poorly named; it's not a Vec. I am happy to see your use of nth; many people would collect into a Vec, which is inefficient.
There's no reason to convert the result of nth into a String, you can call replace on a &str equally as well.
Avoid using mut just to be able to reassign a variable (e.g. the result of replace). Instead, just bind the variable a second time. This reduces the amount and scope of mutability.
requested_page == "" should be requested_page.is_empty()
Why would you convert a String to a String using to_string? Just take a reference to the existing string.
There's no need to create a string to write to the stream; just write! directly to the stream.
The code always prints "OK", regardless of the status.
Checking if a file exists before reading it introduces a race where the file can be deleted between the check and the read. It's better to open the file and check any resulting error.
Instead of creating mutable variables (response, status) with defaults, consider only setting them in the appropriate branches. Again, this reduces the number of mutable variables and the scopes of mutability.
Once response and status are moved to a function, you can just return them directly.
read_request does more than just read, so it should be renamed.
The current code doesn't require a TcpStream except in the outermost loop. It only needs anything that implements Read and Write. Using generics will allow you to more easily test those functions in isolation.

use std::io::{self, Read, Write, BufReader, BufRead};
use std::net::TcpListener;
use std::fs::File;

fn main() {
    loop {
        let listener = TcpListener::bind("localhost:8000").unwrap();
        let stream = listener.accept().unwrap().0;
        handle_request(stream);
    }
}

fn handle_request<S>(mut stream: S)
    where S: Read + Write
{
    let requested_page = parse_request(&mut stream);
    let (response, status) = read_file(&requested_page);
    send_response(stream, &response, status);
}

fn parse_request<R>(stream: R) -> String
    where R: Read
{
    let mut line = String::new();

    let mut reader = BufReader::new(stream);
    reader.read_line(&mut line).unwrap();

    let mut words = line.split_whitespace();
    let requested_page = words.nth(1).unwrap();
    let requested_page = requested_page.replace("/", "");

    if requested_page.is_empty() {
        String::from("index.html")
    } else {
        requested_page
    }
}

fn read_file(requested_page: &str) -> (String, u32) {
    match File::open(&requested_page) {
        Ok(mut file) => {
            let mut s = String::new();
            file.read_to_string(&mut s).unwrap();
            (s, 200)
        }
        Err(ref e) if e.kind() == io::ErrorKind::NotFound => (String::from("Not Found!"), 404),
        Err(e) => panic!("Unable to open file: {}", e),
    }
}

fn send_response<W>(mut stream: W, res: &str, status: u32)
    where W: Write
{
    write!(&mut stream, "{}{}{}{}", "HTTP/1.1 ", status, " OK\n\n", res).unwrap();
}

There are way too many uses of unwrap. At the very least, use expect so you have some clue about what caused the program to terminate. Even better, use Result for error handling.

As a basic step, returning a Box<Error> is extremely simple and allows you to consolidate your error handling:

use std::io::{self, Read, Write, BufReader, BufRead};
use std::net::TcpListener;
use std::fs::File;

type Error = Box<std::error::Error>;
type Result<T> = std::result::Result<T, Error>;

fn main() {
    loop {
        if let Err(e) = handle_one("localhost:8000") {
            panic!("An error occurred, I'm exiting! {}", e);
        }
    }
}

fn handle_one(address: &str) -> Result<()> {
    let listener = TcpListener::bind(address)?;
    let stream = listener.accept()?.0;
    handle_request(stream)
}

fn handle_request<S>(mut stream: S) -> Result<()>
    where S: Read + Write
{
    let requested_page = parse_request(&mut stream)?;
    let (response, status) = read_file(&requested_page)?;
    send_response(stream, &response, status)
}

fn parse_request<R>(stream: R) -> Result<String>
    where R: Read,
{
    let mut line = String::new();

    let mut reader = BufReader::new(stream);
    reader.read_line(&mut line)?;

    let mut words = line.split_whitespace();
    let requested_page = words.nth(1).ok_or("request missing path")?;
    let requested_page = requested_page.replace("/", "");

    if requested_page.is_empty() {
        Ok(String::from("index.html"))
    } else {
        Ok(requested_page)
    }
}

fn read_file(requested_page: &str) -> Result<(String, u32)> {
    match File::open(&requested_page) {
        Ok(mut file) => {
            let mut s = String::new();
            file.read_to_string(&mut s)?;
            Ok((s, 200))
        },
        Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
            Ok((String::from("Not Found!"), 404))
        }
        Err(e) => Err(e.into()),
    }
}

fn send_response<W>(mut stream: W, res: &str, status: u32) -> Result<()>
    where W: Write,
{
    write!(&mut stream, "{}{}{}{}", "HTTP/1.1 ", status, " OK\n\n", res)?;
    Ok(())
}


For your controller, a method like this would be best to call all your variables:

$data = array(
    "add_user" => $this->load->view('form_add_user'),
    "username" => $username,
    "admin"    => $admin
);

(Variables are made up just for example)

Then, within your code, do this:

                 Nuevo Usuario

        <?=$add_user;?>


Rather than use the Arduino delay feature, use a watchdog timer to turn the Arduino on/off to take readings.  The TI TPL5010 should serve well. http://www.digikey.com/product-detail/en/texas-instruments/TPL5010DDCT/296-38829-2-ND/5130142


Ask for stream of character input and print number of uppercase/lowercase characters

It looks unusual to have newlines between the function statement and body since they're associated with each other.  This just adds extra lines and makes the code a little harder to read.
If case_letters() is just supposed to print something at the end and not return a value, it should return void (no value), not int.  main() isn't doing anything with this function after calling it.
Unformatted outputs should use puts() instead of printf().
As @Rhs has mentioned, your program doesn't handle special characters.  Based on this from @Loki Astari, there are additional types of characters and with accompanying testing functions.
According to this answer, CTRLD only works on Mac OS and Linux.  For Windows, it's CTRLZ.  All of this should be stated in the output in case the user is running this on Windows.
Consider making this more modular for increased maintainability:

keep letter counters for final output (in main())
collect each character from user
determine if the character is a letter
increment either counter if a letter is entered

Here's what I came up with:

#include <ctype.h>
#include <stdbool.h> // add this library
#include <stdio.h>

bool valid_char(char ch)
{
    if (isdigit(ch)) return false;

    // include additional non-letter checks...

    // if everything checks out:
    return true;
}

void update_counters(char ch, int* numOfUpper, int* numOfLower)
{
    if (isupper(ch))
    {
        (*numOfUpper)++;
    }
    else if (islower(ch))
    {
        (*numOfLower)++;
    }
}

void get_letters(int* numOfUpper, int* numOfLower)
{
    puts("Please enter some characters\n");
    puts("Press CTRL+D on Mac OS/Linux or CTRL+Z on Windows to see the results\n");
    char ch;

    while ((ch = getchar()) != EOF)
    {
        while (!valid_char(ch))
        {
            puts("Character must be a letter\n");
            ch = getchar();
        }

        update_counters(ch, numOfUpper, numOfLower);
    }
}

int main(void)
{
    int numOfUpper = 0;
    int numOfLower = 0;

    int* upperPtr = &numOfUpper;
    int* lowerPtr = &numOfLower;

    get_letters(upperPtr, lowerPtr);

    printf("There are %d uppercase letters and %d lowercase letters\n", numOfUpper, numOfLower);
}


Using bluepy to send and read serial data

Concatenation
In computer science terms, depending on a lot of things, this:
    self.data = self.data + data

can be worst-case O(n^2). This happens when the Python runtime needs to work reallocating everything in the existing buffer before it's able to add new data. One way around this is to use BytesIO instead.
Casting to a list
Based on the documentation:

getServices() / Returns a list of Service objects

Since it's already a list, there is no need to re-cast to a list here:
    self.write_service = self.peripheral.getServiceByUUID(list(services)[s].uuid)

Disconnection safety
Since myHC08 has a disconnect method, it should be made into a context manager, and used in a with statement; or at the least:
bt.connect()
try:
    r = bt.write('1*', 1250*2, '1250H')
finally:
    bt.disconnect()


Few notes about naming conventions (I do not repeat for each method/class but they apply to all of them).

Namespace EntitiesLayer does not help to categorize your code. Namespace are hierarchical and here you're not using them in that way. Obviously it's not mandatory but something like Juan.AwesomeProduct.Data, Juan.AwesomeProduct.Model and Juan.AwesomeProduct.Presentation may help you to organize your code. I am shameless and I admit that at the very beginning (with Managed Extensions for C++, you're lucky if you never had to use it) I used namespaces like you're doing and I still regret.

Classes like ECategoria should not be prefixed with E (or C or anything else.) That's what namespaces are for.

Idcategoria is a public property then it should be PascalCase IdCategoria.

_idcategoria is underscore prefixed but descripcion and categoria are not. Pick a convention (with or without prefix) but be consistent. There are good reasons both to use it or to avoid it, have an informed decision and don't look back.

You're not validating any value in your entities layer. Is acceptable to have null for Descripcion? A negative ID? A blank string?

I see no reason for ECategoria to do not be sealed.

Also take care of indentation.

DCategoria (again, remove that prefix) is an utility class. More often than not you do not need it. Its responsibility may be moved to another class that does something else. It may also be a generic class for many entities. Something like a repository, reconsider that name. Also consider to make it sealed (do you want to extend it through inheritance? Where extension points are?)

Usually underscore is not used to separate words, Act_Categoria() should be PascalCase (it's a public method) then ActCategoria() may be more appropriate. However you're mixing two languages. Use English or your own language but do not mix them in code. If you can you may write everything in English and keep comments in your own language (if you work in an company they should have a procedure for this.)

rpta and ds are declared at the beginning of your method. In C# you can (and you should) declare them as late as possible. Ideally in the same moment you initialize them. Let's see a proof of concept which also includes some others tips:

public string Act_Categoria(ECategoria categoria)
{
    try
    {
        var parameters = new Dictionary<string, object>();
        parameters.Add("@idcategoria", categoria.Idcategoria);
        parameters.Add("@categoria", categoria.Categoria);
        parameters.Add("@descripcion", categoria.Descripcion);
        const string query = "SP_ACTCATEGORIA";
        var ds = dbconnection.execute_query(query, parameters);

        return ds == null ? "Error Insertando" : "REGISTRO REGISTRADO/ACTUALIZADO EXITOSAMENTE";
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

Note that you're catching Exception. It's a very bad thing to do (I won't repeat here the reasons, do a quick search of check any of my previous reviews here.) Catch the exceptions you know may happen and you want to ignore. NullReferenceException is a programming error, not a run-time transitory error condition you may want to swallow.

In your business layer data_categoria may be readonly. In this moment and with this code I do not see any reason to have a BCategoria class. It just forwards calls to DCategoria. Drop one of them until you will actually need it. Business logic should add some value, what's the value of a tunnel? You still expose the same model (ECategoria) and you just forward calls. In a somehow simple scenario you may merge business layer and data layer but when things are more complex the business layer should have its own model (it is the model...) I'd suggest to do not make things complicate if unnecessary, maybe a 2-tiers architecture is what you should start with.

Presentation layer is just a proof of concept however (besides naming convention) it's where you should put more logic. Business layer and Presentation Layer are what will change more often (and probably independently) but here you're directly calling business layer without any abstraction. How do you test your user interface without the attached business layer? What will happen when you need, for example, a IsChanged property in ECategoria? Will you add it in the shared class even if it's used only in presentation? Check MVC, MVP and MVVM to pick the one that best suits your needings (and your UI framework).

Also note that this line:

categoria.Idcategoria = Convert.ToInt32(this.txtcodigo.Text.Trim());

May fail (and trimming is optional here.) User input may be wrong and you must handle that, proof of concept:

int categoryId;
if (Int32.TryParse(this.txtCodigo.Text, out categoryId))
    categoria.CategoryId = categoryId;
else
    ; // Ooops input is not a number (formatted according to current culture)


Graph (adjacency list) for BFS and DFS in Golang

I don't know Go so I'll limit this to a more general review. If I recommend non-standard things, please point them out so someone else doesn't pick up bad habits. :)

Unless the error result is always named ok in Go, I would prefer found in the cases where you are searching for a node by key to clarify its meaning.

A comment in addEdge says missing nodes will be created automatically ("make new node if doesn't have one"), but the code doesn't match. The problem is that there's no payload for the new node(s).

The graph will let you add nodes to which you cannot attach edges. Move the key checking to a new getNode method, and call it from addNode and addEdge.

func (g *Graph) addNode(key int, payload Interface) {
    if node, found := g.getNode(key); !found {
        node = Node{payload: payload, adjNodes: make(map[int]struct{})}
        g.nodes[key] = node
    }
    return node
}

func (g *Graph) getNode(key int) {
    if key < 0 {
        panic("Node key can't be negative")
    }
    if node, found := g.nodes[key]; !found {
        panic("Node key not found")
    }
    return node
}

func (g *Graph) addEdge(src, dst int) {
    if srcNode, found := g.getNode(src); !found {
        panic("No node " + string(src))
    }
    if dstNode, found := g.getNode(dst); !found {
        panic("No node " + string(dst))
    }
    // connect by adjacent list
    srcNode.adjNodes[dst] = struct{}{}
    dstNode.adjNodes[src] = struct{}{}
}

Map vs. List

To your comment, since the caller is free to use sparse keys, e.g., 1, 29187, 23957172, 6832, 4772589, etc., the map (assuming it's a hash map under the hood) will give you \$O(1)\$ access for the most part.

If you were to assign the keys as indices into a list in addNode and return the new key, you could use a list instead. I don't know how Go's internal map and list are implemented, but I assume it must provide some sort of growable array class. If not, they aren't difficult to build.

As a user, I would prefer to have the graph assign the keys for me.


Logic in a card matching game controller

You certainly get points for using IBOutletCollection(UIButton). But, it's unclear why you want to replace this array with a new one? If you're going to do that it should be this view controller that creates the new buttons and adds them as subviews. Also, if you're going to create the buttons in code then I wouldn't expect the first set to be defined in the XIB.

I'm assuming (based on your property definitions) that you're using ARC too.

This section of code can be better by maintaining and incrementing an index instead of interrogating the array you're looping over for the index:

for (UIButton *cardButton in self.cardButtons) {
    Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];

Also, in the updateUI button loop you don't need to set the title multiple times to the same thing and the loop should be completed before you modify the label text.

You want to know about logic, but there is basically no logic in this class. What this class does have is a bit of confusion about whether it owns the buttons and associated cards or if some other class does. The only comments that can be made really relate to efficiency rather than logic.


int vs size_t
Accordingly to the c language specification, it's highly recommendable to use size_t as the type for index variables. So in your case...
int i = 0, k = 0;

should be:
size_t i = 0, k = 0;

if condition repeats while condition
I was a bit confused by this piece of code
while (input[j] != '\0' && input[j] == ' ') {
  if (input[j] == ' ') {
    i++; // keep indexing input-index
  }
  j++; // keep incrementing temporary indexer.
}

Specifically the if condition - it will always be true due to the while condition logic. So, as result, variable j just duplicates i with an invariant j = i+1.

Lack of null character
If you test your code on any string input, you will notice that the program prints some strange characters after your result. It happens because you didn't copy the \0 character to the output array.

Taking all this into an account (as well as @pacmaninbw's and @holroy's recommendations)
#include <stdio.h>
#include <ctype.h>

#define MAX 100

int
main ()
{
  char input [MAX], output[MAX];
  fgets(input, MAX, stdin);
  size_t inputIndex = 0, outputIndex = 0;

  while (input[inputIndex] != '\0')
    {
      output[outputIndex++] = input[inputIndex];
      if (input[inputIndex] == ' ')
        while(input[++inputIndex] == ' ')
          ;
      else
        inputIndex++;
    }
    output[outputIndex] = '\0';
    printf("%s", output);
}


Capturing temperature information for a patient

Technicalities

Your destructor is the same as the default destructor -- I wouldn't bother defining one. It makes me think that the class is going to actually do something in there, so it's strange when it doesn't.

Your header doesn't use iostream, only your implementation does. This means that the #include should be in the cpp file. Try to keep headers as tightly included as possible.

You're not mutating the patient variable so there's no need to make a copy. Instead, you should take it by const reference.

Temperature(const std::string& patient, float temp, char degree);

Instead of assigning your parameters, you should use an initializer list. Assinging means that they might be default constructed first then assigned, and this is unnecessary.

Temperature::Temperature(const std::string& patient, float temp, char degree)
  : patient(patient), temp(temp), degree(degree)
{ }

You did a good job of making your getters const, but getFahrenheit, getCelsius and hasFever should all also be const (they should also be renamed as this implies -- see the Style section).

You shouldn't use using namespace std in header files.

For little toy programs like this, it doesn't matter much, but it can be a good habit to always remember that any kind of IO can fail. In particular, if you want to indulge in some paranoia, you should check that your cin extraction was successful. After all, what if someone puts in a non-sense value when you're expecting a float. You don't particularly want your program to continue after that.

Style

float Temperature::setFaren(){
    float faren = newTemp+32;
    return faren;
}

This isn't setting anything. This is a getter. It should be named getFaren, or even better, getFahrenheit. To get a bit cliche-y for a second, code is read much more than it's written. Strive for clarity even if that means typing a few extra characters.

Also, the variable is a bit superfluous. I'd go with a simple return newTemp + 32;.

#ifndef Temperature_h

Include guards are traditionally SCREAMING_SNAKE_CASE:

#ifndef TEMPERATURE_H

Temperature(string, float, char);

This is confusing as a consumer of the class. You should give these parameters names:

Temperature(string patient, float temperature, char degree);

You have some non-optimal namings. For example, newPatient, newTemp, and newDegree don't really make sense. Why are they new? Just call them patient, temp and degree. If you're worried about them clashing with the local variables in the constructor, you can just use this->patient. I would also consider calling patient patientName since patient makes me expect some kind of model rather than a simple string.

I also am not a fan of the parameter name temp. That makes me assume it's some kind of temporary variable. temperature is clearer.

degree also unfortunately has issues. Fahrenheit and Celsius aren't degrees. They're scales of temperatures. This parameter could instead be named scale.

void Temperature::hasFever(){
    if(newTemp >= 100.4){
        cout << "Patient " << newPatient << " has a fever!!\n";
    }
}

This shouldn't output, but should instead return a bool. The consumer of the class should decide what to do with this information. What if you had a list of Temperatures and you wanted to count how many instances were considered to have a fever. You would likely not want this to output each time a fever was found. Instead, you want the method to return a bool that you can then decide what you want to do with it.

Also, you need to be aware of what scale you're using here. The threshold for a fever in Celsius is much different than the threshold in Fahrenheit.

enum TempMethod {oral, arm, leg, bum};

As this seems to be unused, I would remove it.

If this code were going to live longer than 1 homework assignment or practice, I would expect the class and its methods to be documented.

Design

I would decide on a canonical scale and use that internally. Then, your other scale(s) would simply convert in their getters. For example, you could always store Celsius and just convert to Fahrenheit when needed (this would of course mean that your constructor would need to convert to Celcius when Fahrenheit is provided).

I would consider using an enum for your scale instead of a char. An enum would mean that a user could only provide correct values. It also more explicitly signals what is supported. For example, someone might try to pass in K as your code currently is, then your conversion methods might not support that. Even worse, someone could currently pass in some non-sense like a.

If you do keep it a char, make sure to validate that it's one of the expected values.

It's strange for Temperature to have a patient name. It means that you're not really modeling a temperature; you're modeling a patient/temperature combination. In other words, you've coupled your Temperature object to your patient. What if you wanted to model the temperature of a room? Or of a bucket of water? There's nothing about a temperature that inherently has a patient name.

You should likely have some form of a Patient model that has a temperature (or something even more complex than this in the real world). More pragmatically though, this is a completely reasonable way to do it as long as you're aware that you've made this decision and the program isn't going to grow much. Do keep in mind though that this is a very real tradeoff, and if this program were to ever grow in complexity, you'd likely want to decouple these.


Making a copy constructor more flexible for ADT queue

Remove redundancy

   {
    Node* saveFirst;
    Node* walker;
    first = other.first;
    walker = new Node(first->data);
    saveFirst = walker;
    while (first->next != nullptr)
    {
        walker->next = new Node(first->next->data);
        walker = walker->next;
        first = first->next;
    }
    walker->next = nullptr;
    first = saveFirst;
    }
this->nrOfElements = other.nrOfElements;

You create a temporary variable saveFirst.  You then use a class field as temporary variable.  When done, you set the class field to the value set in the temporary variable.  Why not do it the other way around?

   {
       Node* current = new Node(other.first->data);
       first = current;

       for (Node *otherCurrent = other.first; otherCurrent->next != nullptr; otherCurrent = otherCurrent->next)
       {
           current->next = new Node(otherCurrent->next->data);
           current = current->next;
       }

       current->next = nullptr;
       nrOfElements = other.nrOfElements;
    }

This uses the temporary variable to hold the changing current variable.  It sets first to the correct value immediately and directly.  It changes the loop to say for every node in other.  Now you don't have to set the class field at the end.

Note that I also moved the number of elements assignment inside the else.  In the original it would have tried to dereference a null other.

Reuse other methods

You don't mention other functions in the class, but there are certain ones that could be used here (assuming C++11).

    {
        for (auto i : other)
        {
            this.append(i.data);
        }
    }

This would replace the entire else block.  If you have to create the begin, end, and append functions anyway, then this drops the amount of code that you have to maintain considerably.  Note that begin and end are required to make the range-based for loop work.


I have a confusion about this temps[temps.size()/2] when temps.size() is an odd number. How does the "vector::operator[]" handle floating point numbers?

There are well defined rules to implicit conversions.  temps.size() returns an unsigned integral type that represents the total count of elements in the container.  Dividing an unsigned integral by 2 (a signed integral), the implicit conversion rules for mixed expressions promotes the signed 2 to be unsigned. Division between two unsigned integrals results in an unsigned integral and any remaining fractional part is truncated.  So \$3/2 = 1\$ and the remaining \$.5\$ is truncated and discarded.

    std::vector<double> temps;
    for (double temp; std::cin>>temp; )
        temps.push_back(temp);
    // temps = ???

Be aware of the possible states a type may represent.  What happens if someone runs the program and inputs no data?  Boom.  The mean cannot be calculated because division-by-zero is undefined behavior.  The median cannot be calculated as an empty set is consider an even-sized set.  temps[0-1] accesses results in an out-of-bound access, which is also undefined behavior.  Explicitly assert/validate your pre- and post-conditions.  Do not rely on assumptions.

    for (int x : temps) sum += x;

Use auto to avoid redundant repetition of type names.  temps represents a container of doubles.  You define x to be of type int, which results in a narrowing conversion that's likely to be a source of a bug (Test! Test! Test!).  The compiler already knows what type x should be.  Use auto and let the compiler do its job.

Don't state in comments what can be clearly stated through code.  When programming, the code states what is being done.  If you need to provide/document any reasoning regarding your intent, use comments then.

Write functions. Lots of functions.  You've already split your program into single logical operations via comments.  Break up that monolithic main into parameterized functions.

int main() {
    auto temperatures = read_temperatures(std::cin);
    const auto mean_temperature = mean(temperatures);
    const auto median_temperature = median(temperatures);

    report(std::cout, mean_temperature, median_temperature);
}

Now you can write the short and simple functions that are easy to read, test, and maintain.

Get familiar with the standard algorithms found in <algorithm> and <numeric>.  Do you really need to sort the entire data set?  Would partial sorting (std::nth_element) suffice?  For even-sized data sets, you could pair up std::nth_element with std::min_element to find the two values. As Vnp mentioned, std::accumulate is a candidate for summing up a range.

Use strongly defined types to represent your temperatures.  A raw double representing temperatures is not safe.  Numeric types that are conceptually incompatible may cause catastrophic mathematical errors.  The Mars Climate Orbiter failure is a famous catastrophe caused by taking an impulse result from the US system and using that result in SI calculations without any conversions.  So if you want to store temperatures, are you representing Celsius, Fahrenheit, Kelvin, or Rankine?  Note - You'll need an understanding of programming with objects to accomplish this.  If you haven't learned about objects yet, keep it in mind for when you do encounter them.


Determine dependency injection type at runtime from config

Since the value that determines what type to use doesn't change I personally would prefer your first solution of a switch statement in the registration.
The current implementation of the factory pattern would lose any type safety.  If a parameter gets added to the constructor then then the Activator.CreateInstance would fail.  For example the database one might take in a connection string or sql object while the default one wouldn't.  Plus a naming convention would need to be understood and knowledge passed down in maintenance mode.  As the saying goes juice not worth the squeeze.
If the value to return could change based on a parameter being passed in then I would agree factory pattern could be used but as it stands I think the switch statement in the container registration is the simplest and meets the requirement.
There is still ways to create the factory pattern that would give type safety and DI but it ends up looking a lot like the switch statement.


SICP - exercise 2.27 - reversing elements of a list and sublists

If you actually indented it that way please use an editor that does
automatically - usually the individual cases of the cond should align,
e.g. like so:

(define (deep-deep-reverse lst)
  (cond
   ((null? lst) '())
   ((list? lst) (append (deep-deep-reverse (cdr lst))
                        (list (deep-deep-reverse (car lst)))))
   (else lst)))

The function looks good.  For clarity it might make sense to move the
middle case to the end, but it's not like that changes much.

However consider that append used in this way is quite expensive
because it repeatedly recreates a "long" list (from the cdr recursion)
to stick the "short" list (from the car part) at the end.

(As an exercise for the reader) you can use an accumulator instead to
avoid append completely (instead cons is enough).  The function
would look pretty similar:

(define (deep-deep-reverse2 lst)
  (define (aux lst acc)
    ...)
  (aux lst '()))


Your enumerate2 is a nice touch but I am not quite convinced that this is necessary : if you are to play with the length manually, you might as well compute the power from the index manually.

Also, if you were to handle the negative with a minus instead of the plus, you'd be able to get rid of the brackets. On the other hand, you cannot use join anymore which is a bit of a pain because it is a cool and efficient function.

Anyway, here's my try :

def poly(p, var_string='x'):
    res = ''
    first_pow = len(p) - 1
    for i, coef in enumerate(p):
        power = first_pow - i

        if coef:
            if coef < 0:
                sign, coef = (' - ' if res else '- '), -coef
            elif coef > 0: # must be true
                sign = (' + ' if res else '')

            str_coef = '' if coef == 1 and power != 0 else str(coef)

            if power == 0:
                str_power = ''
            elif power == 1:
                str_power = var_string
            else:
                str_power = var_string + '^' + str(power)

            res += sign + str_coef + str_power
    return res

and the corresponding output :

2x^8 + 3x^6 - 4x^5 - 3x^4 + 2x^3 + x + 10

Bug found

As I was looking at my original implementation, I found a bug which happens to be in yours too : try with [1,1,1,1,1].


TSQL query to gather amounts for an employees, spouses, and children in one row

You can use T-SQL's operator PIVOT to do this.

SELECT EmpID, Name, [EE], [Spouse], [Child]
FROM
(
    SELECT EmpID, Name, Relationship, CAST(Amount AS INT) AS AmountINT
    FROM Source
) AS SourceTable
PIVOT
(
    MAX(AmountINT)
    --
    -- Define your target relationships here
    -- EE, Spouse, Child ...
    -- These relationships should be exactly the same as described in
    -- the SELECT statement
    --
    FOR Relationship IN ([EE], [Spouse], [Child])
) AS PivotTable;

Result

EmpID   Name    EE      Spouse  Child
1       James   2000    5000    10000
2       Mary    2000    NULL    NULL
3       Pete    2000    NULL    10000

You need to cast your Amount into numeric type before doing so.


Your code looks pretty decent. My two cents:

Implement Default

impl Default for Fifo {
    fn default() -> Fifo {
        Fifo {
            size: 0,
            read_idx: 0,
            write_idx: 0,
            buffer: [0; FIFO_CAPACITY],
        }
    }
}

Then you could simplify your new to:

pub fn new() -> Fifo {
    Fifo::default()
}

Simplify expressions

L27: self.size = self.size + 1 will become self.size += 1
L40: self.size = self.size - 1 will become self.size -= 1
Replace str error with enums

pub enum FifoError {
    FifoFull,
}

pub fn push(&mut self, item: u8) -> Result<(), FifoError> {
    if self.buffer_full() {
       Err(FifoError::FifoFull)
    } else {
        ...
}

Add assert_eq!(None, buffer.pop()); to the end of every test where feasible, e,g.

pop_item_that_was_pushed_to_buffer
popping_returns_first_pushed_first
pop_beyond_write_index_continuing_on_works
buffer_wraps_around

For further exercices I would recommend:

Implement Iterator/IntoIterator/FromIterator
Next, implement Debug, which is fairly easy (Hint: Take a look at the implementation of Debug for slice)
Make it accept a generic type


Given an ASCII string, replace all ASCII chars with their Cyrillic equivalents

Why a recursive function for such a simple task?

$in = 'This is your input';
$map = 'your char translation array here';
$out = '';
for($i = 0; $i < strlen($in); $i++) {
   $char = $in[$i];
   if (isset($map[$char])) {
       if (is_array($map[$char])) {
           $newchar = $map[$char][0]; // whatever your multi-char selection logic is...
       } else
           $newchar = $map[$char];
       }
       $out .= $newchar;
   }
}


Elegant way of making a List of an attribute from a list of objects containing that attribute

When I have encountered this type of problem, it typically involves creating some ugly code in your method to do that iteration. In essense, there is no way to do things any differently, you have to iterate, and collect the UUID's (but, you could wait for Java8 and do lambdas ..).

But, there is no reason why you have to do it outside of the Something class. A trick you can do which keeps like-code together, is to put a static method on Something, which does:

public static final List<UUID> getUUIDs(Iterable<Something> somethings) {
    List<UUID> ids = new ArrayList<UUID>();
    for(Something thing : somethings) {
        ids.add(thing.getId());
    }
    return ids;
}

Now that code is stashed away somewhere useful, and when you need it you can:

for (UUID uuid : Something.getUUIDs(things) {
    ... do something ....
}


Computing logits for a vector and for all vectors in a set

Why do you want to combine them into two functions? It’s possible, but I don’t think it would be an improvement. They’re two fairly distinct functions, and cramming the code for both into a single function would make the code less readable.

If you really need a single function that handles both, you could do something like:

def softmax(a):
    if isinstance(a, vector):
        return softmax_a_vector(a)
    elif isinstance(a, set):
        return softmax_a_set(a)

which gets what you want, but you keep the nice separation of code into distinct functions.

One other minor thing: you can improve the for loop in softmax_a_set with enumerate:

for idx, a_vector in enumerate(a_set):
    softmax_set[idx] = softmax(a_vector)


The code:

def nice_numbers
  ([rand(9),rand(9)]*2).join
end

generates the same output as your function. It is also faster, as it does not test then regenerate anything.

If you want to DRY this up for rand(9):

def nice_numbers
  (Array.new(2) {rand(9)} * 2).join
end

Ruby language features used in this last example:

Array constructor takes a size param and a block to fill the Array
Multiplying an array by an integer repeats the array


You should not need to populate the ClientTypes property with your own query. Usually it is handled by a navigation property that already knows how to handle related tables but for this to work you first need to set the foreign key properly. Since you did not post the models I cannot say if it would be possible in your case.

You can read this article explaining how it should work: Don’t use Linq’s Join. Navigate!

Then you should be able to load the relations with Include:

var x =
    from c in _context.Cases.Include("ClientTypes")
    where c.ClientID == code
    select c;

See also Loading Related Objects


Schema.org structure for a news aggregator individual post

HTML5+Microdata

In case of meta/link:

If the value is a URI, you have to use link instead of meta.

So this

<meta itemprop="isBasedOnUrl" content="http://eluniverso.com/2015/03/01/noticia3.html" />

should be

<link itemprop="isBasedOnUrl" href="http://eluniverso.com/2015/03/01/noticia3.html" />

and this

<meta itemprop="logo" content="/logos/eluniverso.png" />

should be

<link itemprop="logo" href="/logos/eluniverso.png" />

Your thumbnail img is missing the required alt attribute.

Schema.org

In addition to (or instead of) headline it can be beneficial to provide name. The headline property can only be used for CreativeWork (and sub-types), while the name property is defined for every type. It’s likely that many consumers look for and make use of name but not headline.

You could provide both properties, separated with a space, on the same element, i.e.,

If the link in Organization is about this organization, you might want to use the url property.
The WebPage could reference the NewsArticle via the mainEntity property (if the page is only about a single news article; otherwise the NewsArticle could reference its WebPage with the reverse mainEntityOfPage property).

While you could use Microdata’s itemref attribute to reference it without changing the markup structure, it’s not necessary if markup changes are possible. You could specify WebPage on a container div (or the body, if it’s the only/current web page), e.g.:

Related News 1

Related News 2

Related News 3


Function that inserts values for an array of fields into a database table

There's a couple of issues with it, for start your nested if blocks are unnecessary: instead of manually checking and returning true or false, just return the result of those methods, like so:

return $this->_pdo->prepare($sql) and $this->_pdo->exec($sql);

Additionally, you have made $fields and $values into optional parameters by making them auto-initialise to empty arrays, however you cannot have an INSERT INTO statement without specifying at least one field and value, therefore instead of making them optional array parameters, you should use type hinting to ensure they are arrays, and then check to make sure that the arguments are correct before you send the query off to the server, something like this:

public function insert($table, array $fields, array $values) {

    $numFields = count($fields);
    $numValues = count($values);

    if($numFields === 0 or $numValues === 0)
        throw new Exception("At least one field and value is required.");
    if($numFields !== $numValues)
        throw new Exception("Mismatched number of field and value arguments.");

    $fields = '`' . implode('`,`', $fields) . '`';
    $values = "'" . implode("','", $values) . "'";
    $sql = "INSERT INTO {$table} ($fields) VALUES($values)";

    return $this->_pdo->prepare($sql) and $this->_pdo->exec($sql);
}


Matching two lists of dicts, strictly and more loosely

Exceptions can be faster and slower than using dict.get.

If you don't care about performance then you pick whichever you prefer.
However, if you do care you have to take into account three timings;
using get, without an exception, and with an exception.
Using get is slower than try without an exception, by about 37.8%.
But try with an exception is slower than get, by about 35.7%.

So, you should pick the method on whether there will be a sizeable amount of exceptions, or not.
In this case, as you expect upto four times, you should use dict.get.

Here are my timings in Python 3.6.0:

>>> from timeit import timeit
>>> timeit('''\
try:
    v = d['key']
except KeyError:
    pass
else:
    pass
''', 'd = {}')
0.25764639688429725
>>> timeit('''\
try:
    v = d['key']
except KeyError:
    pass
else:
    pass
''', 'd = {"key": "here"}')
0.034827991199023245
>>> timeit('''\
v = d.get('key')
if v is not None:
    pass
''', 'd = {}')
0.0920266698828982

Change match to return, rather than being in the if.
Move match into fetch. It makes the code easier to read.
Changing your nested trys to a function that yields the possible symbols, makes the code more DRY, and easier to read.
Move adddict into lookup.
Possibly remove the comments.

This makes swapping between try and dict.get simpler if one is faster than the other.
And also makes the code a little more dense, whilst still being readable.
Personally, I find the code being a bit more dense makes your code more readable.
But it's not much of a change from your current code.

This can change your code to:

# lookup helpers
def fetch(name, symbols, key):
    ''' find name by dict[key] in list of dicts symbols  '''
    return next((
            item
            for item in symbols
            if name.strip('.') in item[key]
            or name.split()[0] in item[key]
        ), None)

def methods(entry, symbols):
    yield next((item for item in symbols if entry['stock'] == item['name']), None)
    yield fetch(entry['stock'], symbols, 'name')
    yield fetch(entry['stock'].upper(), symbols, 'symbol')
    yield fetch(entry['stock'], SPECIALS, 'name')

def lookup(stox, symbols):
    '''lookup symbol for stock name'''
    hits = []
    misses = []
    for entry in stox:
        for symbol in methods(entry, symbols):
            try:
                hits.append({'source': entry['stock'],
                             'found' : symbol['name'],
                             'symbol': symbol['symbol']})
                break
            except TypeError:
                continue
        else:
            misses.append(entry['stock'])

However I don't think this should be done in Python.
It looks like your extracting data from your database and filtering it in Python, rather than performing both in SQL.
And from my limited knowable of SQL this would be much easier written SQL. Assuming SQL has an equivalent of in.

But if you want to keep with Python, to change your code to use equality, rather than in.
This is as it can change your code to have linear time, rather than quadratic.
If I were to do this I'd change your code to something like:

def methods(stox, symbols):
    methods = [
        {i['name']: i for i in symbols},
        {i['symbol']: i for i in symbols},
        {i['name']: i for i in SPECIALS}
    ]
    def inner(stock):
        strip = stock.strip('.')
        split = stock.split()[0]
        yield methods[0].get(stock)
        yield methods[0].get(strip)
        yield methods[0].get(split)
        yield methods[1].get(strip.upper())
        yield methods[1].get(split.upper())
        yield methods[2].get(strip)
        yield methods[2].get(split)
    return inner

def lookup(stox, symbols):
    meth = methods(stox, symbols)
    hits = []
    misses = []
    for entry in stox:
        for symbol in meth(entry['stock']):
            if symbol is not None:
                hits.append({'source': entry['stock'],
                             'found' : symbol['name'],
                             'symbol': symbol['symbol']})
                break
        else:
            misses.append(entry['stock'])


Several aspects of your code could use improvement:

It would be nice if the code were packaged in a function.
Date.new(Integer(dates.first[0..3]), Integer(dates.first[4..5]), Integer(dates.first[6..7])) is rather verbose and ugly.

I recommend DateTime.strptime for date parsing — it's the inverse of strftime.
You can call Range#map directly; you don't need to do to_a first.
dates.map { |d| range.index(d) } could be problematic for performance, since it is O(n2).

Instead, you should make a Hash.

Here is one solution:

require 'date_core'

DATE_FMT = '%Y%m%d'

def filled_date_series(dates, values, default_value=0)
  data = Hash[dates.zip(values)]
  datetime_range = (DateTime.strptime(dates.first, DATE_FMT) ..
                    DateTime.strptime(dates.last,  DATE_FMT))
  date_range = datetime_range.map { |dt| dt.strftime(DATE_FMT) }
  [
    date_range,
    date_range.map { |d| data[d] || default_value }
  ]
end

dates = ["20161010", "20161013"]
values = [5, 3]
range, filled_values = filled_date_series(dates, values)


In all, this looks pretty solid to me, so I have only a few suggestions:

Eliminate spurious inline

The inline keyword is only useful if this is moved to a header file, so it's not strictly needed in the context of the code in the question.

Consider defining a string literal

Here's a small enhancement: provide the ability to define a string literal.  Here's how it might be done:

constexpr uint32_t operator"" _be32(unsigned long long num) {
    return htobe32(num);
}

Usage:

printf("%16x %16x\n",   0x11223344,     0x11223344_be32     );

This makes things very tidy and easy to use.  Naturally, 16- and 64-bit versions are almost identical except for return type and name.


C function to move and collapse cells in 2048 game

Don't repeat yourself

The two loops can be joined pretty easily. We basically just need to factor out the (few) pieces that are different between the two, and pull those pieces out of the loop. The loops are just short enough, however, that the result may not be a whole lot shorter than the two loops are right now (so if you care more about short code than lack of repetition, you may not want to do this).

Comments

Right now, you've provided comments for what the loop does in one of the loops, but not the other. By collapsing the loops together, we can eliminate this inconsistency. That leaves the question of whether to include the comments or not. In general, I'd rather write the code to be self-documenting instead. See below for at least some of how to do that.

Symbolic names

Instead of writing the code to explicitly state the an empty cell contains the value 0, I'd prefer to give that a name:

#define EMPTY 0

// ...

if (_vector[i] == EMPTY)
   // ...

This (probably) eliminates any requirement for a comment to tell us that we're checking whether that cell is empty.

Unnecessary Indirection

It appears that you can pass _score as a pointer to int rather than a pointer to pointer to int as you're doing now. At least as far as I can see, the extra level of indirection isn't accomplishing anything useful at all.

Bool Parameters

I generally discourage using bools as function parameters. I'd rather use an enumeration that directly states what you want to express:

enum { UP, DOWN };

collapseVector(..., UP);

...seems much more meaningful than:

collapsVector(..., true);

Final Code

One possibility would be something on this general order:

#define EMPTY 0

bool down(int a, int b) {
    return a < b;
}

bool up(int a, int b) {
    return b < a;
}

enum direction { UP, DOWN };

/**
* collapseVector: Collapse a vector "2048" style, flush the cells in one direction, joining them if legal.
* @param _vector 1-D array to be collapsed
* @param _score Score counter
* @param invert Whether or not to inverse-flush vector. Useful for Up(false) vs. Down(true), and so on
*/
void collapseVector(int _vector[MAX_BOARD_POS], int *_score, direction dir) {
    int idx = 0;
    int buf[MAX_BOARD_POS] = { 0 };
    int start = 0;
    int end = MAX_BOARD_POS;
    int inc = 1;
    bool (* cmp)(int, int) = down;

    if (dir == UP) {
        idx = start = MAX_BOARD_POS - 1;
        end = 0; // Not sure if this is quite right, but I think it's at least close
        inc = -1;
        cmp = up;
    }

    for (int i = start; cmp(i, end); i += inc) {
            if (_vector[i] == EMPTY) {
                continue;
            }
            if (buf[idx] == EMPTY) {
                buf[idx] = _vector[i];
            }
            else if (_vector[i] == buf[idx]) {
                ++buf[idx];
                *_score += 1 << buf[idx];
            }
            else {
                buf[idx += inc] = _vector[i];
            }
        }
    }
    memcpy(_vector, buf, MAX_BOARD_POS * sizeof(*_vector));
}


Thread Safe Objects in CSharp - ConcurrentDictionary

I'm reading files from the local system in parallel, to speed up the process.

Are you sure it's actually beneficial? Hard disks work best when you read them in sequence, not when they have to go back and forth to satisfy concurrent requests. (And even if you have a SSD, you're not going to gain anything.)

You seem to be in the habit of using framework names for types (e.g. Byte, Int64) instead of the C# names (byte, long). I believe that using the C# names is more common.

Byte[] CompleteLetterContent;
CompleteLetterContent = ConvertToPdfWithAspose(System.IO.File.ReadAllBytes(file), letterId);

There is no reason to separate the declaration and assignment here. Also, local variables are generally written in camelCase:

Byte[] completeLetterContent = ConvertToPdfWithAspose(System.IO.File.ReadAllBytes(file), letterId);

System.IO.File.ReadAllBytes(file)

You're already using System.IO, so the namespace should be redundant here. And if it isn't because you have something else called File, then you should probably fix that conflict.

concurrentDictionary.GetOrAdd(letterId, CompleteLetterContent);

You're calling GetOrAdd(), but you always only want to add, you never want to get. For that, you can either use TryAdd() or the indexer setter:

concurrentDictionary.TryAdd(letterId, CompleteLetterContent);
concurrentDictionary[letterId] = CompleteLetterContent;

In all three cases, the behavior is the same if there are no values with the same key, but I think the latter two are clearer.

      Byte[] LetterContent;
      Byte[] CompleteLetter;

These variables are never used, get rid of them.

Letter letter = new Letter();
letter.LetterId = letterId;

You can use var (since the type is clear from the assignment) and object initializer here:

var letter = new Letter { LetterId = letterId };

if(file.Contains("CL"))
{
    letter.CompleteLetter = ConvertToPdfWithAspose(System.IO.File.ReadAllBytes(file), letterId);
}
else
{
    letter.LetterContent = ConvertToHTML(System.IO.File.ReadAllBytes(file), letterId);
}

In both branches, you're repeating the System.IO.File.ReadAllBytes(file) part. Consider extracting it into a local variable before the condition.

The code you have shown appears to be thread-safe, assuming that the methods that you're calling from it (ConvertToPdfWithAspose, ConvertToHTML) are thread-safe.


increase efficiency of loops and element-wise operations in PyTorch implementation

A few hints for improving efficiency:

When W[i, j] == 0, B equals to W so tmp remains unchanged. In this case, the computation of C values can be done only once outside the loop instead of inside the loop.

torch.nonzero / torch.Tensor.nonzero can be used to obtain all indices of non-zero values in a tensor.

Since W is symmetric, C is also symmetric and only half of its values need to be computed.

All repeated computation can be moved out of the loop to improve effciency.

Improved code:
n = len(W)
nIW = n * torch.eye(n) - W
nIB = nIW.clone()
C = nIB.inverse()

for i, j in W.nonzero():
    if i < j:
        nIB[i, j] = nIB[j, i] = 0
        C[j, i] = C[i, j] = nIB.inverse()[i, j]
        nIB[i, j] = nIB[j, i] = nIW[i, j]

Further performance improvement may be achieved according to this.
As for backpropagation, I have no idea how it can be done on elements of matrix inverses.


Exposing a directive's computed variable

Given your code, it only filters the list and assigns the value on initialization. From the outside world, the count appears like a read-only value. This is ok... sort of.

One problem I see is that the count can be bound somewhere else and potentially manipulated. This potentially makes the count out of sync with the list count. Your list could say one thing, the count another. I don't know of any way to make it read-only. You could provide a function into the directive, sort of an onchange, where it gets called on modification in the directive and passes in the value there. This would mean that the controller holds responsibility of caching that value in a property. Just make sure that property also doesn't get manipulated though.

Another way you could improve this and avoid the 2-way binding "hack" is to move out the filtering to the enclosing controller. That way, the controller knows about the filtered list and it's length. All you have to do then is to provide that filtered list into your directive, since all it does is just render that list.

An even better way (I guess) is to move out the list and logic into a service/factory. That way, your "single source of truth" is a service, and not the controller nor directive. All you have to do then is pull in the data (full list and a filtered list) from the service/factory into the controller (controller will know about both), and pass in the filtered list to the directive. Any operations that manipulate the data lives in the service/factory, and done via function calls to it. It's essentially what React does with it's Flux architecture, isolating state and state changes into one location to prevent confusion caused by binding and multiple actors.