Review
Not bad, but there is room for a few improvements to avoid some possible problematic input arguments.
Style
Some points on your code.

The names nums and k could be better, maybe array and rotateBy
Try to avoid one use variables unless it makes the lines using them to long. Thus you can pop and unshift in one line nums.unshift(nums.pop());
Idiomatic javascript uses zero based loop counters rather than starting at 1. Thus the loop would be for (let i = 0; i < k; i++) {

Complexity
Your complexity is \$O(n)\$ and storage \$O(1)\$ where \$n\$ is the number of rotations, the range \$n>0\$
However consider the next examples
rotate([1,2,3,4,5,6,7,8,9], 18); // Will rotate 18 times same as rotate 0
rotate([1,2,3,4,5,6,7,8,9], 8); // Will rotate 8 times same as rotate left 1
rotate([1], 8e9); // Will spend a lot of time not changing anything

Your function will do too much work if the rotations are outside the expected ranges, the rotation can be done in reverse in less steps, or rotating has no effect.
You can limit the complexity to \$O(k)\$ where \$0<k<=n/2\$
Rewrite
This is a slight improvement on your function to ensure you don't rotate more than needed.
function rotate(array, rotateBy) {
    rotateBy %= array.length;
    if (rotateBy < array.length - rotateBy) {
        while (rotateBy--) { array.unshift(array.pop()) }
    } else {
        rotateBy = array.length - rotateBy;
        while (rotateBy--) { array.push(array.shift()) }
    }
    return array;
}

Update
As vnp's answer points out the complexity of Array.unshift and Array.shift is not as simple as \$O(1)\$ and will depend on the array type. We can assume the best case for this problem, sparse array (effectively a hash table) and thus will grow/shrink down at \$O(1)\$
In that case the function above has a mean complexity of \$O(log(n))\$ of all possible values of \$k\$
Note that if the cost of grow/shrink operations is \$O(n)\$ (dense array) this will add \$n\$ operations for each \$k\$ making the above \$O(kn)\$ with \$0<=k<(n/2)\$ Expressed in terms of \$n\$ or \$k\$ only it remains \$O(log(n))\$  or \$O(k)\$

You could also use Array.splice
 array.unshift(...array.splice(-rotateBy,rotateBy));

However under the hood the complexity would be a little greater \$O(2n)\$ (which is still \$O(n)\$) as splice steps over each item to remove and add to a new array. Then ... steps over them again to unshift each item to the array.
The storage would also increase as the spliced array is held in memory until the code has finished unshifting them making storage \$O(n)\$
If the array contained all the same values the rotation would have no effect thus all rotation could be done in O(1). However there is no way to know this without checking each item in turn.


Updating an inventory with R using apply functions

You can indeed use vectorization. Create two vectors of indices (or booleans like I did) to identify the rows of the master that need to be updated. To find the corresponding row from the new, you can use the match function like I did.

## Update inventory
if (all(new$book %in% master$book)) {
   idx.map       <- match(master$book, new$book)
   is.match      <- master$book %in% new$book
   checking.out  <- is.match & master$status == "IN"
   checking.in   <- is.match & master$status == "OUT"
   master$status[checking.out]  <- "OUT"
   master$status[checking.in ]  <- "IN"
   master$student[checking.out] <- as.character(new$student[idx.map[checking.out]])
   master$student[checking.in ] <- NA
   master$date[checking.out]    <- as.character(new$date[idx.map[checking.out]])
   master$date[checking.in ]    <- NA
} else {
   stop("At least one book not found in database")
}

You will notice another improvement: everywhere I am referring to columns using their name, for example, master$student instead of their index like master[..., 3]. It makes the code more readable and easier to maintain (Imagine what would happen if suddenly a column was inserted at the beginning of master: you would have to modify all your indices...)


Multi-threading with TPL - Access Internal Class Properties

Values of the Base class should have protected set;.

In Mesh there is inconsistency with properties. Most are not readonly while some are.

Depending of whether or not those properties should be readonly you may remove Values initialization as well as xn and yn computation from Compute.

Furthermore, regardless of previous points, depending on whether or not Compute is called a lot in your application you might want to have a run context with array as a field so that a closure is not created.
And then you can even turn lambda in Parallel.For into a method pointer to a private method.
What this will allow you to do is allocate memory for 2 less object in Compute, which again based on frequency of usage can give you a performance boost.

Why? Firstly, allocation of memory is a slow operation. Secondly, garbage collection freezes all threads while is works. So less objects to collect - better.


Comments

Inline commend are usually no JavaDoc comment (/* vs /**).
Please check your comments, if they add any new information, that is not covered by the method or variables names, e.g:

    /**
     * If the payer is beneficiary remove the payer from the list of
     * beneficiaries
     */

    if (IfPayerIsBenificiary) {

        consolidatedBenificiary.remove(payer);
    }

could be a oneliner to improve (opinion!) readability:

  if (ifPayerIsBenificiary) consolidatedBenificiary.remove(payer);

As mentioned by the other reviewers, and I can only stress this point: comments are not used to explain what you are doing but why.

Variables/Method

Variables starts lower case in java.

In java it is not that common to define/initialize variables at the beginning of the method. Just do it when you need them. (e.g amountToBePaid)

Naming a method getPayDetails and return void is confusing. Just call it print...

Generics

List<String> benificiaryList = new ArrayList<String>();

Since Java 7 you can omit the second <String> and use the diamond operator <>

Simplification

checkIfPayerIsBenificiary could be written as:

public boolean checkIfPayerIsBenificiary(String payer, List<String> beneficiary)
{
    return beneficiary.contains(payer);
}

If this don't need to be public, just inline the one usage. Your variables is telling everything IfPayerIsBenificiary in that place.

Unused code

setPayableOrToBePayed and outputMap are not used. If there is no code missing in your question, just delete it.

consolidatedBenificiary is redundant and can be inlined.

(to be continued after you completed your code)


As a rule I don't like to trigger exceptions, even controlled ones. One reason is that they are more expensive to handle, and as the name implies they should remain exceptions.

So rather than doing this:

try:
        bond = open('/proc/net/bonding/%s' % iface).read()
except IOError:
        print "ERROR: Invalid interface %s\n" % iface
        usage()

I would have something like this:

import sys, os

iface = 'bond0'
bond = ('/proc/net/bonding/%s' % iface)

if not os.path.exists(bond):
    print "ERROR: Invalid interface %s\n" % iface
    sys.exit(1)

# continue

NB: seeing that you are using Python 2.x I have tried to provide compatible code.

Rather than blindly trying to read a file that may not be there in the first place, I simply use os.path to ascertain its existence (could use the isfile function as well).

I also return an exit code, which could be useful if you will be calling this script from another bash script, then you might like to know if the output was as expected or if there is a possible error like a broken network link. Rather than just return 0 (success) or 1 (failure) you could adjust the value depending on the kind of error encountered. Then it's useful to have the special codes in mind.

I see that you are already using sys.exit(1) in your code, which is excellent, but it is in the usage function, where it's the least useful. Consider returning an exit code in the other parts of the code including exceptions. One way of doing it would be to have a main try catch block with a finally so that an exit code is always returned, which could be 0 by default.

You can still have exception handling in this block though, because you might run into some permission issue, depending on the user and perhaps the OS. It's just that I would avoid raising exceptions for situations that are easily anticipated and tested.

Consider logging exceptions and even console output or debugging information. A recent discussion on the topic: Custom exception handling function or logging library?

This is especially important for unattended scripts. In this case, it's probably less important if the script will always be run interactively. But it's good to have a trace on file when you are working in some tiny SSH or screen terminal session with a small buffer size and difficulty scrolling text.

Regarding semi-constant variables like /proc/net/bonding/ or bond0 I try to regroup them together on top of the script. The paths and interface names may vary from an OS to another and porting code to another platform is easier when essential variable names are not scattered all over the place. Obviously, they should be defined only once and repetition is to be avoided absolutely. I develop scripts for servers that run on at least 3 different flavors of Linux and I sometimes have surprises...

Regarding the code proper: the final line doing the print is quite hard to read. All that splitting is unnecessary and even unsafe. If the output of /proc/net/bonding/bond0 changes, or the number of slaves is less than 2, your code could fail.

Ideally, you should have ready-to-use variables and just print them. All the processing, parsing, validation etc has to take place before.

Let's take this snippet as an example:

    m = re.match('^Slave Interface: (.*)', line)
    if m:
            s = m.groups()[0]
            slaves += ', %s' % s

Your code iterates twice. At the first iteration the value of slaves is: , ens3f0. At the second iteration it is: , ens3f0 up, ens3f1. Note the leading comma.
It seems that you are not yet familiar with Python structures such as lists or dictionaries, so you are resorting to string manipulations techniques that are superfluous.
Here how I would do it, using a simple list:

First add this somewhere in your code, for example before the for loop:

slave_interfaces = []

We simply define an empty list. Then your code becomes:

    m = re.match('^Slave Interface: (.*)', line)
    if m:
            slave_interfaces.append(m.group(1).strip())

When a match if found, the value is appended to the list, which means adding an element. Note the addition of strip() to trim whitespace that may surround the interface name.

The regular expression can not only match but capture as well. Since m.group(1) already contains the name of the interface you can use it. Now, at the first iteration the value of slave_interfaces is: ['ens3f0']. At the second iteration it is: ['ens3f0', 'ens3f1']. You have a list of two elements, and you can address each of them by index number, thus slave_interfaces[0] = 'ens3f0' and slave_interfaces[1] = 'ens3f1'. You can check the number of elements: len(slave_interfaces) will return 2. So you know in advance that using an index number greater then 1 will result in an error (IndexError: list index out of range).

Producing a comma-separated list is as easy as joining:

','.join(slave_interfaces)

=> 'ens3f0,ens3f1'

On a final note, for parsing arguments and if you have Python 2.7 at least, the argparse library provides more flexibility. Have a look at the add_help function too. When you develop more sophisticated scripts with multiple arguments that may be in no particular order, your way of doing it will not scale well.


Your loop has a potential complexity of R * M (R number of words in ransom, M number of words in magazine). Additionally you use remove in the inner loop which which does linear search in magazine.

The solution is to count occurences of words in both, magazine and ransom. this is done in a single sweep and of linear complexity R + M (dict get/set is average linear).

the moste dense and readable solution is

from collections import Counter

def ransom_note(magazine, ransom):
    ran = Counter(ransom)
    mag = Counter(magazine)
    return len(ran - mag) == 0

if you assume a very long magazine and a short ransom message you could go for an early break by counting the ransom first, then do a down count with magazine words. magazine could be a generator in that case reading from an arbitrary large file.

from collections import Counter

def ransom_note(magazine, ransom):
    ran = Counter(ransom)
    if not ran:
        return True # handle edge case
    for m in magazine:
        if m in ran:
            # we need this word
            if ran[m] > 1:
                ran[m] -= 1
                # still need more of that one
            else:
                # the last usage of this word
                ran.pop(m)
                if len(ran) == 0:
                    # we found the last word of our ransom
                    return True
    return False


Define the problem

It's not clear from the description what's considered "excessive" whitespace.  From experimenting, it seems that the idea is to collapse multiple whitespace to a single whitespace character, except at the end of the string, where whitespace is to be completely removed.  (Whitespace at the beginning of string seems to treated the same as inner whitespace).  It's also not clear which whitespace character should be kept - the example code keeps the last one, but is that a requirement, or just an implementation choice?

Missing include

std::begin() and std::end() are declared in <iterator>.  However, there's no reason not to use the begin() and end() member functions of std::string here, as we're not operating on generic values.

When an argument is to be copied, pass by value

We don't need to copy str into result:

std::string remove_excessive_ws(std::string str)

Bug

Like all the <cctype> functions, std::isspace() requires that its argument be either EOF or representable as unsigned char.  Converting a (possibly signed) char direct to unsigned int can sign-extend to an out-of-range value.  We need to convert char to unsigned char before widening to unsigned int:

static_cast<unsigned char>(ch)

Bug

Prior to C++11, accessing the character after the end of the string is undefined behaviour (C++11 requires an extra null to follow the string data).  Thankfully, it's easy to avoid this bug by simply remembering whether the last character seen was a space.

Here's a C++11 version:

#include <algorithm>
#include <cctype>
#include <string>
#include <utility>

std::string remove_excessive_ws(std::string str)
{
    bool seen_space = false;
    auto end{ std::remove_if(str.begin(), str.end(),
                             [&seen_space](unsigned char ch) {
                                 bool is_space = std::isspace(ch);
                                 std::swap(seen_space, is_space);
                                 return seen_space && is_space;
                             })};
    // adjust end to remove end whitespace
    if (end != str.begin() && std::isspace(static_cast<unsigned char>(end[-1]))) {
        --end;
    }
    str.erase(end, str.end());
    return str;
}

We might want to move seen_space into the lambda expression in later C++ versions that allow that.

This also is more readable, as we can perform the widening to unsigned int when calling the lambda, rather than having to write a cast.

Style-wise, I'd normally prefer to name the lambda, and keep the erase-remove call on a single line so that the idiom is obvious:

// Assuming C++17 now
std::string remove_excessive_ws(std::string s)
{
    auto is_doubled_space =
        [seen_space=false](unsigned char c) mutable {
            return std::exchange(seen_space, std::isspace(c))
                && seen_space;
        };
    s.erase(std::remove_if(s.begin(), s.end(), is_doubled_space), s.end());
    // remove trailing whitespace
    if (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) {
        s.pop_back();
    }
    // convert all whitespace into ordinary space character
    std::replace_if(s.begin(), s.end(),
                    [](unsigned char c) { return std::isspace(c); }, ' ');
    return s;
}


Make this Ruby array pivot more efficient?

Ruby allows -1 as an index that means last, so you don't have to calculate it at all.

Calculating the whole left_sum every time is repeating work since it is always the previous left_sum + arr[index-1] (except for when index = 0). Similarly the right_sum is always the previous right_sum - arr[index].

You don't have to gather all results, so you can terminate early on finding the leftmost solution, or as soon as sum_left > sum_right (assuming there are no negative numbers in arr?) you know there is no solution, so can return -1.

For example (untested)

def find_pivot(arr)
  sum_left = -arr[-1]
  sum_right = arr.inject(:+)
  arr.each_index do |i|
    sum_left  += arr[i-1]
    sum_right -= arr[i]
    if sum_left == sum_right
      return i
    elsif sum_right < sum_left
      # assuming there are no negative numbers we already know there's no solution
      return -1
    end
  end
  return -1 # in case we somehow reach the end without a solution or early termination
end

Initialising sum_left to -arr[-1] is a trick to save on having to add an if statement to detect and handle the first iteration of the loop differently, since it cancels out the effect of sum_left += arr[0-1] which would make sum_left jump to the value of the last value in the array.


QNetworkReply network reply timeout helper

Here are my thoughts:

It's a simple class that allocates quite a few times on the heap. You could minimize the number of implicit allocations it does. The QTimer::singleShot creates a temporary QObject instance and allocates a bunch on the heap. You can avoid it by handling a single-shot timer explicitly using timerEvent. You also avoid the need to set up any connections that way. A QObject does about two allocations when the first connection is added to it.
Use Qt-5 style connections, but that doesn't apply anymore in light of #1 above.
Add a static helper method that uses this class to set a timeout on a network request. The fact that you need to allocate ReplyTimeout is an implementation detail of sorts that could be abstracted out that way.
Check if the reply is running before you set a timeout on it. Perhaps it was an incorrect/impossible request at the moment it was submitted to the manager and it was immediately finished.
You're not supposed to name your classes with a Q prefix. It's reserved for Qt.

The code below is portable across Qt 4 and Qt 5:

class ReplyTimeout : public QObject {
  Q_OBJECT
  QBasicTimer m_timer;
public:
  ReplyTimeout(QNetworkReply* reply, const int timeout) : QObject(reply) {
    Q_ASSERT(reply);
    if (reply && reply->isRunning())
      m_timer.start(timeout, this);
  }
  static void set(QNetworkReply* reply, const int timeout) {
    new ReplyTimeout(reply, timeout);
  }
protected:
  void timerEvent(QTimerEvent * ev) {
    if (!m_timer.isActive() || ev->timerId() != m_timer.timerId())
      return;
    auto reply = static_cast<QNetworkReply*>(parent());
    if (reply->isRunning())
      reply->close();
    m_timer.stop();
  }
};

Use:

QNetworkAccessManager networkAccessManger;
QNetworkReply* reply =
  networkAccessManger.get(QNetworkRequest(QUrl("https://www.google.com")));
ReplyTimeout::set(reply, 100);


Handling exceptions and executing code if one was found

So I'm assuming that all of this code is in a for loop, and that for loop is incrementing i as it's loop statement.

What you can do here is not unconditionally increment i in each iteration of the loop, and instead only increment i if you're able to read in the number successfully:

for (int i = 0; i < 10; )
{
    try
    {
        Console.WriteLine("Input number {0}", i + 1);
        int number = ReadNumber(start, end);
        i++;
    }
    catch (ArgumentException)
    {
        Console.WriteLine("The input number wasn't in the alowed range. Please try again.");
    }
    catch (FormatException)
    {
        Console.WriteLine("The input isn't an integer number. Please try again.");
    }
    catch (Exception)
    {
        Console.WriteLine("An unknown error occured. Please try again.");
    }
}

However, for this case I'd say that there's an option that's better still.

What you should really do is, rather than having a method try to get another value from the user and possibly failing and possibly succeeding and needing to be called again, create a method that keeps asking the user for a value until it gets a valid one.  This logic is far easier to implement at that scope than it is to try to continually add more iterations to the loop.

Once you create a method that will always get a valid value, trying as hard as it needs to:

public static int ReadNumber(int start, int end, int iteration)
{
    while (true)
    {
        Console.WriteLine("Input number {0}", iteration + 1);
        int n;
        if (!int.TryParse(Console.ReadLine(), out n))
            Console.WriteLine("The input isn't an integer number. Please try again.");
        else if (n < start || n > end)
            Console.WriteLine("The input number wasn't in the alowed range. Please try again.");
        else
            return n;
    }
}

(Also note the use of conditional checks to determine if the user input is valid, rather than using exceptions for non-exceptional control flow.)

Now our loop is dead easy:

for (int i = 0; i < 10; i++)
{
    int number = ReadNumber(start, end, i);
}


Is there a better way to do get/set periodically in tornado?

You could use a class to keep your scores inside a defined scope and not use the globals. This way it's fairly easy to test and you don't have to deal globals. All you need to ensure is that you always pass the same instance. You could probably do it using some sort Singleton patterns.

import tornado
import tornado.web

# I hate the name manager but couldn't come up with something good fast enough.
class ScoreManager(object):
    def __init__(self):
        self._scores = {}

    def fetch_from_database(self):
        # fetch from database
        self._scores = {'key': 'score'}

    def get_all(self):
        return self._scores

class MyRequestHandler(tornado.web.RequestHandler):
    # this is the way to have sort of a constructor and pass parameters to a RequestHandler
    def initialize(self, score_manager):
        self._score_manager = score_manager

    @tornado.web.asynchronous
    def get(self):
        def choice_with_score(items):
            # return a key related to scores
            return key

        def get_key():
            global scores
            return choice_with_score(self._score_manager)

        self.write('%s' % get_key())
        self.finish()

if __name__ == '__main__':
    # initially update
    score_manager = ScoreManager()
    score_manager.fetch_from_database()

    app = tornado.web.Application([
        (r'.*', MyRequestHandler, dict(score_manager=score_manager)), # these params are passed to the initialize method.
    ])

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()

    # background update every x seconds
    task = tornado.ioloop.PeriodicCallback(
            update,
            15 * 1000)
    task.start()

    ioloop.start()


There is only one concern for me: you should not allow to instantiate the object with max elements below 0 (IllegalArgumentException ). Therefore a proper handling for this situation in your methods has to be made to avoid a neverending blocking. I suggest to return null.

Expecting a timout for your poll-method may be beneficial in several situations. Concurrent implementations of the Java API do define both: a non-argument poll-method and one with a timeout. But I do not see this as mandatory.

Some developers will suggest to make synchronization intransparent to the user of your class introducing an internal lock object and mention thread-safety in JavaDoc. They argue with "defensive programming" to prevent deadlocks. My personal opinion to that: You send the wrong message to the using developer.

Don't get me wrong: Preventing deadlocks is important. But it is more important to know what to do when. That is known as competence. Preventing others to make mistakes is ok. That can be done in several ways. But others to allow a lack of competence is exactly the message you would send. You would try to solve a potential future errors that are not your business. On the other side you allow misusage of objects without habing the other force to correct thhis. My way is: If someone is doing strange things with objects he doesn't own he either should know exactly what he is doing or handle occuring errors and deadlocks. You should know that this is how the majority of developers will NOT argue.


Parsing values from string into struct using match in Julia

The easiest thing I can think of is to use eachmatch -- when there is no match at all, it returns an empty iterator:
julia> collect(eachmatch(r"(bar:(\w*))", "bla bar:werfsd 1223 bar:skdf"))
2-element Array{RegexMatch,1}:
 RegexMatch("bar:werfsd", 1="bar:werfsd", 2="werfsd")
 RegexMatch("bar:skdf", 1="bar:skdf", 2="skdf")

julia> collect(eachmatch(r"(bar:(\w*))", "bla "))
RegexMatch[]

Then you can simply combine those into a dictionary, for example:
julia> Dict(re => [m[1] for m in eachmatch(re, s)] for re in patterns)
Dict{Regex,Array{T,1} where T} with 3 entries:
  r"qux:(\w*)" => Union{Nothing, SubString{String}}[]
  r"baz:(\d*)" => SubString{String}["33"]
  r"bar:(\w*)" => SubString{String}["werfsd", "skdf"]

Without further information about how you want to organize your data structure when more then one value occurs, I can't really say more.  Perhaps you can make use of merge.
Give types to struct fields, and don't use mutable structs unless necessary.  Without knowing more, I suggest
struct Foo
    bar::Union{String, Nothing}
    baz::Union{String, Nothing}
    qux::Union{String, Nothing}
end
function Foo(;bar=nothing, baz=nothing, qux=nothing)
    return Foo(convert(Union{String, Nothing}, bar),
               convert(Union{String, Nothing}, baz),
               convert(Union{String, Nothing}, qux))
end

which also takes care of converting the SubString from the regex match, in case this is relevant.


Creating a singleton container class for intrer-class messaging

I don't see why you need a singleton. You are already passing around container references as parameters. So, if you only create one container in __main__ and pass that to the class instances, they will all be accessing the same container.

Instead of calling Singleton() in Three.__init__ you would simply do the usual thing:

class Three:
    def __init__(self, container)
        self.container = container


Opinions/Improvements on a run periodically/timer function in Python 2.7

I don't think you do need the scheduler for that, at least not for how you use it.
Your loop schedules 1 event and just afterwards waits until it's finished, since run() waits until the scheduled event(s) are completed.

You can achieve the same by just sleeping for runtime seconds and calling runme() afterwards (you have to sleep before, since the scheduler delays the action for runtime seconds).

Also note that random.randrange(intsmall, intlarge) will return a value between intsmall and intlarge - 1, so your random time will be between 40 seconds and 99 seconds.


Create a method:

private void DisplayError(String errorMessage)
{
    // display any errors in the error window
    Error errorWindow = new Error();
    errorWindow.Show();
    errorWindow.errorMessage.Text = errorMessage;
}

Then you can do

private void searchButton_Click(object sender, RoutedEventArgs e)
{
    searchCriteria.Clear();
    searchCriteria.Add(townSearchTextbox.Text);
    searchCriteria.Add(countySearchTextbox.Text);
    searchCriteria.Add(postcodeSearchTextbox.Text);

    if (isValidSearchCriteria(searchCriteria))
    {
        formatSearchCriteria(searchCriteria);
        set.updateWOEID(searchCriteria);
        if (set.WOEID.Length > 0)
        {
            // continue
        }
        else
        {
            DisplayError("Error: Could not retrieve WOEID, please try again.");
        }
    }
    else
    {
        DisplayError("Error: Please provide one or more search criteria.");
    }
}

Of course, the next step if you need it would be to use Exceptions instead.  Yes, I know this is for Java, but it shows why.


Stopping a thread that runs an action periodically

Your code is almost correct. Here's your code stripped down:

    while (true)
    {
        auto next_flush = prev_flush + flush_interval_;
        std::unique_lock<std::mutex> lock{flush_stop_mutex_};
        auto stop_reason = flush_stop_cv_.wait_until(lock, next_flush);

        // stopping logic omitted
    }

Notice that the unique_lock is destroyed at the }, and so the mutex is not locked for a little while, until the next time you loop around and hit the std::unique_lock line. If another thread destroys the Logger during this period, it'll notify flush_stop_cv_ but you won't be listening and so you'll miss the notification... and that was your one chance to hear it, so now you'll never stop and your program is frozen.

Solution: If you're waiting for a notification that you absolutely must hear, then absolutely do not stop listening. Don't drop that lock!

    std::unique_lock<std::mutex> lock{flush_stop_mutex_};
    while (true)
    {
        auto next_flush = prev_flush + flush_interval_;
        auto stop_reason = flush_stop_cv_.wait_until(lock, next_flush);

        // stopping logic omitted
    }

Or if you're really worried about holding the mutex for some reason, then check again after taking the lock but before going to sleep:

    while (true)
    {
        auto next_flush = prev_flush + flush_interval_;
        std::unique_lock<std::mutex> lock{flush_stop_mutex_};
        if (flush_stop_) break;  // IMPORTANT LINE ADDED
        auto stop_reason = flush_stop_cv_.wait_until(lock, next_flush);

        // stopping logic omitted
    }

Otherwise, looks good to me.

condition_variable::wait_until is a fairly obscure function, IMO. Here you're assuming that it is implemented correctly and efficiently. I'm not sure that it always is, but I have no evidence to the contrary. The only immediately obvious way to get rid of wait_until is almost certainly worse: You could set another thread to notify the condition variable every flush_interval_ seconds, and detect spurious wakeups by computing std::chrono::system_clock::now() - prev_flush_, instead of by looking for std::cv_status::timeout.


Web scraping the titles and descriptions of trending YouTube videos

Why web-scrape, when you can get the data properly through the YouTube Data API, requesting the mostpopular list of videos?  If you make a GET request to https://www.googleapis.com/youtube/v3/videos?key=…&part=snippet&chart=mostpopular, you will get the same information in a documented JSON format.

Using the Python client, the code looks like:

import csv
import googleapiclient.discovery

def most_popular(yt, **kwargs):
    popular = yt.videos().list(chart='mostPopular', part='snippet', **kwargs).execute()
    for video in popular['items']:
        yield video['snippet']

yt = googleapiclient.discovery.build('youtube', 'v3', developerKey=…)
with open('YouTube Trending Titles on 12-30-18.csv', 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(['Title', 'Description'])
    csv_writer.writerows(
        [snip['title'], snip['description']]
        for snip in most_popular(yt, maxResults=20, regionCode=…)
    )

I've also restructured the code so that all of the CSV-writing code appears together, an inside a with open(…) as f: … block.


Counting characters, digits, spaces and newlines in the loaded file

Don't use wildcard imports

PEP8 says that wildcard imports should be avoided. Instead, I recommend you import tkinter like this:

import Tkinter as tk

This means that everywhere you use a tkinter class or constant you need to prefix it with tk.. This will make your program a bit easier to read and understand, especially if you eventually choose to import widgets from ttk which provides many classes with the same name as tkinter classes.

Group layout commands together

You have calls to pack scattered throughout your code, making it difficult to visualize how things are laid out. I strongly recommend grouping your layout code based on parent (ie: call pack on all children that share the same parent)

For example:

topFrame1 = Frame(root)
lbl = Label(topFrame1, text="Chars count: ")
lblCharLength = Label(topFrame1, textvariable=self.charLength)

# pack all children of topFrame1 together
lbl.pack( side = LEFT )
lblCharLength.pack( side = RIGHT )

lbl = Label(topFrame2, text="Digits count: ")
lblDigitsLength = Label(topFrame2, textvariable=self.digitsLength)

# pack all children of topFrame2 together
lbl.pack( side = LEFT )
lblDigitsLength.pack( side = RIGHT )

...

# pack all of the children of root together
topFrame1.pack( side = TOP )
topFrame2.pack( side = TOP )
topFrame3.pack( side = TOP )
topFrame4.pack( side = TOP )
bottomFrame.pack( side = BOTTOM )

You don't need StringVar

You don't need to use StringVar in your code. The way you are using it means you have more objects, but these objects don't give you any added benefits. Thus, it makes your code more complex than it needs to be.

If you need to change a label at runtime, you can keep a reference and then use the configure method to directly change the label.

self.lblCharLength = Label(topFrame1, textvariable=self.charLength)
...
self.lblCharLength.configure(text=len(s))

If you choose to use them, I recommend setting the value at the time  you create them, which will cut down on the total lines of code:

self.filePath = StringVar("File not loaded")
self.charLength = StringVar(value=0)
self.digitsLength = StringVar(value=0)
self.spacesLength = StringVar(value=0)
self.entersLength = StringVar(value=0)

Use with to open and read a file

with makes it easy to write code that is wrapped by other code. In this case you want to do an open, read some code, and then do a close.

Note: you should also verify that the user picked a path. As written, if the user presses cancel, self.filePath will be empty and your code will throw an error.

Also, when you try to cram two or more function calls into a single statement it can make the code harder to debug. By using intermediate variables it makes it easier to pause your program and examine the state.

For example:

if filepath:
    self.filePath.set(filepath)   # if using StringVar
    # self.filePath.configure(text=filepath)   # if not using StringVar

    with open(filepath, "r") as f:
        s = f.read()
    ...

Avoid calling update

At the end of your function importFile you call self.root.update. That is completely superfluous. The screen will update as soon as the function returns.


for x, y in [(x,y) for x in loop_range for y in loop_range]:

Here you could avoid the list creation by using a generator (by changing the [] to ()) or you could use itertools.product. Probably no difference performance-wise, but the latter is less code.

    for x_coef, y_coef, mods in [(4, 1, [1, 5]), (3, 1, [7]), (3, -1, [11])]:

Again, you are creating lists which takes time. This whole thing you iterate over could be a constant nested tuple that's only allocated once at the top (or even outside the function).

        for square in [i * value**2 for i in range(limit//value**2+1)
                       if i * value**2 < limit]:

At this point you can probably guess that I'll recommend doing away with the list. A generator should work. If on Python 2, xrange is probably better than range as well.

(Note, I didn't mention loop_range. That could be changed into xrange invocations if you are on Python 2, but you seem to be on Python 3.)

There's also a question mark I have: int(limit**(1/2)) – that works in Python 3, but not Python 2, because 1/2 == 0. Since your code seemed to work for you, I assume you are on Python 3. I'm not sure if Python 3 people think making it portable with a dot/cast is a good idea or not (i.e. 1./2). There's always the explicit sqrt if you can't decide.


Generic logging class for tracing the function calls

Stop doing this:

using namespace std;

see: Why is “using namespace std;” considered bad practice?

These two are not unique to the class.

string in{ ">>" };
string out{ "<<" };

May as well make them static. Also they re never modified so make them const.

No need to force a flush with std::endl

    cout << in << name << endl;

Prefer "\n" when you don't need a flush (also cerr or clog may be better choices of output stream).

That seems like an overly verbose and error prone way of use.

void generic_function() {
    functionlogging logger{ __func__ };

You have to use up a variable and remember __func__. Can't we get a macro in here to do all the for you? I actually need to look up to see if func is a standard macro.

Just checked the standard:

8.4.1 In general
Paragrah 8:
The function-local predefined variable __func__ is defined as if a definition of the form

static const char __func__[] = "function-name ";

So I would define the macros:

#define LOG_ENTRY_EXIT_FOR(x)       functionlogging  SomeLongNameThatIsNotLikelyToBeUsedInTheFunctionlogger(x)
#define LOG_ENTRY_EXIT              LOG_ENTRY_EXIT_FOR(__func__)

Then usage is simply:

void generic_function() {
    LOG_ENTRY_EXIT;

    int a = 10;
    int b = 100;
    a += b;
}


Throwing an exception within a try/catch block in PHP

The way you did it is pretty much the standard way to bubble exceptions up the stack. Basically something like:

function a(){
    throw new Exception("Exceptional!");
}

function b(){
    try{
        a();
    } catch (Exception $e){
        throw $e;
    }
}

try{
    b();
} catch (Exception $e){
    echo $e->getMessage();
}

This will output:

Exceptional!

Do note that if you in b() do throw new Exception($e), you'll get:

exception 'Exception' with message 'Exceptional!' in sandboxed.php:1
Stack trace:
    #0 php(5): a()
    #1 php(12): b()
    #2 {main}

For your code however, you'd have to make sure that you are your try/catch block is within another try/catch block, otherwise you will end up with an uncaught exception error.

try{
    try {
        $ffprobe      = FFProbe::create();
        $streams      = $ffprobe->streams($infile);
        $videoStreams = $streams->videos();
        $audioStreams = $streams->audios();

        if (!$videoStreams) {
            throw new Exception("Could not find a video stream for file: " . $infile . PHP_EOL);
        }

    } catch (RuntimeException $e) {
        throw $e;
    }
} catch (Exception $e){
    echo $e->getMessage();
}

May I ask why you are bubbling exceptions like this rather than erroring out on a caught exception?

EDIT
Fail often:

try{
    $ffprobe = FFProbe::create();

    try {
        $streams = $ffprobe->streams($infile);
    } catch (RuntimeException $e) {
        throw $e;
    }

    $videoStreams = $streams->videos();
    $audioStreams = $streams->audios();

    if (!$videoStreams) {
        throw new Exception("Could not find a video stream for file: " . $infile . PHP_EOL);
    }
} catch (Exception $e){
    echo $e->getMessage();
}


Cancelable AsyncLazy that is thread-safe

Specification Considerations

Note that the first caller that gets access is the one that provides the cancellationToken for the valueFactory. Other callers use their own cancellationToken for timing out on awaiting the result of the async operation. This is how you designed your class. I did not change this part of the behavior.

If this behavior is not wanted, consider storing a cancellation token through the constructor. This one is used solely for the factory. And each call to GetValueAsync could then use its own cancellation token to time out, without influencing possible cancellation of the factory. This is a design decision you would have to make.

Review

This is not a good solution. You know it, we all know it :-)

await Task.Run(() =>
{
    while (_shouldWait) Thread.Sleep(1);
});

The way to delay a thread the async way is to use Task.Delay (Overview TAP Guidelines). This is already better. But as you mentioned, this still feels like a hack (and it is). Using some sort of Mutex would be a better approach, as you rightfully indicated. We'll get to that.

Lets' walk through your code.

You define 2 similar variables _isValueCreated and _shouldWait. If you think about it, they have the same purpose. As long the value is not created, a caller should wait. Let's merge them into a variable named .. let's say _memoized. This is common terminology in caching.

private bool _isValueCreated = false;
private volatile bool _shouldWait = false;

Rather than the whole construct of abusing a thread's Sleep and using a volatile bool to simulate a lock, we could use a Semaphore (Async Mutex using a Semaphore).

As discussed in the previous link, this is not possible..

// example code
lock (lockObject)
{
    await Task.Delay(1000);
}

.. but this is..

// example code
await semaphoreSlim.WaitAsync();
try
{
    await Task.Delay(1000);
}
finally
{
    semaphoreSlim.Release();
}

Let's see how we can implement this in your cancellable async lazy class.

Refactoring the Code

We define our variables. Your two booleans are merged into one. And we use the semaphore described above.

private readonly Func<CancellationToken, Task<T>> _valueFactory;
private volatile bool _memoized;
private readonly SemaphoreSlim _mutex;
private T _value;

The constructor is straight-forward. Make sure to use a Semaphore than emulates a Mutex so one thread has access to the resource simultaneously.

public CancelableAsyncLazy(Func<CancellationToken, Task<T>> valueFactory)
{
    _valueFactory = valueFactory ?? throw new ArgumentNullException(nameof(valueFactory));
    _mutex = new SemaphoreSlim(1, 1);
}

The infamous GetValueAsync can then be rewritten completely. Each caller thread can provide its own cancellationToken. Use it to acquire a lock on _mutex. Once we have the lock, check whether _value is already memoized. If not (!_memoized) execute _valueFactory, and memoize the value. Now, we perform another timeout check for the calling thread ThrowIfCancellationRequested. Even though we have the value available now, the caller might still have timed out, so let him now. Don't forget to release the mutex.

public async Task<T> GetValueAsync(CancellationToken cancellationToken)
{
    await _mutex.WaitAsync(cancellationToken);
    try
    {
        if (!_memoized)
        {
            _value = await _valueFactory(cancellationToken).ConfigureAwait(false);
            _memoized = true;
            cancellationToken.ThrowIfCancellationRequested();
        }
        return _value;
    }
    finally
    {
        _mutex.Release();
    }
}

We should allow for a convenience overload if no cancellation support is required for a given caller.

public async Task<T> GetValueAsync() => await GetValueAsync(CancellationToken.None);

And since we comply to the concept of Lazy we should also provide a synchronous property Value.

public T Value => GetValueAsync().Result;

Refactored Code

public sealed class CancelableAsyncLazy<T>
{
    private readonly Func<CancellationToken, Task<T>> _valueFactory;
    private volatile bool _memoized;
    private readonly SemaphoreSlim _mutex;
    private T _value;

    public CancelableAsyncLazy(Func<CancellationToken, Task<T>> valueFactory)
    {
        _valueFactory = valueFactory
            ?? throw new ArgumentNullException(nameof(valueFactory));
        _mutex = new SemaphoreSlim(1, 1);
    }

    public T Value => GetValueAsync().Result;

    public async Task<T> GetValueAsync() => await GetValueAsync(CancellationToken.None);

    public async Task<T> GetValueAsync(CancellationToken cancellationToken)
    {
        await _mutex.WaitAsync(cancellationToken);
        try
        {
            if (!_memoized)
            {
                _value = await _valueFactory(cancellationToken).ConfigureAwait(false);
                _memoized = true;
                // at this point, the value is available, however, the caller
                // might have indicated to cancel the operation; I favor
                // checking for cancellation one last time here, but you
                // might decide against it and return the result anyway
                cancellationToken.ThrowIfCancellationRequested();
            }
            return _value;
        }
        finally
        {
            _mutex.Release();
        }
    }
}


Passing data from one promise to another using then

You could do like so if you prefer, essentially just pass forward the data i the promises. You could write your own promiseAllObject if you want it to be slightly neater.
const result = getMovies()
  .then(movies => {
    return Promise.all([
      Promise.all(movies.map(({ movieId }) => getTitle(movieId))),
      movies.map(_ => _.rating)
    ]);
  })
  .then(([titlesObj, ratings]) => ({
    titles: titlesObj.map(_ => _.title),
    ratings
  }))
  .catch(console.log);

result.then(r => console.log(r));


Your parseChunk function is not really parsing an expression — it is also evaluating it.  Its naming style is also inconsistent with is_number?.  I think that eval_binary_expr would be a more appropriate name.

Augmenting the String class with an is_number? method is something to avoid doing.  That kind of patching increases the chances of breakage when your code coexists with other code in the same program.

In functions that are meant to be used by other code, calling exit is not an appropriate way to handle errors.  You should raise exceptions instead, so that the caller can handle the error in whatever way it chooses.

You appear to be working much too hard to parse the binary expression.  I think that this would accomplish more or less the same thing:

def eval_binary_expr(expr)
  l_operand, op, r_operand = expr.partition(%r{[/*+-]})

  if op.empty?
    raise ArgumentError, "Invalid operation or no operation in expression: #{expr}"
  end
  l_operand, r_operand = Float(l_operand), Float(r_operand)

  case op
    when '/' then l_operand / r_operand
    when '*' then l_operand * r_operand
    when '+' then l_operand + r_operand
    when '-' then l_operand - r_operand
  end
end

The solution above makes no attempt to handle negative numbers correctly.  As with your original solution, it fails when the first operand is negative.


Basic Imitation of C# Enumerable in VBA - or any other static class

For each requires that number be declared as a Variant, but For..To requires a number. I like that you explicitly declared Dim number As Variant. It makes it clear that that you intended on it and didn't simply forget to specify the type. However, you've not specified what type param1 and param2 should be. By declaring them as longs you can stop several lines of code from executing if some unwary dev passes a string or object into .Range(). Runtime error 13 "Datatype mismatch" gets thrown either way, but it happens sooner and there's a tool tip showing what datatype is to be expected.

The params also being passed ByRef. While there are no side effects on the parameters, it would be nice and in good faith to let anyone using this class know that there are not any side effects by passing them ByVal.

Public Function Range(ByVal param1 As Long, ByVal param2 As Long) As Collection
    Set c = New Collection
    Dim i As Long
    For i = param1 To param2
        c.add i
    Next
    Set Range = c
End Function

Another thing to note is that using this method will be exactly twice as slow as just using a For loop. This is because the code loops once to build the collection and then again to enumerate over the collection. When performance is absolutely critical you might want to skip the syntactic sugar.

I tested against negative longs and your code works just fine.

There are a number of missing features that I'd like to see, but I suspect you'll have some amount of difficulty getting them to "feel right". This has to do with VBA's lack of proper inheritance and method overloading. I've attempted to do something similar recently without much luck. You've already gotten farther than I did though, so I'll be keeping an eye on vba4All to see what you come up with. =)


You can use roll_sum from the RcppRoll package to calculate rolling sums. That way I got an 80-fold speed increase.

Also from a memory perspective, your bigMatrix can be a lot smaller.

Below is my version of nextMatrix.

require(RcppRoll)
nextMatrix2 <- function(mat,w) {
  # Make continuous matrix only as large as necessary
  wideMatrix <- cbind(mat[, ncol(mat)-4:0], mat, mat[, 1:6])
  bigMatrix <- rbind(wideMatrix[nrow(mat)-4:0, ] , wideMatrix, wideMatrix[1:6, ])
  # use roll_sum from RcppRoll to get act/inh as matrices
  actMat <- roll_sum(roll_sum(bigMatrix[3:208, 3:208], 7), 7, by.column=FALSE)
  inhMat <- roll_sum(roll_sum(bigMatrix, 12), 12, by.column=FALSE)*w
  # create the new matrix
  newMat <- actMat > inhMat
  newMat[actMat == inhMat] <- mat[actMat == inhMat]
  # retrun newMat
  return(newMat)
}

And the benchmarktest:

# load benchmarking package
require(microbenchmark)
# create data
x <- createMatrix(200,200)
y <- x
# benchmarktests
microbenchmark(
  x <- nextMatrix(x, 0.33)
  ,
  y <- nextMatrix2(y, 0.33)
)
## Unit: milliseconds
##                      expr        min         lq       mean    median         uq       max neval cld
## x <- nextMatrix(x, 0.33)  545.519907 566.455440 584.396621 577.26897 590.373952 687.29806   100   b
## y <- nextMatrix2(y, 0.33)   5.858406   6.131756   7.214752   6.24489   6.453976  62.63813   100  a
#
# checking for equality
all.equal(x, y)
## [1] TRUE


Order list of movies and save sorting in cookies

You could improve your code by doing the following:

Do not use and/or but &&/|| since what you need here is boolean operators, not flow control operators. Take a look at this article for a great example on how and when to use each operator.
You are constantly doing instance variable assignment at the one-liners conditionals which makes the code difficult to read (conditional ? @i = x ? @i = y). It's not wrong, but you could assign the result of the operation directly to the instance variable.
You could extract some conditional checks to private methods to state in a more clear way what your code does.
I'm not sure for this one, but I'll go for it. I think that you need the redirect when you set the session. You could just pass it to Movie.sort_by_and_rating(...).

Here's a refactored version of your code:

class MoviesController < ApplicationController
  def index
    @movies = Movie.all
    @all_ratings = Movie.all_ratings
    @sort = params[:sort] || session[:sort]
    @ratings_filter = params_rating? ? params[:ratings].keys : (session[:ratings] || @all_ratings)

    if set_cookies?
      session[:ratings] = @ratings_filter
      session[:sort] = @sort
    end

    @movies = Movie.sort_by_and_rating(@sort, @ratings_filter)
  end

  private

  def params_rating?
    params[:ratings] && params[:commit] == 'Refresh'
  end

  def set_cookies?
    params[:sort] != session[:sort] || params[:ratings] != session[:ratings]
  end
end


Partitioning a list in F# based on whole group characteristics

Based on this answer from the Haskell version of this question, it looks like we can do something as simple as:

let partitionOn groupComplete list =
    let rec inner currentGroup remainingList =
        match (currentGroup, remainingList) with
        | (group, []) -> [group]
        | (group, remaining) when groupComplete group -> [group] @ (inner [] remaining)
        | (group, head::tail) -> inner (group @ [head]) tail
    inner [] list

This simply recursively handles the three cases of: running out of elements; having a complete group; and building a group.

Update

Henrik Hansen pointed out that it is preferable to have a tail-recursive function. One possible way of achieving this is:

let partitionOn groupComplete list =
    let rec inner currentGroup remainingList =
        match remainingList with
        | [] -> [currentGroup]
        | head::tail ->
            let complete = groupComplete currentGroup
            let additionalGroup = if complete then [currentGroup] else []
            let newCurrentGroup = if complete then [] else currentGroup @ [head]
            let newRemaining = if complete then remainingList else tail
            additionalGroup @ (inner newCurrentGroup newRemaining)
    inner [] list

This merges together the last two cases of the match and gives a single call to inner at the end.

Update 2

If we look at the IL for this version, we can see that it is tail recursive:

    ...
    IL_0069: tail.
    IL_006b: call class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!!0> [FSharp.Core]Microsoft.FSharp.Core.Operators::op_Append<class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!!a>>(class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!!0>, class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!!0>)
    IL_0070: ret
    IL_0071: ldarg.1
    IL_0072: call class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!0> class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!!a>>::get_Empty()
    IL_0077: call class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!0> class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!!a>>::Cons(!0, class [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1<!0>)
    IL_007c: ret
} // end of method _::'inner@2-5'

Update 3

Nice idea to use a fold, from TheQuickBrownFox. This can be done more simply using the built-in fold function, keeping the same API:

let partitionOn groupComplete list =
    let folder acc x =
        match List.rev acc with
        | [] -> [[x]]
        | current::rest when groupComplete current -> acc @ [[x]]
        | current::rest -> (List.rev rest) @ [current @ [x]]
    List.fold folder [] list

However, @ is O(n), whereas :: is O(1), so it should really be:

let partitionOn groupComplete list =
    let folder acc x =
        match acc with
        | [] -> [[x]]
        | current::rest when groupComplete current -> [x]::acc
        | current::rest -> (x::current)::rest
    List.fold folder [] list |> List.map List.rev |> List.rev

Update 4

Based on TheQuickBrownFox comment the fold could be modified as follows:

let partitionOn initialGroupValue groupUpdate groupComplete list =
    let folder acc x =
        match acc with
        | ([], score) -> ([[x]], groupUpdate score x)
        | (a, score) when groupComplete score -> ([x]::a, groupUpdate initialGroupValue x)
        | (current::rest, score) -> ((x::current)::rest, groupUpdate score x)
    List.fold folder ([], initialGroupValue) list |> fst |> List.map List.rev |> List.rev

This version separates the current group evaluation into an update and a test, so that the minimum change is made for each iteration of the fold and the whole group doesn't need to be recalculated each time.


Did you ask any questions before you started?
It seems like there are a couple of holes in the design that need firming up.

Is there a maximum run length?  (ie is single digit lengths enough)
Does the input string only contain alpha? (ie no numbers).
Do you encode single character runs? (ababab => a1b1a1b1a1b1 or ababab)

General comments
The algorithm you are using is too complex.
Some of the answers on SO show you how to simplify the algorithm so I will not repeat that here (they are all good).
Code comments
Don't put two variables on a line:
int charRepeatCount = 0; bool isFirstChar = true;

Any function that begins with an underscore is a not a good idea.
_snprintf(repeatStr, 10, "%i", charRepeatCount);

The underscore means that it is implementation defined. If there are no alternatives fine. But always prefer standard functions to non-standard implementations hacks (especially if they were done by MS). In this specific case the standard one is better designed and make usage easier.
Also why are you printing to a character array then copying to the destination array?
 _snprintf(repeatStr, 10, "%i", charRepeatCount);
 int repeatCount = strlen(repeatStr);
 for (int i = 0; i < repeatCount; i++)
 {
     *target = repeatStr[i];
     target++;
 }

You can print directly to the destination:
 sprintf(target, "%i", charRepeatCount);  // notice not snprintf because I
                                          // I don't know the size of the
                                          // target. That is comming up.
                                          // You should definately use the
                                          // snprintf() version if you can.

You have sections of repeated code (the bit above).
If you are repeating code you should break it into a separate function.
Interface design:
void formatstring(char* target, const char* source)

I have no idea how much space I am allowed to use in target. Either allow the function to allocate its own space (and return the pointer) or get a maximum size passed into the function. If you pass in a size the return value is usually the amount of space you would have needed to succeed. This allows the user to do pre-flighting to work out the size required.
int size = LokiFormatString(source, NULL, 0);
char* tareget = (char*) malloc(size + 1);
int size = LokiFormatString(source, target, size);


I have a couple of suggestions and observations I'd like to point out:

Fully qualified System types reduce readability without adding information.
So: use string[] instead of System.String[], bool instead of System.Boolean and so on.

Defining a lambda statement and storing it in a variable overcomplicates the code. Use query expression syntax instead.

Are you actually using the return value as a string[] (accessing by index, etc.) or could you get away with returning IEnumerable<string>? (Eric Lippert explains why you should.)

Your isConstKey looks wrong, but it's hard to tell because of the double negative. Are you trying to remove empty strings? Currently, you're leaving the white space in the result, not removing it. In below code sample, I've corrected the problem.

Instead of comparing all the SpecialKeyStrings seperately, put them into a sequence exposed as a property of MyUtility and use LINQ to validate against that:
  public static IEnumerable<string> SpecialStringKeys
  {
      get
      {
          return new[] { SpecialStringKey1, SpecialStringKey2, SpecialStringKey3,
                         SpecialStringKey4, };
      }
  }

Edit: other possibilities would be to avoid creating a new array every time; you could create a private static readonly ReadOnlyCollection<string> field or just a private static readonly string[].
All that would allow your GetStringParts method to be changed to the following:
protected static IEnumerable<string> GetStringParts(string stringValue)
{
    return from part in stringValue.Split('!')
           where !string.IsNullOrWhiteSpace(part) &&
                 !MyUtility.SpecialStringKeys.Any(part.StartsWith)
           select part;
}

(If you really need an array, add the ToArray call and change the return type back).
If you want to go one step further in readability, you could extract the condition to an extension method:
public static bool IsNeitherKeyNorWhiteSpace(this string source)
{
    return !string.IsNullOrWhiteSpace(source) &&
           !MyUtility.SpecialStringKeys.Any(source.StartsWith);
}

Changing your original method thus:
protected static IEnumerable<string> GetStringParts(string stringValue)
{
    return from part in stringValue.Split('!')
           where part.IsNeitherKeyNorWhiteSpace()
           select part;
}


Lowest Common Ancestor in Binary Tree (Iterative)

Unit tests
Turn these:
print(lowest_common_ancestor(root, root.left.left, root.left.right))       # 11
print(lowest_common_ancestor(root, root.left.left, root.left))             # 11
print(lowest_common_ancestor(root, root.left.left, root.right.right))      # 30

into assertions of the form assert 11 == ..., and you'll immediately have a unit test, which is generally of greater value.
Pop
node = stack[-1]
stack.pop()

should not be necessary; that's what pop already does:
node = stack.pop()


Check Digit Calculator & GTIN-8 Validator

The doMaths function has no clear purpose — hence its weird name.  It acts as both to calculate the expected last digit of a 7-digit input and to validate the last digit of an 8-digit input.  Furthermore, it prints its results instead of returning them, hindering reuse of the function.

What you really want to do is share the code that calculates total.  You could write a function like this, using slices:

def gtin8_checksum_digit(number):
    """
    Given a 7- or 8-digit string, calculate the expected GTIN-8 checksum.

    >>> gtin8_checksum_digit('3141592')
    '7'
    >>> gtin8_checksum_digit('31415927')
    '7'
    """
    total = sum(3 * int(d) for d in number[0:7:2]) + \
            sum(int(d) for d in number[1:6:2])
    return str(10 - (total % 10))

No floating-point arithmetic should be necessary.

Note the docstring, and in particular, the doctests that make it clear how the function behaves.

To use that function…

if __name__ == '__main__':
    while True:
        try:
            number = input("Enter a 7 or 8 digit number for testing: ")
            int(number)    # Trigger possible ValueError
            if 7 <= len(number) <= 8: break
            print("Length of number must be 7 or 8")
        except ValueError:
            print("Only enter numbers.")
    if len(number) == 8:
        print("Valid" if gtin8_checksum_digit(number) == number[7] else "Invalid")
    else:
        print(gtin8_checksum_digit(number))


palindrome code in C times out in program challenge?

General Observations
It might be better to use an iterative solution rather than a recursive solution for this problem. Recursion can be expensive in terms of memory resources for the stack and it could also result in stack overflow. Calling a function is more expensive in terms of time than looping through a string as well. If the calling function created a reverse string it might be possible to use strcmp() or strstr() in the palindrome() function, either of those functions are very fast. It would also be faster to base the palindrome() function on strings rather than indexes.
While the program description uses n and d it would better to use more descriptive names in the program to make it more readable, examples might be length and displacement.
Since this question is performance based I won't recommend this, but memory for palavra be allocated in the while (1) { loop in main() since the length of the string is read in during each iteration.
Since English variable and function names are generally considered a global programming standard it might be better to use English variable and function names. I can figure out inicio and fim as start and end, but I don't have a clue what palavra or maior_sequencia (for maior_sequencia I'm guessing that it means major sequence). This is especially true since the problem statement is in English.
Avoid Global Variables
It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation.
The variable palavra should be declared in main and passed into functions as necessary.
Declare Variables as Necessary
The original version of C required all variables to be declared at the top of a logic block, but this is no longer the case. In almost all programming languages it is now considered better to declare and initialize variables as they are needed. In the C programming language they need to be initialized because no local variable have a default value assigned. Each variable should be declared and initialized on its own line to make the code easier to read, write and maintain. In the function maior_sequencia the variables i and j can be defined in their respective loops:
int maior_sequencia(const size_t length, const size_t displacement, char *palavra) {

    size_t valor = 0;
    size_t temp = 0;

    for (size_t i = 1; i <= displacement; i++) {
        temp = 0;
        for (size_t j = 0; j < length; j += displacement) {
            if (palindrome(j, j + i, palavra)) {
                temp++;
            }
        }
        if (temp * i > valor) {
            valor = temp * i;
        }
    }

    return valor;
}

Use Unsigned Integer Based Variables for Indexes and Sizes
Rather than using integers that can go negative for indexes and sizes it is better to use types such as size_t which are based on unsigned integers. The type size_t is what is returned by the sizeof(OBJECT) function as an example.
Magic Numbers
There are Magic Numbers function (100000), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Don't Ignore Library Function Return Values
The function scanf() returns an integer that indicates the number of values read or end of file (EOF). This value can be used to control the while loop in main() rather than having the while (1) loop with a break.
#define MAX_LENGTH 10000

int main() {
    size_t length = 0;
    size_t displacement = 0;

    while (scanf("%d %d", &length, &displacement) != EOF) {
        char palavra[MAX_LENGTH + 1];

        if (scanf("%s", palavra) == EOF)
        {
            break;
        }
        else
        {
            printf("%d\n", maior_sequencia(length, displacement, palavra));
        }
    }

    return 0;
}


There are a few things:

Comments like this one:

    parent::__construct(); // to run the constructor of parent

provide no real value; they just repeat what the code does.  Prefer reserving comments
for tricky bits of code that aren't self-explanatory.
You never use $dbLink; get rid of it. If subclasses need a database, let them
create one.
__destruct is largely unnecessary here.  You gain nothing from detaching references at
this point; PHP will already release them once your destructor returns.  And if you
followed the previous point, the only thing you're releasing no longer exists anyway.
All your variables are protected, which implies that you are planning for subclasses to
exist.  I'm not sure specializing a cart even makes much sense, though.

Unless you already have subclasses, and those subclasses need basically
unrestricted access to those properties, you should make them private.
(And even if you do, you might want to reexamine whether inheritance is the proper
relationship.)
You have a public constructor and a "create_cart" function?  That's going to confuse
people.  (You already created a Cart when you said new Cart.)  It looks like what you
need here is a name that more clearly describes what the function does.
I'm not a big fan of instance method names that include the containing class's name.
It feels like a symptom (or maybe a cause) of drifting away from OO concepts and back
to proceduralism.

This is just personal preference; take it as you will.  But IMO, if you have a Cart,
then from now until it dies, it will always be a Cart.  You don't have to keep
reminding it of that.  :)
I see that $cartProducts is a reference to an array in $_SESSION.  At that
point, both names refer to the exact same value.  Any change you make to
$this->cartProducts also happens to $_SESSION[$this->cartName], and vice versa.

Which makes me wonder: Why do so many methods mess with
$_SESSION[$this->cartName] rather than with $this->cartProducts?
Variable names like $data aren't very descriptive.  You know a product is being
added; most carts would include a quantity as well.  But i don't know for sure what
$data looks like, for two big reasons.  One is the name.  The other...?
You let the caller stuff whatever garbage it wants to in your cart.

A cart keeps track of items (or products), and typically quantities as well,
and usually has a way to get a total price.  This cart is basically a list of blobs,
and can't currently do any of that stuff easily, because it doesn't exert any type of
ownership.

The list of items is your domain, not the caller's.  Unless this is intended to be a
generic list of "whatever", you decide the structure of what goes into it -- and in
return, you get the ability to do stuff over and above what a stock list can do.
Otherwise, the caller is actually worse off using your cart than mucking around with
the $_SESSION['cart'] array directly.  (At least when they're using $_SESSION,
they know they're farting around with global state.  Your class hides that fact behind
what looks like a per-instance interface.)

You don't necessarily need to say "everything you insert must be an instance of this
particular class".  You could conceivably let the caller decide that much.  But you can
-- and probably should -- require that they exhibit certain behaviors (like having a
get_price() method).  These requirements should be documented.  And if you're
tracking quantities, then do so explicitly -- consider making $quantity a discrete
parameter to the add_product method.

Once you have decided how an item must behave, then you can do stuff that a typical
cart does out of the box.  If you decide items must have a price, for example, then
now you can add a way to get the total price of all items.   That in itself is part
of the bare minimum functionality i expect of any shopping cart class.  If it doesn't
have that, it's just another list.  :P

But the really big thing i'm seeing here is the relationship between carts and sessions.  A Cart might have a session, or use a session.  But it is really a different thing.  Inheriting from Sessions seems to me incorrect, unless the parent class is badly named.

It feels to me, though, like you have the relationship the wrong way around.  A Cart is obviously part of a session, as evidenced by your bunch of functions to manage subsets of session data.

And PHP lets you put objects in a session.

The cart itself could be session data, at which point $session->gimme('some cart name')
can return a whole Cart object, and all this session-management stuff becomes obsolete.

In order to make it work:

The class needs to be loaded, or autoloadable, before session_start().
The class must be serializable...which requires that anything you need to
persist must also be serializable, and/or that anything that's not serializable
not be included in the list of properties to store.
That's usually not a big deal; the only things PHP can't serialize are resources and
quasi-resources like your $dbLink.
(One of a number of reasons $dbLink probably isn't worth keeping.  But even if you
do, you can add a __wakeup() function to reinitialize it.)

The main thing to keep in mind is that if you only want the item info serialized, or you have unserializable fields (like $dbLink), you should provide a __sleep method that tells PHP which properties to serialize.  You'll probably also want a __wakeup() method to reinitialize those items that you didn't serialize.

With all that taken care of...what's left?

class Cart {
    private $items = [];

    public function add_product($product, $quantity) {
        $this->items[] = ['product' => $item, 'quantity' => $quantity];
    }

    public function delete_product_at($index) {
        unset($this->items[$index]);
    }

    public function update_product_at($index, $product, $quantity) {
        if (isset($this->items[$index])) {
            $this->items[$index] = ['product' => $product, 'quantity' => $quantity];
        }
    }

    public function get_total() {
        return array_reduce($this->items, function($sum, $item) {
            return $sum + $item['product']->get_price() * $item['quantity'];
        }, 0);
    }

    # don't really need __sleep or __wakeup, since $dbLink is gone.  But it might be
    # helpful to illustrate their use.
    private $some_value;

    public function __sleep() {
        # in `__sleep`, you return a list of properties you want saved
        return ['items'];
    }

    public function __wakeup() {
        # since $some_value wasn't serialized, it doesn't have a value.
        # before you use it again, set it to something sensible.

        $this->some_value = 42;
    }
}

The main missing piece left at this point is your display_cart function.  Not sure what it does...but frankly, if its name is accurate, it shouldn't be here.  :P

This is a model class, or a business object if you don't care about MVC and such.  It's responsible for managing the data, and for representing it in a way that the UI can do something with it. But most schools of thought on software architecture would say this class shouldn't be involved in the actual presentation/rendering.  That's the job of the code that manages the UI.

If you want to be able to list the cart's contents, two simple ways would be to have a function that returns $this->items, or implement the IteratorAggregate interface and have a getIterator() function return an iterator over $this->items.


Your indentations strike me as reasonable.  In any case, in functions you can often use return statements to help avoid indentation ...

def get_fields(id):
    if id:
        fields = ...
        return fields

    try:
        fields = ...
    except:
        fields = ...

    return fields


You could remove all elements from the queue and then offer them back if necessary.

public void run() {
    ArrayList<Task> tasks = new ArrayList<>();
    {
      Task task;
      while((task = queue.poll()) != null) {
        tasks.add(task);
      }
    }
    for(Task task: tasks) {
      service.submit(() -> {
        if(!task.finish()) offer(task);
      });
    }
}


Comparing a string that can hold a numeric value

this.getNo() - that.getNo()

may violate the contract of compareTo() if the subtraction overflows or underflows which is a likely event if the compared values are integer IDs of a large set of elements.

Instead you should explicitly compare the two:

return Integer.compare(this.getNo(), that.getNo());

Another way to avoid numerical comparison altogether is to format numbers as fixed-width strings with a DecimalFormat and compare the resulting strings (including some example code at the end):

import java.text.DecimalFormat;

public class SomeItem implements Comparable<SomeItem> {

    private static final DecimalFormat fmt = new DecimalFormat();

    static {
        int len = 19; // = String.valueOf(Long.MAX_VALUE).length();
        fmt.setMinimumIntegerDigits(len);
        fmt.setMaximumIntegerDigits(len);
        fmt.setPositivePrefix("+");
        fmt.setGroupingUsed(false);
    }

    private String id;

    public SomeItem(String id) {
        this.id = id;
    }

    public SomeItem(int no) {
        this(fmt.format(no));
    }

    public String getId() {
        return id;
    }

    public int getNo() {
        return Integer.parseInt(id);
    }

    @Override
    public int compareTo(SomeItem that) {
        return this.getId().compareTo(that.getId());
    }

    public static void main(String[] args)
    {
        java.io.PrintStream o = System.out;

        SomeItem[] items = new SomeItem[] {
            new SomeItem(1),
            new SomeItem(-1),
            new SomeItem(Integer.MAX_VALUE),
            new SomeItem(Integer.MIN_VALUE)
        };

        for (SomeItem i: items)
            System.out.format("id=%s, no=%+020d%n", i.getId(), i.getNo());
    }
}

Additionally, I based the amount of digits on long instead of int to provide room for (future) growth. I would have replaced the latter by the former entirely if Java converted the return value of #getNo() silently from long to int.


A more Pythonic way to iterate over a list with duplicate items

You could use enumerate to get the index. It makes the code both simpler and more efficient, as the linear search of index is avoided. I would also suggest unpacking t to (word, tag) to improve readability.

for ndx, (word, tag) in enumerate(wsj_list):
    if word in wordlist and tag == 'VN':
        print wsj[ndx-1:ndx+1], ndx


Regex to find addresses and phone numbers

Not sure about Java string catenation.
Below is your regex formatted and commented (by RegexFormat 5)

This puts it in expanded mode. The good thing is anybody can read it in
your source code for later reference.

Below is 2 versions. One a c++ normal catenation where newline \n are
added. Two a single quoted string where the newline is natural.

The nice thing about doing this in your code is you can always print it out
for debug purposes. It prints as a nice format.

"(?x)                                                               \n"
"   ( [^\\^]* )            # (1), Address type                      \n"
"   \\^                                                             \n"
"   ( [^\\^]* )            # (2), street1;street2;street3;street4;  \n"
"   \\^                                                             \n"
"   ( [^\\^]* )            # (3), City                              \n"
"   \\^                                                             \n"
"   ( [^\\^]* )            # (4), State                             \n"
"   \\^                                                             \n"
"   ( [^;]* )             # (5), Zip                                \n"
"   ;                                                               \n"
"   ( [^;]* )             # (6), Phone                              \n"
"   ;                                                               \n"

======================================

"(?x)
   ( [^\\^]* )            # (1), Address type
   \\^
   ( [^\\^]* )            # (2), street1;street2;street3;street4;
   \\^
   ( [^\\^]* )            # (3), City
   \\^
   ( [^\\^]* )            # (4), State
   \\^
   ( [^;]* )             # (5), Zip
   ;
   ( [^;]* )             # (6), Phone
   ;
"


How could I make my controller a little less hideous?

Based on your case your controller seems to be mixing multiple things at the same time. The total context is not clear but it seems this is a controller method in a controller that does more than this, correct?

In general I would suggest to see it different. An import is an object, so create a seperate controller for it: ImportsController. That can be a very standard controller:

Add: User add a new file, controller just sends it to Import model -> save. The model saves it in a temp file or whatever it needs to do. You can implement validation here already but you can also say: "A upload and saved file is ok. That is a correct creation of an import."

Pseudo code:

if(dataIncoming) {
    this->Import->save(data)
    //handle file save errors, no data received etc. All coming back from model which should take care of the validation.
    //redirect to edit
}

Edit: Next step is to review the import. Here you can ask the model to validate.

Pseudo code:

ON SAVE (if this is requested without a save/submit action just show data and validation results)
this->Import->parseFile(data) //validate

//show parse file issues to user if any
return View(processedValues);

if(no errors in parsefile) {
  //try database save
  Import->saveInDatabase
  //show validation errors if needed

  //if all ok you can redirect (or have user interaction) to delete
}

View: Always shows you the data of the import

Delete: Can be used to remove a wrong import upload (user uploaded file twice) or when import is done. You can validate this.

Here you can implement also a soft delete for example.

Pseudo code:

Import->delete

So as you see I would move all that file, tmpfile and other parts to the model by seeing an import as a standalone object. That makes it possible to have all encapsulated and also well testable. A controller method doing all steps is much harder to test. For example you would need to catch all different views rendered etc. I prefer to split it up.


Integer Factorization using the Trial Division Algorithm

A few comments :

Before writing any code, perform the computation manually. How would you do it for 20? You'd do something along the lines like :

let's try the first prime number : 2
is 2 a divisor of 20 ? yes, it is. 20 is 2*10 so let's add 2 to the list of divisors and let's focus on 10 now.
is 2 a divisor of 10 ? yes, it is. 10 is 2*5 so let's add 2 to the list of divisors and let's focus on 5 now.
let's consider the next prime number. It's 3. Oh, 3*3 is actually bigger than 5 so we won't be able to find any other prime factor smaller than 5 : let's add 5 to the list of divisors.
Try it yourself  with numbers such a 8, 100, 19....

Then, about your code : the first is I noticed that your loop condition is not right and you might get out of your array. Just try a value of n greater than 168 and you'll probably notice the issue.

If you want to follow the wiki page and to something like : for p in primes: if p*p > n: break what you really need to do is.

// Find prime factors
var n = 180;
var primeFactors = "";
// Trial division algorithm
for (var i = 0, p=primeNumbers[i]; i < primeNumbers.length && p*p<=n; i++, p=primeNumbers[i]) {
    while (n % p == 0) {
            primeFactors += " " + p + " ";
            n/=p;
    }
}
if (n>1)
{
    primeFactors += " " + n + " ";
}

document.getElementById("divSolution").innerHTML = primeFactors;

(Sorry for rewriting the whole code)


I would recommend using the .on() for click event delegation:

$('.wwd-filters').on('click', 'a', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    jQuery('.wwd-content-container .wwd-content-each').fadeOut();
    jQuery('.wwd-content-container .wwd-content-each.' + id).fadeIn();
});

This implementation grabs the id of the section you wish to show via the data attribute in the a elements:

Corporate

Commercial

Construction


I don't know what you mean by "more elegant", but I would recommend using pathlib.  This class provides for caching to be enabled/disabled for all files.  If the class is not initialized with a cache_dir, then caching is disabled.  If a cache_dir is provided, then __getitem__() loads data from cached files, if they exist.  Otherwise the data is calculated and cached.

class HeavyCalculationClass:
    def __init__(self, cache_dir=None):
        # sets the path to the cache directory if it was specified
        # and creates the cache directory if needed
        if cache_dir:
            self.cache = pathlib.Path(cache_dir)

            if not self.cache.is_dir():
                self.cache.mkdir()

        else:
            # empty cache path means ignore the cache
            self.cache = None

    def __getitem__(self, idx):
        # if caching is 'on' and this file is cached,
        # then load it
        if self.cache:
            cache_file = self.cache / f"{idx}.npy"

            if cache_file.is_file():
                data = numpy.load(cache_file))
                return data

        # otherwise calculate the data
        data = very_heavy_calculation()

        # cache the data if a cache path is set
        if self.cache:
            numpy.save(self.cache / f"{idx}.npy"), data)

        return data


Attempting to run multiple simulations of the Gillespie algorithm for a set of stochastic chemical reactions in less than 10 minutes

Pythonic code follows PEP8, mostly you need to stick to one type of variable format.
In Python they are:

snake_case variables. (functions are variables).
UPPER_SNAKE_CASE constants.
CammelCase classes.

There are a few white space conventions that you didn't follow, such as spaces around operators, and one space after commas.
But all in all you have some nice style.

First things first, don't use pylab. It's not supported,
in-fact I could only find one archive page about it that said to use matplotlib instead.

I assume that pylab.rand is the same as numpy.random.

Due to the above style concerns I found your code hard to read.
But there are also a lot of variables that are written and read once.
This makes the code harder to read, as then you have to remember senseless names such as u_event or kT.

I found the inner part of the while loop hard to read, instead split, the time changes and changes in p, d and dp, into two sections.
This made it easier for me to read and understand.

After doing the above I ran a profiler over the code, and using numpys array and cumsum were dramatic performance sinks.
To resolve this I implemented cumsum in Python, and used a Python array.

This lead to a 260% increase in speed on max_time = 0.1.
Note that I don't test the generation of P0_VEC as I made it a global variable in my code, but didn't in yours.
(So mine has an unfair advantage).

Also as @oliverpool says in the comments, you can get a speed up from using functions. (I put both my code and your code in a function, so the timings wern't extreemly unfair.)

I doubt that you can make the code much faster, as it's seems to be \$O(n)\$ already.
And with my change you are doing 309057 function calls, or 214921 a second.

import numpy as np
import matplotlib.pyplot as plt
random = np.random

# testing functions remove them from this script.
PROFILE = True
TIME = True

# Global constants
DELTA = 1e-3
SIM_NUM = 100
K_MINUS = 1e-3
K_CAT = 1 - 1e-3
ZETA = 1e-4
D = 10000
QP_VEC = np.logspace(-2, 1, 101, 10)
KAPPA_M = (K_CAT + K_MINUS) / ZETA
P0_VEC = QP_VEC / DELTA

def gillespie(max_time=0.01):
    p_tot_stoch = np.zeros((SIM_NUM, len(QP_VEC)))
    for len_qp_ind in range(len(QP_VEC)):
        qp = QP_VEC[len_qp_ind]
        p0 = int(P0_VEC[len_qp_ind])
        for sim_num_ind in range(SIM_NUM):
            p = p0
            d = D
            dp = time = 0

            while True:
                tot = [qp, ZETA * p * d, K_MINUS * dp, K_CAT * dp]
                for i in range(3):
                    tot[i + 1] += tot[i]
                kt = tot[-1]
                time += -np.log(1 - random.random()) / kt
                if time > max_time:
                    p_tot_stoch[sim_num_ind, len_qp_ind] = p + dp
                    break

                event_kt = random.random() * kt
                if event_kt < tot[0]:
                    p += 1
                elif event_kt < tot[1]:
                    p -= 1
                    dp += 1
                    d -= 1
                elif event_kt < tot[2]:
                    p += 1
                    dp -= 1
                    d += 1
                elif event_kt < tot[3]:
                    dp -= 1
                    d += 1

    return p_tot_stoch

if __name__ == '__main__' and PROFILE:
    import cProfile
    cProfile.run('gillespie()')

if __name__ == '__main__' and TIME:
    import timeit
    def gillespie_dot_one():
        return gillespie(0.1)
    def gillespie_one():
        return gillespie(1)
    print('gillespie(0.01)*100 = ', timeit.timeit(gillespie, number=100))
    print('gillespie(0.1)*10 = ', timeit.timeit(gillespie_dot_one, number=10))
    print('gillespie(0.1) = ', timeit.timeit(gillespie_one, number=1))

if __name__ == '__main__':
    p_tot_stoch = gillespie()
    p_mean = p_tot_stoch.mean(axis=0)
    p_std = p_tot_stoch.std(axis=0)

    plt.figure(0)
    plt.plot(QP_VEC, p_mean, marker=".")
    plt.errorbar(QP_VEC, p_mean, yerr=2 * p_std, xerr=None)
    plt.show()


An iterable implementation of LinkedList

Antipattern

It's not a good idea to expose the internal list nodes, and this is why:

public static void main(String[] args) {
    LinkedList<Integer> list = new LinkedList<>();
    list.add(123);
    // Make a loop:
    list.head.next = list.head;
    int i = 0;

    for (LinkedListNode<Integer> node : list) {
        ++i;

        if (i == 100) {
            break;
        }
    }

    System.out.println("i = " + i);
}

As the above snippet demonstrates, a user may restructure your linked list into a cycle in which iteration will never terminate. So the moral here is that:

hide implementation from the user!

First of all, make head a private field. Then, reimplement the iterator that iterates over values and not the internal nodes holding those values.

Additional field tail would not hurt, while keeping your add method a constant time operation.

Summa summarum

All in all, I had this in mind:

package concepts;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedListCR<E> implements Iterable<E> {

    private static final class LinkedListNode<E> {
        private E element;
        private LinkedListNode<E> next;

        LinkedListNode(E element) {
            this.element = element;
        }
    }

    private class LinkedListIterator implements Iterator<E> {

        private LinkedListNode<E> nextNodeToReturn = head;

        @Override
        public boolean hasNext() {
            return nextNodeToReturn != null;
        }

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Iterator exceeded.");
            }

            E ret = nextNodeToReturn.element;
            nextNodeToReturn = nextNodeToReturn.next;
            return ret;
        }

    }

    private LinkedListNode<E> head;
    private LinkedListNode<E> tail;

    public void add(E element) {
        LinkedListNode<E> newnode = new LinkedListNode<>(element);

        if (head == null) {
            head = newnode;
            tail = newnode;
        } else {
            tail.next = newnode;
            tail = newnode;
        }
    }

    @Override
    public Iterator<E> iterator() {
        return new LinkedListIterator();
    }

    public static void main(String[] args) {
        LinkedListCR<String> list = new LinkedListCR<>();
        list.add("hello");
        list.add("world");
        list.add("y'all");

        for (String s : list) {
            System.out.print(s + " ");
        }

        System.out.println();
    }
}

Hope that helps.


Splitting a Multi-FASTA file into individual files

There are a number of things in here which make the code somewhat hard to read. Also, there's a big bug.

Bug

You never reset the $seq_obj variable. As a result, each time you add a new file you are actually adding the new data to the end of the old data too. Thus, your files get bigger, and bigger, etc.

Thus, the third sequence in your input:

>gi|402898625|ref|XP_003912321.1| PREDICTED: cellular tumor antigen p53 [Papio anubis]
MEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSPLPSQAVDDLMLSPDDLAQWLTEDPGPDEAPRMSEATPPMAPTPAAP
KPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPAGSRAHSSHLKSKKGQSTSRHKKFMFKTEGPDSD

actually produces the output:

>gi|402898625|ref|XP_003912321.1| PREDICTED: cellular tumor antigen p53 [Papio anubis]
MEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSPLPSQAVDDLMLSPDDLAQWLTEDPGP
DEAPRMSEAAPHMAPTPAAPKPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPA
GSRAHSSHLKSKKGQSTSRHKKFMFKTEGPDSDMEEPQSDPSIEPPLSQETFSDLWKLLP
ENNVLSPLPSQAVDDLMLSPDDLAQWLTEDPGPDEAPRMSEAAPPMAPTPAAPSCMGGMN
RRPILTIITLEDSSGNLLGRNSFEVRVCACPGRDRRTEEENFRKKGEPCHELPPGSTKRA
LPNNTSSSPQPKKKPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPAGSRAHSS
HLKSKKGQSTSRHKKFMFKTEGPDSDMEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSP
LPSQAVDDLMLSPDDLAQWLTEDPGPDEAPRMSEATPPMAPTPAAPKPLDGEYFTLQIRG
RERFEMFRELNEALELKDAQAGKEPAGSRAHSSHLKSKKGQSTSRHKKFMFKTEGPDSD

which is the accumulation of all the previous inputs too. I have spent 20 minutes trying to figure out why my code is wrong.... but it's your code.

Better system

Additionally, the process you have 'batches' the data in one variable, and then dumps the variable when all the data is read.

If you reverse the algorithm, and open a file when the header arrives, and then write all the data (that's not a header) to that file, then the process would be simpler.

Additionally, you should use the 'diamond' magic filehandle <> for ease of use:

  The null filehandle <> is special: it can be used to emulate the
  behavior of sed and awk, and any other Unix filter program that takes
  a list of filenames, doing the same to each line of input from all of
  them. Input from <> comes either from standard input, or from each
  file listed on the command line.

So, if I break your code in to three sections. One section closes an open file, the next section starts a new file, and then a simple loop that checks to see whether it should start a new file, the code is much simpler.

Note also the general lack of global variables. Also, the 'id' line is not printed to the file when the file is created, but rather after the file is created as part of the 'normal' loop.

Finally, the process below copies the input lines unchanged from the input to the output. Your code 'reformats' the lines to 56 chars wide. This code does not do the reformat. I consider this to be a feature because of two things:

preserving input format is generally a good idea.
it saves having to chomp every line
it allows the data to be processed 1 line at a time, instead of batching it

If that does not work for you, then the code will have to be changed significantly.

#!/usr/bin/perl

use strict;
use autodie;

sub flushfile {
    my $file = shift;
    return undef unless $file;
    close $file;
    return undef;
}

sub makefile {
    my $control = shift;
    chomp $control;

    my @parts = split( /\h+/, $control, 2);
    my $f_name = $parts[0];
    $f_name =~ s/\|/_/g;
    $f_name =~ s/^>//;
    $f_name =~ s/\_$//;
    $f_name .= ".fasta";

    print "Processing $f_name from $control\n";

    open (my $ofile, '>', $f_name);
    return $ofile;
}

my $outfile;
while (<>) {

    if (/^>/) {
        $outfile = flushfile($outfile);
        $outfile = makefile($_);
    }

    $outfile or die "Unexpected input: $_";
    print {$outfile} $_;
}
flushfile($outfile);

Line Trimming version

I have written it again using a system that does the line sizing too.

The following code is different. It accumulates partial lines and the outputs them when they are full. It also needs to print the control line first because that cannot be line-trimmed.

#!/usr/bin/perl

use strict;
use autodie;

my $linesize = 60;

sub flushfile {
    my $file = shift;
    my $partial = shift;
    return undef unless $file;
    print {$file} $partial . "\n";
    close $file;
    return undef;
}

sub makefile {
    my $control = shift;
    chomp $control;

    my @parts = split( /\h+/, $control, 2);
    my $f_name = $parts[0];
    $f_name =~ s/\|/_/g;
    $f_name =~ s/^>//;
    $f_name =~ s/\_$//;
    $f_name .= ".fasta";

    print "Processing $f_name from $control\n";
    open (my $ofile, '>', $f_name);
    print {$ofile} $control . "\n";
    return $ofile;
}

sub addline {
    my $file = shift;
    my $part = shift;
    my $nxt = shift;
    $file or die "Unexpected input: $nxt";

    $part .= $nxt;
    while (length($part) >= $linesize) {
        my $front = substr ($part, 0, $linesize);
        #print "Printing $front\n";
        print {$file} ($front , "\n");
        $part = substr ($part, $linesize);
    }
    return $part;
}

my ($partial, $outfile);
$partial = "";
while (<>) {

    chomp;

    if (/^>/) {
        $outfile = flushfile($outfile, $partial);
        $outfile = makefile($_);
    } else {
        $partial = addline($outfile, $partial, $_);
    }
}
flushfile($outfile, $partial);


Brute force algorithm for printing all possible alphanumeric combinations

I must say that this looks pretty clean for a beginner.  There are no obvious problems with indentation and whitespace (common with beginners), which is a great start.  This especially makes it easier for others to read your code and for reviewers to focus on the more important aspects.

In most cases, don't use global variables:

char engWord[9];
char alphaNum[36] = {"0123456789abcdefghijklmnopqrstuvwxyz"};
int maxSize = sizeof(alphaNum);

This is highly discouraged because they're exposed to all the code and can be modified from anywhere, making maintenance and debugging much more difficult.  Instead, you can just put them in looper() since only that function uses them.  That way, if they're modified by accident, you'll know where to look.

In addition, alphaNum and maxSize should be const since they're not meant to be modified:

const char alphaNum[36] = {"0123456789abcdefghijklmnopqrstuvwxyz"};
const int maxSize = sizeof(alphaNum);

Some other issues seem to be with the naming:

There is one inconsistency: the naming convention of both non-main functions.  It's common for functions in C to start with a lowercase letter (either in camelCase or snake_case), so BruteForceInitializer() should be renamed as such.
It doesn't seem to make sense for BruteForceInitializer() to return bool if it's actually initializing something.  It looks like this function is doing most of the work anyway.  You could consider renaming this function in the verb form, which is common with functions (since they're performing a task).  It'll also help the check in main() to make more sense.
The name looper() doesn't quite seem clear, especially with the values it returns.  Based on the one comment in there, perhaps this function should also return bool.