Creating a concurrent/parallel ForEachAsync that can fail immediately or wait until enumeration is complete

CancaellationToken is a struct, not a class, so it can never be null. When people don't want to cancel stuff they just pass CancellationToken.None.
However note that If you change your cts assignment logic to something like parallelOptions.CancellationToken != CancellationToken.None you could hit a NullReferenceException when the cancellation token is None and FailImmediately is false. One simple way to make things work would be to just always assign cts = CancellationTokenSource.CreateLinkedTokenSource(parallelOptions.CancellationToken). Then you won't need the cts nullity check in the loop as well.
Instead of checking for IsCancellationRequested directly, it's a better practice to call cts.Token.ThrowIfCancellationRequested() - that way you will actually mark the task as canceled.
Instead of checking t.IsFaulted, it's a better practice to check if t.Exception != null.
Instead of iterating over t.Exception.InnerExceptions, you should iterate over t.Exception.Flatten().InnerExceptions`.
Creating the ConcurrentBag inside the task like you're doing now is not thread safe. I suggest just creating it upon declaration (instead of assigning null like you do now).
allDone issues:

allDone could be faulted if one of the body methods throw synchronously.
allDone would have IsCanceled set if cancellation was initiated either by the caller or by the FailImmediately logic
In either case, you won't get to the following line as await allDone would throw.

You don't need else after you throw new AggregateException.
If all you do is re-throw the exceptions at the end of the method, you could just await the Task.WhenAll and get the same behavior for free (without the Console.WriteLine though). To make this work, you'll have to re-throw the exception instead of adding its inner exceptions to the concurrent bag.


_validateForm can be reduced to

_validateForm() {
    this._resetErrors(); // Reset errors before validating
    return this._validateName() && this._validatePhone();
}


Constants naming

CONSTANT_HUNDRED is a bad name. It tells us its value, but not its role. Its value could be changed, making the whole thing useless, and in addition it is used in completely different contexts (queue size, and time out delay) so a user wishing to change one, might unknowingly alter the other.

You should declare two distinct constants:

private static final int QUEUE_DEFAULT_SIZE = 100;
private static final int LOCK_TIMEOUT_MILLIS = 100;

Usage:

    this.queue = new PriorityQueue<>(QUEUE_DEFAULT_SIZE);
    ...
    if (this.lock.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {

Dubious Exception

When setting fetchByCustomPriority to false on a Queue which does not support custom priority, there will be an exception. There shouldn't be, because the user isn't asking for the unavailable functionality

Timing out breaks Queue contract

When timing out on pop(), you would return null. according to the Queue contract this null value means, "there are no Objects in the Queue now", but that may be wrong. It might just be that too many Threads are waiting to get their turn and this one got timed out.

You should Throw a custom TimedoutException to differentate between timing out, and having an empty queue.

Same goes for push().

Wrong usage of ternary operator ?

In peek:

return this.fetchByCustomPriority ? this.queue.peek() : (this.customPriorityQueue != null ? this.customPriorityQueue.peek() : null)

if the condition is true, the first member is returned, otherwise the second is returned. I suspect if fetchByCustomPriority is true, you'll want to use the customPriorityQueue, so you need to invert arguments 2 and 3.

Uneven popping

In push, you push messages on both queues.

In pop(), you either pop the queue, or the customPriorityQueue. This means both queues act differently depending on if fetchByCustomPriority is true or false. This makes your object inconsistent and breaks Queue interface contract:

ComparableQueueElement comparableQueue = new ComparableQueueElement(aComparator);
comparableQueue.push(element);
comparableQueue.setFetchByCustomPriority(true);
comparableQueue.pop(); // returns element
comparableQueue.setFetchByCustomPriority(false);
comparableQueue.pop(); // returns element AGAIN!!

Your objects should stay consistent.

You could fix this by popping both queues in pop() method.

Or you could design your functionality in a way that it cannot fail...

Infallible DynamicPriorityQueue

Your fields are too rich for your object. The two queues could become out of sync. The best way to fix this is to have your objects only allow states which make sense.

Since you're describing an Object wich is a queue, let the only field by a queue.
I've changed to class to make it a bit more dynamic even, in that the comparator is no longer a fixed one. So now your can setFetchByCustomPriority(null) to fetch in-order, or setFetchByCustomPriority(comparatorA) and switch to setFetchByCustomPriority(comparatorB) on the fly.

import javax.naming.OperationNotSupportedException;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class DynamicPriorityQueue<ComparableQueueElement> implements IQueue<ComparableQueueElement> {
    private static final int CONSTANT_HUNDRED = 100;
    private final ReentrantLock lock;
    private PriorityQueue<ComparableQueueElement> queue;

    public DynamicPriorityQueue() {
        this(null);
    }

    public DynamicPriorityQueue(Comparator<ComparableQueueElement> comparator) {
        this.lock = new ReentrantLock();
        if (comparator != null) {
            this.queue = new PriorityQueue<ComparableQueueElement>(CONSTANT_HUNDRED, comparator);
        } else {
            this.queue = ew PriorityQueue<ComparableQueueElement>(CONSTANT_HUNDRED);
        }
    }

    public void setFetchByCustomPriority(Comparator<ComparableQueueElement> comparator) {
        // Just replace the existing queue
        PriorityQueue<ComparableQueueElement> newQueue = comparator == null ? new PriorityQueue(queue.size()) : new PriorityQueue(queue.size(), comparator);
        ComparableQueueElement element = queue.poll();
        while(element != null){
            newQueue.push(element);
            element = queue.poll();
        }
        queue = newQueue;
    }

    public void push(ComparableQueueElement t) throws InterruptedException, TimedOutException {
        if (this.lock.tryLock(CONSTANT_HUNDRED, TimeUnit.MILLISECONDS)) {
            try {
                this.queue.offer(t);
            } finally {
                this.lock.unlock();
            }
        } else {
            throw new TimedOutException();
        }
    }

    public ComparableQueueElement peek() {
        return this.queue.peek();
    }

    public ComparableQueueElement pop() throws InterruptedException, TimedOutException {
        ComparableQueueElement returnElement = null;
        if (this.lock.tryLock(CONSTANT_HUNDRED, TimeUnit.MILLISECONDS)) {
            try {
                return this.queue.pop();
            } finally {
                this.lock.unlock();
            }
        }
        throw new TimedOutException();
    }
}


Yes I think your usage of unique_ptr is correct. The only recommendation I would make is to use make_unique for construction:

explicit Queue(std::size_t space) :
    q_ptr(std::make_unique<T[]>(space)),
    capacity(space) {}

This answer provides motivation for its use. I've also used explicit to avoid implicit conversion from size_t to Queue. And I made use of a member initialization list.

I wrote the following tests using googletest:

TEST(QueueTester, testEmpty) {
    Queue<int> queue(0);
    EXPECT_EQ(0, queue.size());
}

TEST(QueueTester, testSingle) {
    Queue<int> queue(1);
    EXPECT_EQ(0, queue.size());
    queue.push(0);
    EXPECT_EQ(1, queue.size());
}

But neither passed. I corrected this by using the following:

int front_idx = 0;

And changing push:

template<typename T>
void Queue<T>::push(T value)
{
    if (back_idx - front_idx + 1 == capacity)
    {
        std::cerr << "Queue full\n";
        return;
    }
    q_ptr[++back_idx] = value;
}

I changed front and back to return references to the elements to allow the user to modify the contents. I also wrote overloads for returning const references to allow reading when the Queue is passed by const reference:

template<typename T>
T &Queue<T>::front()
{
    return q_ptr[front_idx];
}

template<typename T>
T &Queue<T>::back()
{
    return q_ptr[back_idx];
}

template<typename T>
const T &Queue<T>::front() const
{
    return q_ptr[front_idx];
}

template<typename T>
const T &Queue<T>::back() const
{
    return q_ptr[back_idx];
}

I further noticed that push, given a nonzero front_idx, will write past the end of the array pointed to by q_ptr. I took inspiration from this page and modified the code to store elements circularly around the array. Here is the final implementation:

#include <iostream>
#include <memory>
#include <cstddef>

template<typename T>
class Queue
{
    std::unique_ptr<T[]> q_ptr;
    int front_idx = 0;
    int back_idx = -1;
    std::size_t _size = 0;
    std::size_t capacity;
public:
    explicit Queue(std::size_t space) :
        q_ptr(std::make_unique<T[]>(space)),
        capacity(space)
    {
    }
    void push(T value);
    void pop();
    bool full();
    bool empty();
    T &front();
    T &back();
    const T &front() const;
    const T &back() const;
    std::size_t size() const;
};

template<typename T>
void Queue<T>::push(T value)
{
    if (full())
    {
        std::cerr << "Queue full\n";
        return;
    }
    back_idx = (back_idx + 1) % capacity;
    q_ptr[back_idx] = value;
    ++_size;
}

template<typename T>
bool Queue<T>::full()
{
    return _size == capacity;
}

template<typename T>
void Queue<T>::pop()
{
    if (empty())
    {
        std::cerr << "Empty queue\n";
        return;
    }
    q_ptr[front_idx] = T{};
    front_idx = (front_idx + 1) % capacity;
    --_size;
}

template<typename T>
bool Queue<T>::empty()
{
    return _size == 0;
}

template<typename T>
T &Queue<T>::front()
{
    return q_ptr[front_idx];
}

template<typename T>
T &Queue<T>::back()
{
    return q_ptr[back_idx];
}

template<typename T>
const T &Queue<T>::front() const
{
    return q_ptr[front_idx];
}

template<typename T>
const T &Queue<T>::back() const
{
    return q_ptr[back_idx];
}

template<typename T>
std::size_t Queue<T>::size() const
{
    return _size;
}


Possible undefined behaviour

There are several places that will lead to undefined behaviour.

In ajustar it can be possible that longitud < taminio. We will then happily copy into cadenaTemporal[i] where longitud < i < taminio. It's easy to create an example for this:

David::Cadena example("oh oh");
std::cin >> example;

So instead of taminio use both longitud as well as taminio as upper limit.

In operator [] (size_t indice), you return bufer[-1] on example[0] if the string hasn't been initialized. This should either get documented or checked.

Consistency

borrarBufer() should also set tamino to zero. That seems to be your "empty string" scenario.

Don't include the \0 in len()

If the string is empty, len() should return 0, not -1. strlen() or std::string::size() don't return the \0 either.

    const size_t len() const {
        return tamanio;
    }

Use common interface

operator= should return a Cadena&, not void. Similar, operator>> should return istream&, not void.

Follow the rule of five

You provide a custom constructor. Therefore, you should also provide

a custom copy constructor,
a custom move constructor,
a custom copy assignment,
a custom move assignment and
a custom destructor.

You don't provide any of them, but you should. For example, I cannot copy a Cadena at the moment. I have to write

Cadena my_copy(other.formaConstante())

Use copy and swap idiom for operator=

As soon as you have a copy constructor, you can write operator= very easy:

    void swap(Cadena & other) {
        std::swap(tamino, other.tamino);
        std::swap(bufer,  other.bufer);
    }

    Cadena& operator=(const char* cadena) {
        Cadena temporary(cadena);
        swap(cadena);
        return *this;
    }

Provide push(char) to add single characters

This will make operator>> a lot simpler.

Use a capacity

Your operator>> is \$\mathcal O(n^2)\$ since you have to realloc for every single char. Instead, allocate more memory than you actually need. Or use std::vector for your internal memory instead, it will take care of that automatically.


Fastest way to determine if a number is perfect square

It is indeed very simple and straightforward. The time complexity is however \$(O(\sqrt n)\$. A binary search variation will do it in \$O(\log n)\$ time. Along the lines of the pseudocode:

    while lo < hi
        mid = lo + (hi - lo)/2
        square = mid * mid
        if square == n
            return true
        if square < mid
            lo = mid
        else
            hi = mid
    return false

Depending on the expected magnitude of \$n\$ it may or may not worth the effort. In the interview setting (no restrictions on \$n\$) I would go for the binary search.

if inside a tight loop usually hurts performance. Consider

    while (n > 0) {
        n -= i;
        i += 2;
    }
    return n == 0;


Efficent way to Query a DB and write to text file - Large Recordset

You can simplify the code greatly without loosing any performance, more likely gaining instead.

There is no need to use StringBuilder - you can write directly to the StreamWriter - it will be faster since there will be no need of copy the whole data twice.

Next, there is no need to use MemoryStream - you are using it to buffer data before writing it to the disk. The same can be achieved by specifying the buffer size when creating FileStream. You should play around with the buffer size to see what is fastest on your environment - usually 4KB is used, in the sample below it is 1MB, but you have to try it on your hardware.

You should also play around with the options how to open FileStream. You should try what impact Asynchronous and WriteThrough has on your solution.

Of course, as the other answer proposed, separating reading from database and writing to the file in two threads might work as well. Try and measure three separate scenarios - just reading from the database (measure separately the query (ExecuteReader() and first Read() and then reading the other rows - because it might be that most of the time is spending to initially execute the query, not to iterate through the data), just writing to the file (dummy data) and then combined. This way you will see if there is actual reason to put the two operations in parallel.

Dim conn As New OracleConnection()
...
Sub DBExecuteQueryWriteToFile(ByVal SQLCommand As String, ByVal FileName As String, Optional ByVal Delimiter As String = ",")

    Dim cmd = New OracleCommand(SQLCommand, conn)
    Dim bufferSize = 1024*1024; // 1Mb

    If File.Exists(FileName) Then
        File.Delete(FileName)
    End If

    Using FileObject As New FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, bufferSize)
    Using StreamWriterObj As New StreamWriter(FileObject)
    Using Reader As OracleDataReader = cmd.ExecuteReader()
        Dim FieldCount As Integer = Reader.FieldCount - 1

        Do While Reader.Read()
            StreamWriterObj.Write(Reader.Item(0))
            For i = 1 To FieldCount
                StreamWriterObj.Write(Delimiter)
                StreamWriterObj.Write(Reader.Item(i))
            Next
            StreamWriterObj.WriteLine();
        Loop

    End Using
    End Using
    End Using
End Sub

P.S. few other issues in your code:

StringBuilder().ToString().ToCharArray() - no need to convert to char array.
new StringBuilder() - instead of reusing the memory already allocated to the existing builder, you are throwing that away and creating new one.
MStream.Seek() - you are seeking to the beginning of the stream but are not setting Length to 0. So if the second block written there is smaller than first one, junk data will be written to the file.


As some other stated I am also convinced that there is less or no beneficial usage for enriching a simple associative map to throw an exception if an element is not found.

I suggest to go with a use case specific exception handling as the context is important where a not available value is an exceptional case.


Displaying text extracted from XML using PHP simplexml

My preference is to leave the html escaping until the last minute.

Here are some changes you could make to simplify your code.

Code should work but there is no link between $xml and $items, so unable to test.

<?php

$file = 'xml/noticias.xml';

// guard clause exit early, instead of last
if (!file_exists($file)) {
    // do something... throw error message
    throw new \Exception('File does not exist');
}

$xml = simplexml_load_file($file);

foreach ($items as $item) {
    $titulo = $item->titulo;
    $desc = $item->desc;
    $url = $item['url'];

    // use mb_ function as you are dealing with unicode text, strlen will report incorrect length
    if (mb_strlen($titulo) < 3) {
        $titulo = 'Título em falta';
    }
    // no need to reassign value to itself
    //else {
    //    $titulo = $titulo;
    //}

    if (mb_strlen($desc) < 3) {
        $desc = 'Descrição em falta';
    }
//    else {
//        $desc = $desc;
//    }

    // not expecting url to be unicode
    if (strlen($url) >= 3) {
        $url = "noticia/{$url}";
    } else {
        $url = null;
    }

    $h3 = $titulo;

//        $h3 = '
' . $titulo . '
';
//    } else {
//        $h3 = '
' . $titulo . '
';
//    }
    ?>

                <?php if ($url): ?>
                    <a href="<?php echo $url; ?>">
                <?php endif; ?>

<?php echo htmlentities($h3); ?>

                <?php if ($url): ?>

                <?php endif; ?>

<?php echo htmlentities($desc); ?>

    <?php
}


You might want to ask a more specific question on Stack Overflow if you don't know if it works.

In the meantime, you should catch the most specific exception you can, so except OSError instead of a bare except.   Also, you should use exception code to mitigate a problem and continue, so more like:

try:
    shutil.rmtree('c:/guna/newCAT1')
    print("dir newCAT1 deleted")
except OSError:
    pass  # do nothing on this exception.
# continue with making the directory.  The exception statement is complete

or, if you read the documentation for shutil.rmtree:

shutil.rmtree('c:/guna/newCAT1', ignore_errors=True)
print("dir newCAT1 deleted")
os.mkdir('c:/guna/newCAT1')
print("dir newCAT1 created")
fileIN=open('c:/guna/newCAT1/secretMSG.txt','w' )
fileIN.writelines("the dog is green")
fileIN.close()


Private Sub GetLastRow()

I like that it's Private. Other than that... a Sub doesn't "get" anything; a Sub does something - this is a side-effecting procedure with the lipstick of a Function. A pig with lipstick is still a pig though. Let's look at how it's implemented:

 'Step 1: Declare Your Variables.
  Dim LastRow As Long

 'Step 2: Capture the last used row number.
  LastRow = Cells(Rows.Count, 8).End(xlUp).Row

 'Step 3: Select the next row down
  Cells(LastRow, 8).Offset(1, 0).Select

These comments are noise. Comments that say what the code does are useless clutter, unless the code is absolutely unreadable... in which case the solution is to improve the code's readability. Good comments say why, not what. Bad comments should be removed.

There are a number of serious issues with that procedure. Cells and Rows both implicitly refer to the active worksheet, which means if the user happens to activate another sheet while the code is running, everything falls apart (I see you've addressed that elsewhere though) - it also falls apart if other code activates another sheet than the one that's expected to be active though. And given how your entire code [ab]uses Select and Activate, that's a real concern.

This would be my GetLastRow:

Private Function GetLastRow(ByVal sheet As Worksheet, Optional ByVal fromColumn As Long = 1) As Long
    GetLastRow = sheet.Cells(sheet.Rows.Count, fromColumn).End(xlUp).Row
End Function

No side effects. Returns ("gets") a value. Says what it does, does what it says: it returns the last row; a better name for a side-effecting procedure that selects the first empty row could be SelectFirstNonEmptyRowInColumnH. Too specific? It's exactly what it does though. The problem isn't the specific name - the problem is what the procedure does.

The benefits of using non-side-effecting functions are numerous: first, I can call my function off any worksheet (not just the active one), make it look at any column, and I can call it 20 times in a row on 20 different sheets, not once will my Application.Selection be affected.

It also makes code that reads exactly like what it does:

Call GetLastRow

Regardless of the Call keyword being useless here (or anywhere else - it's been obsolete since the advent of the implicit procedure call syntax... over 20 years ago), reading the above line of code has a very different feel than reading this one:

sheet.Cells(GetLastRow(sheet, 8), 8).Offset(1).Select

More complicated? Ok then, let's split it up:

Const importantColumn As Long = 8

Dim lastRow As Long
lastRow = GetLastRow(sheet, importantColumn)

sheet.Cells(lastRow, importantColumn) _
     .Offset(1) _
     .Select

By not hiding .Select operations behind a side-effecting procedure call [disguised as a function], we make it clear that we're tampering with the workbook's state.

There's only ever ONE reason to use .Select in VBA code: when you want to set the current selection for the user.

Using .Select for any other reason, is asking for your code to be as slow as Excel VBA code can get, not to mention extremely frail and bug-prone.

Working off Selection is dangerous. In fact, your code can very easily blow up on the 2nd executable statement:

If Selection.Rows.Count > 1 Then

How? You assume Selection is a Range. But Selection can be a Shape. Selection can be a Chart, or a Series. Selection can be Nothing. Each of these make execution jump to your ErrorHandler subroutine, to display a cryptic error message in the debug/immediate pane, that doesn't tell anything about what's going on, where, or why:

  Error number: 91 Object variable or With block variable not set.

Or

  Error number: 438 Object doesn't support this property or method.

But programmers making assumptions (Selection is a Range?) are a dangerous thing: you'll likely never encounter these error messages, because when you test your macro yourself, Selection will be a Range. Things get more fun when it's an actual user running your code though. Users are particularly bad at wording useful bug reports - most of the time they sound like a downvoted Stack Overflow question that's accumulating "unclear what you're asking" close votes:

  I clicked your macro button but nothing happens, it's not working.

Good luck figuring that one out!

Instead, you could separate responsibilities, increase the level of abstraction, and have smaller procedures that do one thing - and have few reasons to fail. Then you could include the procedure's name in your Debug.Print statement, and at least you'd know which step blew up.

I'd review the actual crux of the code, but the [lack of] indentation makes my head spin, so instead I'll point you to Rubberduck and its Smart Indenter tool (disclaimer: I manage this open-source project; credits to @Comintern for most of the work on the Smart Indenter port), which can help you fix this.

Please read: How to avoid using Select in Excel VBA macros.


Entering and authorizing Twitter credentials

Generally Rubyists define methods in the underscore-lowercase pattern: def twitter_auth, def send_tweet. Additionally most that I've encountered prefer to drop the () from method calls: twitter_authenticate creds; send_tweet creds

Otherwise this looks OK!


I think the problem could be, that your algorithm isn't exactly a selection sort but rater a bubble sort. They are very similar, but where bubble sort swaps every two elements when the left is smaller than the right (descending order), selection sort defers swapping to after the inner loop is finished and then only swaps the last found candidate with the index'th element.

To accomplish that in your algorithm, you can modify it as follows:

function selectionSort(array) {
  let index = 0;
  let length = array.length;
  let nextElementIndex = 0;

  while (index < length - 1) {
    nextElementIndex = index + 1;

    let maxIndex = index; // This will hold the index of the possible last candidate for swapping.

    while (nextElementIndex < length) {
      if (array[maxIndex ] < array[nextElementIndex]) {
        // Instead of swapping here, only the index of the candidate is saved.
        maxIndex = nextElementIndex;
      }
      nextElementIndex++;
    }

    // And finally: if any element to the right of index is greater than the element at index then swap.
    if (maxIndex != index) {
      [array[index], array[maxIndex ]] = [array[maxIndex ], array[index]];
    }

    index++;
  }
}

A suggestion that may improve readability could be to use for-loops instead of while -loops


Probably there is no need to refactor the method as it represents quite clear decision tree. Breaking it down into smaller methods will cause readability problems.

Just make sure you have unit tests covering each outcome and that there are no cases, which the code doesn't handle.

If you definitely want to refactor, I propose to add a method like this:

def _check_log_writesums(cond, logmessage, rewrite=True):
    if cond:
        if logmessage:
            self.logger.debug(logmessage)
        if rewrite:
            self.write_checksums()
        return True
    return False

Then you can call it like this:

    if filename in stored_checks:
        return self._check_log_writesums(stored_checks[filename] != checksum,
                                         "",
                                         rewrite=True)

Maybe the name can be better (_update_checksums or _do_write_checksums).


Don't repeat yourself

Your code violates the DRY principle. If we replace

germanNumeralShort = parseTimeM True defaultTimeLocale
    "%-d.%-m.%y" (t2s datestring) :: Maybe UTCTime
isoformat = parseTimeM True defaultTimeLocale
    "%Y-%m-%d" (t2s datestring) :: Maybe UTCTime
...

with

parse format = parseTimeM True defaultTimeLocale format (t2s datestring)

germanNumeralShort = parse "%-d.%-m.%y"
isoformat          = parse "%Y-%m-%d"
...

then we immediately notice that we use parse on all formats after another till we find a suitable one.

This can be modelled with map parse, e.g.

map parse
    [ "%b %-d, %Y"
    , "%B %-d, %Y"
    , "%b. %-d, %Y"
    , "%-d.%-m.%Y"
    , "%-d.%-m.%y"
    , "%Y-%m-%d"
    ]

We could use <|> alternatively, e.g.

parse "%b %-d, %Y" <|> parse "%B %-d, %Y" <|> ...

but that's less flexible than the list approach.

Use asum to get a single Maybe from a list of Maybes

To get a single Maybe a from [Maybe a], we can use asum. To get the errorT, we just need to pattern match on a single result and end up with

readDate3 :: Text ->   UTCTime
readDate3 datestring = case result of
   Nohing -> errorT ["readDate3", datestring, "is not parsed"]
   Just t -> t
 where
   parse format = parseTimeM True defaultTimeLocale format (t2s datestring)
   result = asum . map parse $
        [ "%b %-d, %Y"
        , "%B %-d, %Y"
        , "%b. %-d, %Y"
        , "%-d.%-m.%Y"
        , "%-d.%-m.%y"
        , "%Y-%m-%d"
        ]

As the current strings are missing some documentation, we could introduce additional types to remedy that:

data DateFormat = ShortMonth
                | LongMonth
                | MonthPoint
                | GermanNumeral
                | GermanNumeralShort
                | ISOFormat

toFormatString :: DateFormat -> String
toFormatString f = case f of
    ShortMonth -> "%b %-d, %Y"
    LongMonth  -> "%B %-d, %Y"
    MonthPoint -> "%b. %-d, %Y"
    -- other left as an exercise

We can also use fromMaybe to get rid of the last pattern match and end up with

import Data.Foldable (asum)
import Data.Maybe (fromMaybe)

readDate :: Text ->   UTCTime
readDate datestring =
    fromMaybe (errorT ["readDate", datestring, "is not parsed"]) $
      asum . map parse $
        [ ShortMonth
        , LongMonth
        , MonthPoint
        , GermanNumeral
        , GermanNumeralShort
        , ISOFormat
        ]
 where
   parse format = parseTimeM True defaultTimeLocale (toFormatString format) (t2s datestring)


A look at the second plot in the post shows that something has gone wrong. There are four points in a line here:

This shouldn't be possible, since "points that create a straight line when plotted" have been removed. How did this happen? A look at the \$x\$ axis shows the cause. The first plot has the \$x\$ coordinate running from 0 to 96, but the second plot has the  \$x\$ coordinate running from 0 to 43, because the \$x\$ values for the omitted points have also been omitted.

To get the correct plot you have to remember the original \$x\$ coordinates and mask them at the same time as you mask the \$y\$ values, like this:

x = np.arange(len(pat))[less_than_180]
y = pat[less_than_180]
plt.plot(x, y)
plt.plot(x, y, 'bo')

See below for the corrected plot.
The name degrees could be better chosen — there are already functions math.degrees in the standard library, and numpy.degrees in NumPy, and a reader might well imagine that your function does something similar. A name like vertex_angle would be better (see Wikipedia).
The line:

pattern = pattern[1:-1] # <- No angles between the end points

discards the endpoints of the data. But surely you want to keep the endpoints in the plot?
Given three points \$A, B, C\$, the code finds the vertex angle \$∠ABC\$ and compares it with 180°. An alternative approach is to linearly interpolate between the endpoints, finding \$B′ = ½(A + C)\$, and see if \$B′\$ is close enough to \$B\$. Like this:

# Boolean mask for the points we are going to plot.
mask = np.ones_like(pattern, dtype=bool)

if len(pattern) > 2:
    # Linearly interpolate between points that are two apart.
    interpolants = (pattern[:-2] + pattern[2:]) / 2

    # Don't plot points that are equal to their interpolant.
    mask[1:-1] = interpolants != pattern[1:-1]

x = np.arange(len(pattern))[mask]
y = pattern[mask]
plt.plot(x, y)
plt.plot(x, y, 'bo')
plt.show()

Here's the resulting plot:

If your data is floating-point then you will need some tolerance in the comparison of points to their interpolants. For example, you might use numpy.isclose:

# Don't plot points that are close their interpolant.
mask[1:-1] = ~np.isclose(interpolants, pattern[1:-1])


I don't know what you mean about 'good ruby'. I show you a object-oriented version.
Instead of

romanize(4)

you can call

4.roman

My solution is similar to your solution. It is Hash-oriented, so you need ruby 1.9.

I also tried to use a array in array solution with ROMAN_NUMBERS.each do |value, letter| without any problem (I'm not sure if it is only ruby 1.9).

class Fixnum
  ROMAN_NUMBERS = {
    1000 => "M",
     900 => "CM",
     500 => "D",
     400 => "CD",
     100 => "C",
      90 => "XC",
      50 => "L",
      40 => "XL",
      10 => "X",
        9 => "IX",
        5 => "V",
        4 => "IV",
        1 => "I",
  }

  def roman
    n = self
    roman = ""
    ROMAN_NUMBERS.each do |value, letter|
      roman << letter*(n / value)
      n = n % value
    end
    return roman
  end
end

With ruby 1.8 you may add use ROMAN_NUMBERS.sort.each.

As an alternative, you can use a recursive solution:

class Fixnum
  ROMAN_NUMBERS = {
    1000 => "M",
     900 => "CM",
     500 => "D",
     400 => "CD",
     100 => "C",
      90 => "XC",
      50 => "L",
      40 => "XL",
      10 => "X",
        9 => "IX",
        5 => "V",
        4 => "IV",
        1 => "I",
        0 => "",
  }
  def roman
    return '' if self == 0
    ROMAN_NUMBERS.each do |value, letter|
      return ( letter * (self / value)) << (self % value).roman if value <= self
    end
    return (self % value).roman
  end
end

I don't recommend the recursive solution. Each number must start again with M.

A little testcode, to check the results:

require 'test/unit'

class NumberTest < Test::Unit::TestCase
  def test_0; assert_equal('',0.roman); end
  def test_1; assert_equal('I',1.roman); end
  def test_2; assert_equal('II',2.roman); end
  def test_3; assert_equal('III',3.roman); end
  def test_4; assert_equal('IV',4.roman); end
  def test_5; assert_equal('V',5.roman); end
  def test_6; assert_equal('VI',6.roman); end
  def test_7; assert_equal('VII',7.roman); end
  def test_8; assert_equal('VIII',8.roman); end
  def test_9; assert_equal('IX',9.roman); end
  def test_10; assert_equal('X',10.roman); end
  def test_11; assert_equal('XI',11.roman); end
  def test_12; assert_equal('XII',12.roman); end
  def test_13; assert_equal('XIII',13.roman); end
  def test_14; assert_equal('XIV',14.roman); end
  def test_15; assert_equal('XV',15.roman); end
  def test_16; assert_equal('XVI',16.roman); end
  def test_20; assert_equal('XX',20.roman); end
  def test_30; assert_equal('XXX',30.roman); end
  def test_40; assert_equal('XL',40.roman); end
  def test_50; assert_equal('L',50.roman); end
  def test_60; assert_equal('LX',60.roman); end
  def test_70; assert_equal('LXX',70.roman); end
  def test_80; assert_equal('LXXX',80.roman); end
  def test_90; assert_equal('XC',90.roman); end
  def test_99; assert_equal('XCIX',99.roman); end
  def test_100; assert_equal('C',100.roman); end
  def test_200; assert_equal('CC',200.roman); end
  def test_300; assert_equal('CCC',300.roman); end
  def test_400; assert_equal('CD',400.roman); end
  def test_500; assert_equal('D',500.roman); end
  def test_600; assert_equal('DC',600.roman); end
  def test_900; assert_equal('CM',900.roman); end
  def test_1000; assert_equal('M',1000.roman); end
  def test_2000; assert_equal('MM',2000.roman); end
  def test_2003; assert_equal('MMIII',2003.roman); end
end


From a once over:

I would not use _ to prefix all your variables, it would make more sense to either actually use private variables or write a comment that this variables should not be touched by callers
pauseTimer lies, since you toggle. I would call it toggleTimer or startStopTimer
Your code is well commented except for //toggles the _paused variable which is kind of obvious ;)
Besides some missing semicolons, your code looks fine on JsHint.com
I think in callTimer you could have called your paramater callback, then do callback = callback || this.callback and then use callback in your closure.

All in all, good, re-usable code.

For my own purposes I would probably make the private variables really private and move the functions out of prototype into the constructor. That would increase memory footprint, but I would never use more than a dozen of these at the same time.


Throttling promise execution (API requests, etc)

The most important advice I can offer is to turn on strictNullChecks and noImplicitAny. Without these settings, TypeScript's ability to warn you about problems in your code is severely limited.

Doing this first, TypeScript reveals several problems (Ignoring errors from your tests, you just need a ! assertion):

test.ts:19:21 - error TS2345: Argument of type 'undefined' is not assignable to parameter of type 'never'.

19     this.stack.push(executor);
                       ~~~~~~~~

test.ts:24:11 - error TS2322: Type 'undefined' is not assignable to type '() => Promise<string>'.

24     const op: () => Promise<string> = this.stack.shift();
             ~~

None of these errors are particularly difficult to fix. First, we need to define the type of stack. Right now, as it is assigned [], the inferred type is [] (an empty tuple). If we look at the type of functions added to it in add, we see that a function of type () => void is added, so declare that.

class RequestThrottle {
  stack: (() => void)[] = [];

This change will change the reported errors slightly, giving us more useful error messages.

test.ts:19:21 - error TS2345: Argument of type 'undefined' is not assignable to parameter of type '() => void'.

19     this.stack.push(executor);
                       ~~~~~~~~

test.ts:24:11 - error TS2322: Type '(() => void) | undefined' is not assignable to type '() => Promise<string>'.
  Type 'undefined' is not assignable to type '() => Promise<string>'.

24     const op: () => Promise<string> = this.stack.shift();
             ~~

The next problem is caused by let executor;. Since no type has been declared, TypeScript will implicitly type the variable as any. You could fix this by typing executor as (() => void) | undefined and then asserting that it has been set after executing the promise, but it is simpler to just add the function to stack within the promise.

At the same time, declaring the add function as a property instead of an arrow function on the class (like you did with pullAndExecute) is kind of weird. I'd prefer this style:

class RequestThrottle {
  stack: (() => void)[] = [];
  spacing = 1000;

  add = (req: () => Promise<string>): Promise<string> => {
    return new Promise<string>((resolve) => {
      this.stack.push(() => {
        resolve(req());
      });
    });
  };

This resolves the first issue, the second issue can be easily resolved by dropping the erroneous Promise<string> type on op in the pullAndExecute function.

class RequestThrottle {
  stack: (() => void)[] = [];
  spacing = 1000;

  add = (req: () => Promise<string>): Promise<string> => {
    return new Promise<string>((resolve) => {
      this.stack.push(() => {
        resolve(req());
      });
    });
  };

  pullAndExecute = () => {
    const op = this.stack.shift();
    if (op) op();
  };

  interval = setInterval(this.pullAndExecute, this.spacing);

  stop = () => clearInterval(this.interval);
}

Next we must consider the access level of each member. add should obviously be public. Similarly, it makes sense for stop to be public. But stack, spacing, interval and pullAndExecute are all implementation details. Users of this class shouldn't need to care (or even know) that they exist. They should all be marked as private.

Despite this... users might want to be able to specify spacing when using the class. There are two ways to meet this need. Either let the user specify it in the constructor, or add a start method that starts the interval. I prefer the start solution.

class RequestThrottle {
  private stack: (() => void)[] = [];
  private interval = 0;

  add = (req: () => Promise<string>): Promise<string> => {
    return new Promise<string>((resolve) => {
      this.stack.push(() => {
        resolve(req());
      });
    });
  };

  private pullAndExecute = () => {
    const op = this.stack.shift();
    if (op) op();
  };

  start = (spacing = 1000) => {
    this.stop();
    this.interval = setInterval(this.pullAndExecute, spacing);
  };

  stop = () => clearInterval(this.interval);
}

Note that in the start method I call stop first. This is to ensure that we don't have multiple queue consuming clocks running at once.

Now, you mentioned that you wanted this class to work with a Promise<R>. As written, it will only let you use Promise<string>. Thankfully, this is a trivial fix, we just need to make the add method generic.

  add = <R>(req: () => Promise<R>): Promise<R> => {
    return new Promise<R>((resolve) => {
      this.stack.push(() => {
        resolve(req());
      });
    });
  };

With all these changes together, the class becomes:

class RequestThrottle {
  private stack: (() => void)[] = [];
  private interval = 0;

  add = <R>(req: () => Promise<R>): Promise<R> => {
    return new Promise<R>((resolve) => {
      this.stack.push(() => {
        resolve(req());
      });
    });
  };

  start = (spacing = 1000) => {
    this.stop();
    this.interval = setInterval(this.pullAndExecute, spacing);
  };

  stop = () => clearInterval(this.interval);

  private pullAndExecute = () => {
    const op = this.stack.shift();
    if (op) op();
  };
}

A couple other notes:

Don't use for .. in to iterate over arrays. Use for .. of instead.

for (const i of [1, 2, 3, 4, 5, 6]) {
  throttle.add(enqueue(i)).then(console.log);
}

Don't make promises that can never be resolved or rejected. In addChild, the promise will never be resolved.
Should RequestThrottle throttle based on promise starts or promise resolves? Currently it throttles based on the initial call of a function... but if that function takes more than spacing to resolve, you could have multiple promises waiting at once. This might be desired, but it is something to consider.


Method that returns description attribute of enum value

Type type = input.GetType();
   MemberInfo[] memInfo = type.GetMember(input.ToString());

You should use more meaningful variable names like enumType and enumMembers and your code could use some more LINQ and vars.

if (memInfo != null && memInfo.Length > 0)

This null check is unnecessary. The docs says about GetMember:

  An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, an empty array.

So we can remove one null check and test only the description-attribute and turn it into a ternary operator:

public static string GetDescription(System.Enum value)
{
    var enumMember = value.GetType().GetMember(value.ToString()).FirstOrDefault();
    var descriptionAttribute =
        enumMember == null
            ? default(DescriptionAttribute)
            : enumMember.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute;
    return
        descriptionAttribute == null
            ? value.ToString()
            : descriptionAttribute.Description;
}

  I think this code can be more elegant

With C# 6 it can be just a small chain of method calls...

public static string GetDescription(Enum value)
{
    return
        value
            .GetType()
            .GetMember(value.ToString())
            .FirstOrDefault()
            ?.GetCustomAttribute<DescriptionAttribute>()
            ?.Description
        ?? value.ToString();
}


Append the contents of latest Stackage nightly build to the global cabal config file

The unappend_cabal_config can be more efficient and more elegant using a generator:

Reading all the lines from the file when you may only need the ones until one containing "Stackage" is wasteful
It's good to avoid the index variable in loops when possible

Like this:

def unappend_cabal_config():
    with open(cabal_config_path) as fh:
        for line in fh:
            if 'Stackage' in line:
                return
            yield line


Python class assignment simplification for d&d character creator

Duplicate code is almost always better replaced with a function. Consider a class method which alters an ability by a given value. This can be achieved (most cleanly, I believe) with getattr and setattr. Calling getattr(x,'spam') will return the value x.spam, and similarly setattr(x,'spam',n) will set the value of x.spam to n.

This, combined with a helpful message when the user enters something unexpected, would yield code like that below:

def ability(self):
    choice = raw_input("Leveling up: do you want to increase 'one' score by two, or 'two' scores by one each?")
    while True:
        if choice == "one":
            stat = raw_input("Which ability do you want to increase by two?")
            self.alter_stat(self, stat, 2)

            break
        elif choice == "two":
            first_stat = raw_input("Which first ability do you want to increase by one?")
            self.alter_stat(self, first_stat, 1)
            second_stat = raw_input("Which second ability do you want to increase?")
            self.alter_stat(self, second_stat, 1)

            break
        else:
            print("Hmm, I don't understand. Enter 'one' or 'two' next time!")

def alter_stat(self, stat, alteration):
    assert stat in ['charisma', 'constitution', 'dexterity', 'intelligence', 'strength', 'wisdom'], "That's not a valid ability!"
    old_value = getattr(self, stat)
    setattr(self, stat, old_value + alteration)


Gather first letter from each string in a list of strings

Well a few thoughts, of all String = [Char] so we could really give the signature

firstLetters :: [String] -> String

Whether you think this is better is a matter of taste. Second, you should take a look at

Data.Maybe.mapMaybe :: (a -> Maybe b) -> [a] -> [b]

It's exactly what you'd expect, it applies a function to Maybes and prunes out the Nothings. This simplifies the slightly ugly concat bit.

 firstLetters = mapMaybe safeHead

Much clearer :) In the interest of teaching you to fish, here's how I found the name of mapMaybe


Iterate through python iterable in chunk of n

Your code has a significant bug. If I ask it to chunk a list with None at a multiple of n plus 1 spot (c * n + 1), it will not return the rest of the list

xs = list(range(75, 90))
xs[5] = None
print([list(c) for c in iterchunks(iter(xs), 5)])
# Outputs [[75, 76, 77, 78, 79]]
# Expected [[75, 76, 77, 78, 79], [None, 81, 82, 83, 84], [85, 86, 87, 88, 89]]

To resolve this, use the standard practice of trying something, and asking for forgiveness later. I would suggest either an iterable you build up. Still this seems like a case of reinventing the wheel, it is unfortunate python doesn't have it built in to the itertools library. It does define grouper in the docs of itertools, which is kinda what you want, except it pads a fill value to the end of the iterable.

def chunk(it, n):
    try:
        while True:
            xs = []  # The buffer to hold the next n items
            for _ in range(n):
                xs.append(next(it))
            yield xs
    except StopIteration:
        yield xs

This is the code from the itertools docs here, with one amendment, to yield from instead of returning the iterable it creates

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    yield from zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue)


I only have a few minor suggestions, but none are hard-line.

You have a space between the else if and open parenthesis. I don't like this style of removing spaces around keywords and from between ) and { as it becomes hard to read without syntax highlighting (even with it).
Instead of too few/many arguments which isn't very specific, have a single exception that says how many were provided and how many are required.

if (colors.length != 3) {
    throw new MalformedColorException("Color requires 3 values, got " + colors.length);
}

Moving the individual value parsing to a separate method would allow for more checks (range, sign, etc) and allow specifying which color was incorrect in the exception.

return new Color(
    parseComponent("red", colors[0]),
    parseComponent("green", colors[1]),
    parseComponent("blue", colors[2])
);

private int parseComponent(String name, String value) {
    try {
        int parsed = Integer.parseInt(value);
        if (parsed < 0 || parsed > 255) {
            throw new MalformedColorException(
                    name + " component \"" + value + "\" out of range");
        }
        return parsed;
    } catch (NumberFormatException e) {
        throw new MalformedColorException(
                name + " component \"" + value + "\" must be an integer");
    }
}


Questions

  Is the factory function approach sound?

Yes it is by far the best for objects that will have more than one long lived instance. Not so good for many short lived instances in which case use prototyped factory to reduce instantiation overheads, but lose some flexibility when protecting state.
For single instance object use a singleton.

Freeze

For added state safety freeze the returned object so that it can not have its state mutated

return Object.freeze({add, remove, getFirst, getSize});

Internal reference

It is often the case that you need to reference the factory object from within the factory function. We can think of the factory functions closure as the object state and the returned object as the interface.

Because in JS the token this is unsafe we need to create a safe reference to the returned object that can be used from within the factory.

What that name is, is up to you, I would personally have called it interface however that is a reserved token in JS so I have taken to standardize the returned object name to API which works well and replaces the this token with the visually easier capitalized name.

Thus you can use the following (see below for details on getters)

const API = Object.freeze({
    add, remove,
    get first() { return  values[1] },
    get size() { return values.length - 1 },
});

return API;

Then from within the factory you can acess the interface as follows

// you had
if (getSize() > 0) {
// becomes
if (API.size > 0) {

Q2

  Are there any JavaScript best practices that I've violated or ignored?

Use const for variables that do not change.
Use object shorthand property notation. See below
Reduce GC overhead and by using preallocation and result object as optional argument. See below
Hoist var declarations to the top of the function.
Don't use line seperated declarations.  See below
Use getters and setters to simplify the interface.
Protect state and freeze the returned factory object.
null is to be avoided. undefined is better. Ignoring the DOM null is seldom used in JS and represents a defined placeholder.
Use shorter function form that is arrow functions.
The JS author's regret was to tokenize function rather than func which spurred the push and adoption of arrow functions. Use common abbreviations when possible, less to read is quicker to read and easier to comprehend. Source code is not an english literature dissertation, you don't need to double space for examiners notes.
JS has one number type (double AKA 64 bit floating point), however almost all implementations have a variety of under the hood number types. Signed 32 integer is the fastest and can be forced by using any of the bitwise operators. If working with known integer types (eg indices) use bitwise operations to ensure internal number type is int32
Don't add inferable names to variable names. You had function getParentIndex(childIndex) { return Math.floor(childIndex / 2); } is just as effective as const parentIdx = idx => idx >> 1; and makes one wonder why you need a function to perform a single operator?

Q3

  Is my implementation flawed in any way?

Not if the user of it is careful.

I do know that you can implement it without the need for the first item in the heap without adding complexity.

You do need to prevent your code from creating invalid states. Such as if you add a string as a number heap.add("1") your determination as to which is greater will false eg "11" > "2" evaluates to false. To prevent that from happening you need to convert added values to Number type. (see rewrite)

Also you do not want to accept values that are not numbers. You can throw a range error or ignore such values.

You do not protect against removing more than available and thus you can mutate the state to unusable. You should first check if there is anything to remove before doing so (see rewrite)

More info on above notes

Line separated declarations

Bad

var valueIndex,
    parentIndex,
    parentValue;

Better

var valueIndex;
var parentIndex;
var parentValue;

Best

var valueIndex, parentIndex, parentValue;

Shorthand property notation

Shorthand notation reduces the source code size, and thus is a major player in reducing to occurance of bugs.

eg creating an object from defined variables

var foo = someVal();
var bar = someOtherVal();

// old school ES notation
var obj = {foo : foo, bar : bar};

// ES6 + shorthand property notation
var obj = {foo, bar};

When you return the factory object

return {
    add: add,
    remove: remove,
    getFirst: getFirst,
    getSize: getSize,
};

You can return using shorthand

return {add, remove, getFirst, getSize};

Memory smart functions.

Memory smart functions aim to reduce the overhead that GC (Garbage collection) incurs by reducing needless memory allocations. It also has an additional benefit as it reduces the allocation and creation overheads associated with new objects and or arrays.

For example the function...

function getChildIndices(parentIndex) {
    var leftChild = parentIndex * 2;

    return {
      leftChild: leftChild,
      rightChild: leftChild + 1,
    };
}

...creates and returns a new object each time it is called. You ate just interested in the 2 64bit numbers (if ints then 32bit numbers), but an object requires much more than 2 64bit values, and it need to invoke memory management, and when done with the object it is added to the GC workload.

You call it as follows

  var childIndices = getChildIndices(lastValueIndex);  // creates new object
  var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

  while (lastValue > smallestNode.value) {
      swap(lastValueIndex, smallestNode.index);
      lastValueIndex = smallestNode.index;

      var childIndices = getChildIndices(lastValueIndex); // Creates it again each iteration
      smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
  }

The function can be changed to be able to remove that overhead using the following pattern

function getChildIndices(parentIndex, result = {}) {  // result is the returning object. If not passed it is created
    var leftChild = parentIndex * 2;
    result.leftChild = leftChild;
    result.rightChild = leftChild + 1;
    return result;
}

Then your calling function uses it as follows

  const childIndices = getChildIndices(lastValueIndex);  // creates new object as default parameter
  var smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);

  while (lastValue > smallestNode.value) {
      swap(lastValueIndex, smallestNode.index);
      lastValueIndex = smallestNode.index;

      getChildIndices(lastValueIndex, childIndices); // reuses the object, saving time, memory and GC overhead
      smallestNode = getSmallestNode(childIndices.leftChild, childIndices.rightChild);
  }

Read only properties using getters

You have the following functions that are equivalent to getters (hint they have get at the start of the name)

function getFirst() {
    return values[1];
}

function getSize() {
    return values.length - 1;
}

return {
    add: add,
    remove: remove,
    getFirst: getFirst,
    getSize: getSize,
};

Should be defined as getters

return Object.freeze({
    add, remove,
    get first() { return  values[1] },
    get size() { return values.length - 1 },
});

A rewrite

I have added some additional state protection to the interface. Done some renaming, and reduced memory management overheads. The whole thing is now 50 lines that easily fits a display meaning the whole function can be understood without any device interaction

const MinHeap = () => {
    const heap = [undefined];
    const childIdxs = (idx, res = {}) => (res.right = (res.left = idx << 1) + 1, res);
    const swap = (idxA, idxB) => {
        const temp = heap[idxA];
        heap[idxA] = heap[idxB];
        heap[idxB] = temp;
    }
    const smallestNode = (idxs, res = {}) => {
        res.idx = heap[idxs.left] > heap[idxs.right] ? idxs.right : idxs.left;
        res.val = heap[res.idx];
        return res;
    }
    const API = Object.freeze({
        add(val) {
            if (isNaN(val)) { throw new RangeError("Can only add numeric values") }
            var idx, parentIdx, parentVal;
            heap.push(Number(val));
            idx = API.size;
            parentIdx = idx >> 1;
            parentVal = heap[parentIdx];
            while (parentVal > val && parentIdx >= 1) {
                swap(parentIdx, idx);
                parentIdx = (idx = parentIdx) >> 1;
                parentVal = heap[parentIdx];
            }
        },
        remove() { // returns undefined if heap is empty
            if (API.size) {
                let lastVal = heap.pop();
                const first = heap[1];
                if (API.size > 0) {
                    let lastIdx = 1;
                    const indices = childIdxs(lastIdx);
                    const smallest = smallestNode(indices);
                    heap[1] = lastVal;
                    while (lastVal > smallest.val) {
                        swap(lastIdx, smallest.idx);
                        lastIdx = smallest.idx;
                        smallestNode(childIdxs(lastIdx, indices), smallest);
                    }
                }
                return first;
            }
        },
        get first() { return heap[1] },
        get size() { return heap.length - 1 },
    });
    return API;
}


This code looks really repetitive. Any way to shorten it?

one way of shortening might be:

having a HashMap consisting of pairs of objects (sender) and Tools. This way you could look up the appropriate Tool for each sender in one single method like this:

HashMap<object, Tool> hashMap = new HashMap<object, Tool>( );

hashMap.put(sender1, new Brush(tileLayers));

// ...add the rest of the Tools
private void clickHandler(object sender, EventArgs e)
{
    currentTool = hashMap.get(sender);

    UncheckToolstripButtons( );
    tspBrush.Checked = true;
}

If tspXxxx cannot be retrieved from the sender directly, use another HashMap to map senders to tspXxxx objects.


Bash script to swap out, edit host files

I think this is generally clean.

Style Points

use $() instead of ``, it's clearer and they can be nested.

E.g:

if [[ "$(whoami)" != "root" ]]; then
    echo "You don't have sufficient priviledges to run this script (try sudo.)"
    exit 1

Consider setting:

set -u #prevent unset variables
set -e #stop on an error

At the top of your script.

rm_host may benefit from rewriting using an inplace sed edit, rather than using awk to copy over the top of the old file.

Locks

Although unlikely, you may want to consider a lock to prevent races between add_host and rm_host. $ACTIVE_FLAG would make a good lock.

$VARDIR

It looks like you intend this script to be used at differing privileges level (e.g. root and non-root). This will change the $HOME env variable and consequently the $VARDIR env variable. Potentially {add,rm}_host may act on different files to {start,stop}_block. Note that this won't present itself  if you only use sudo.

Reconsider what you want $VARDIR to be. On a a single user machine /var/ may be a good choice.


In-proc event dispatching through IoC container

I think the code would be more readable and easier to maintain if there was a method that handled the main calling of the other handlers.
Unless there is a reason for provider to be a property I would make it a readonly field instead.
public class Sender : ISender
{
    private readonly MethodInfo handlerMethodInfo;
    private readonly IServiceProvider provider;

    public Sender(IServiceProvider provider)
    {
        this.provider = provider;
        Func<Task, object> handlerMethod = HandleAsync<object>;
        handlerMethodInfo = handlerMethod.Method.GetGenericMethodDefinition();
    }

    private async Task HandleAsync<TEvent>(TEvent e)
    {
        var handlers = provider.GetService<IEnumerable<IHandler<TEvent>>>();
        await Task.WhenAll(handlers.Select(h => h.HandleAsync(e)));
    }

    public async Task SendAsync(object e)
    {
        // Call the HandleAsync method
        var eventType = e.GetType();
        var method = handlerMethodInfo.MakeGenericMethod(eventType);
        await (Task)method.Invoke(this, new object[] { e });
     }
}

In the constructor just getting a reference to the method needed to call and in a way that's type safe.  Then in the SendAsync we will use reflection to call the private method to call the other classes.  Now the reflection code is a lot smaller but the main logic is still in "normal" code in the HandleAsync method.
We could turn the SendAsync into ExpressionTrees to only require reflection once but they come with a high price.  Typically code would need to be called ~500 to make up the speed hit of compiling the expression vs reflection.


Deleting an item from a Set while iterating

No, there is no risk because you are returning directly after removing, or breaking directly after setting the deleteThis variable.

However, to make each part of your code as safe as possible, I would recommend to use the Iterator approach. The idea is that if you would forget to use break; or return; then you would have problems. If you use Iterator.remove(), then you are still safe.

There is another variant as well, based on Java 8 (if you have that available),

tableData.stream().filter(r -> r.counter.equals(counter)
        && r.reading.equals(reading))
    .findAny()
    .ifPresent(r -> tableData.remove(r));

This will not have a big impact on performance thanks to the fact that you are using a Set.

Now, I am not fully aware of your exact situation but another option might be to implement hashCode and equals in your Row class, in which case two Row objects with the same properties won't be added to the Set in the first place, and if you want to remove one and replace with another, you can do so with \$O(1)\$ complexity instead of your current \$O(n)\$. This assumes though that you are actually free to do this. Implementing hashCode and equals can have other unforeseen consequences.

Other comments

enum values should be named UPPERCASE according to Java naming conventions.
It is unclear what a Row really represents, and what a dfEng is.
Since Java 7, you can use the "diamond operator" <>, you can do new HashSet<>();
Not necessary to store the String in a local variable in toString (although it can be useful if you want to debug and see what the method will return).


Using findInterval to assign vector elements to corresponding brackets

Maybe it is overkill to use findInterval when your brackets only have two values (a min and a max). I would suggest this much shorter function based on two outer calls with >= and <=. As you probably know, outer is efficient in that it can take advantage of vectorized functions, so here only a single call to <= and >= will be made:

assign_interval2 <- function(x, brackets) {
  stopifnot(all(lengths(brackets) == 2L))
  lower_bounds <- sapply(brackets, head, 1)
  upper_bounds <- sapply(brackets, tail, 1)
  outer(x, lower_bounds, ">=") & outer(x, upper_bounds, "<=")
}

The results are the same and benchmarks suggest this is also a bit faster:

x <- 1:6505
brackets <- list(c(1,  325), c(1,  651), c(1,  976),
                 c(1, 1301), c(1, 1626), c(1, 1952))

res1 <- assign_interval(x = x, brackets = brackets)
res2 <- assign_interval2(x = x, brackets = brackets)
any(res1 != res2)
# [1] FALSE

library(microbenchmark)
microbenchmark(
  assign_interval(x = x, brackets = brackets),
  assign_interval2(x = x, brackets = brackets)
)

# Unit: milliseconds
#                                          expr      min        lq      mean
#   assign_interval(x = x, brackets = brackets) 7.851050 11.278404 15.300305
#  assign_interval2(x = x, brackets = brackets) 1.373723  1.628319  3.134719
#     median      uq       max neval
#  13.099052 14.4824 152.33409   100
#   2.192194  3.2971  13.70505   100

That being said, let's review your code and see if we can make small suggestions to improve your code while staying true to your implementation.

Instead of the do.call("cbind", lapply(...)), you could use sapply. The s in sapply is meant to do that exactly that: simplify the output by binding the pieces together. It comes at a very small (time) performance cost which should not affect you much here considering you do not have many brackets. I also notice that you are using the -> assignment operator which is not often used by R programmers hence not recommended.

dat <- sapply(brackets, findInterval, x = x, rightmost.closed = TRUE)

For the friendly names, I think the following would read better:

lower_bounds <- sapply(brackets, head, 1)
upper_bounds <- sapply(brackets, tail, 1)
friendly_names <- paste("int", lower_bounds, upper_bounds, sep = "_")

Next, a call to setNamesis a bit inefficient as it copies your data to a separate space in memory. Instead, you should use the colnames<- function so it only modifies the attribute of your existing object.

colnames(int_dta) <- friendly_names

Next, the use of apply is pretty inefficient as it loops on the columns. Instead you could just do:

int_dta <- int_dta == 1L

to convert to a matrix of TRUE/FALSE.

At the end, you are again making an unnecessary copy of your data. You can just change the rownames of your current object, then return it.


Reading large text file from network (SMB)

Reading just 160 bytes at a time could be bad for performance, especially if you are using the older SMB 1 protocol.  SMB 2.0 introduced pipelining, which allows the client to issue another request before the previous one has completed.  Therefore, with SMB 1, you would have to wait for each request to be finished — including network and disk latency — before making the next read.  If the read requests are too small, then performance could suffer badly.

What is a good buffer size?  Microsoft's KB 223140 suggests that somewhere between 4 kB and 60 kB could be ideal — in any case, much more than 160 bytes.


Apart from that I don't quite get the point of your game, there are a few things that caught my eye:

1. User input
Your user input system is not particularly intuitive to use. Without the source code the user has virtually no way to see what inputs are acceptable at the moment or what your game does.

2. Documentation
Your functions are documented like this at the moment:

#determines reload time
def reloading(reload_time):
    ...

Enter the official Style Guide for Python Code (aka PEP8)! There, the official recommendation on how to document function is to use """documentation strings""" like so:

def reloading(reload_time):
    """determines reload time"""
    ...

Documentation written in that style helps Python's built-in help(...) function as well as basically all Python IDEs to pick it up. Future-you, and depending on the path you choose also others, will thank you a lot if you learn this early and stick to it.

3. Start
The general notes on user input apply here. But apart from that, there is also a lot of repeated code here. You call firearm.upper() on every branch of the if statement, when a simple firearm = input('CHOOSE YOUR GUN (ENTER to exit)\n> ').upper() could do that in one place.

It's also common practice to wrap the code that is supposed to be run in a scripty-manner in if __name__ == "__main__":. This basically tells the Python interpreter (and also people looking at your code) that this part is meant to be run as script and is not part of the code that's eventually going to  be imported into some other script. See also the official documentation or this Stack Overflow post for further details.

if __name__ == "__main__":
    # This makes sure you game will not start if you ever import the file
    start()

sys.exit() is also a bit uncommon here but we will touch on that in a moment.

4. Reloading
Slow reloading is quite a killer (pun intended). Especially if it looks like nothing is happening. When I did a test run with your game on my Windows laptop, nothing happened after Reloading appeared on the console until the "loading" actually finished. This was what I expected, since at least on Windows print does not automatically flush the buffer so you will see nothing in the reload cycle. Using print('.', end='', flush=True) fixes that.

5. Gun play
gun(...) is were the "fun" starts. This is actually your main gameplay, so gun is likely not a really good name. Often methods have some kind of action description in their name like fire_gun(...) or something similar. Nouns like gun are usually only used for class names.

Since we are alread nit-picking about names, let's look at the paramters:

ROUNDS: all uppercase names are by convention usually reserved for global, odule, or class level constant values. Here, the capitalization seems to be used to disambiguate the value from the internal variable rounds. But why not choose a name that seems more appropriate for what the value actually represents like magazine_capacity?
left is very generic here and leaves room for interpretation. total_rounds or reserve_capacity sound like more appropriate names in this context here.
fire_rate is in its own right actually quite okay, although the variable name contradicts the way you use it. A rate is usually defined as something per amount of time, like shots per seconds. In your case it's actually used the other way round as time between two shots. So consider changing  either of them to fit the other.
the_reload: Why this name? Why not time_to_reload?

Now that we have sorted this out, let's look at the control flow: On the top-most level you repeat the fire-till-empty-then-reload cycly until you are completely out of ammo. That's fine. There is a little bit of repeated code in rounds == 0 where print('\n{}/{}'.format(rounds, total_rounds)) could be used just once outside the inner if statement

elif rounds == 0:
    if total_rounds <= magazine_capacity:
        # if bullets left is less than the magazine
        ...
    else:
        ...
    print('\n{}/{}'.format(rounds, total_rounds))

The first case with if rounds == 0 and total_rounds == 0: is also fine. With elif shoot.upper() == 'DONE': things start to get a little bit troubling. The code in this block is as follows:

elif shoot.upper() == 'DONE':
    sure = input('Are you sure?\n> ')
    if sure.lower() == 'y':
        start()

Since this basically has nothing to do with the gameplay, the code breaks the single responsibility principle which is often recommended when thinking about/designing functions. This a higher level gameplay element and should better be placed in start(). Doing this will also help you to get rid of the yet to surface error caused by exceeding the maximum recursion depth. You can get at that point if you get into that branch of the if statement over and over again, calling start(), which then in turn calls gun(...), which then calls start() again, and so on and so forth, until the program crashes.

So how to do this in a better way?

def fire_gun(magazine_capacity, reserve_capacity, fire_rate, time_to_reload):
    """parameters including the numerator/denominator, fire rate, and reload speed"""

    ...

    while rounds > 0 or reserve_capacity > 0:
        shoot = input()

        rounds -= 1
        print('{}/{}'.format(rounds, reserve_capacity))

        if rounds == 0 and reserve_capacity == 0:
            print('OUT OF AMMO')
            break
        elif shoot.upper() == 'DONE':
            sure = input('Are you sure?\n> ')
            if sure.lower() == 'y':
                break
        elif rounds == 0:
            ...

        time.sleep(fire_rate)   # Faster!!

def start():
    while True:
        firearm = input('CHOOSE YOUR GUN (ENTER to exit)\n> ').upper()

        if firearm == 'ASSAULT':
            fire_gun(40, 130, 0.1, 7)
        ...
        else:
            break

In this version there is no recursion and you come back to the "weapons menu" whenever you are out of ammo of the user chooses to quit before. No recursion, no recursion limit, no crash! Cool.

6. Comments
You are using them wrong! Comments in source code are usually best used to explain why you are doing something, and not what you are doing, especially if it's quite obvious, like e.g.

rounds -= 1
# decrement each time input is given

This is clear from the code. No need to waste a comment on this.

Sometimes you have to do a little bit more to make a comment unnecessary, e.g. there at

if left <= ROUNDS:
    ...
    #if bullets left is less than the magazine

If you stick to the naming recommendations from above this can become

if reserve_capacity <= magazine_capacity:
    ...

See? No need for that comment any more! The code is now self-explaining.

On a not-strictly Python-related note: you are the first person I get to know who somehow likes to stick their comments below the line they are commenting on. Most people I know (including me) would expect the comment to live on the line above or on the same line as the code that comments belongs to.

Advanced ideas

You find that long if statement in start() cumbersome to read and hard to extend? You would like to extend your weapons locker with ease? You are willing to look into Python's magic box? Then read on.

Often this kind of long if statement can be transformed into something that's easier to maintain and extend using a Python dictionary. It a so called mapping, which maps a key to a value.

In your concrete example one could use something like this:

def start():
    guns = {
        "ASSAULT": lambda: fire_gun(40, 130, 0.1, 7),
        "SHOTGUN": lambda: fire_gun(6, 30, 2, 12),
        ...   # much more guns here
    }

    while True:
        firearm = input('CHOOSE YOUR GUN (ENTER to exit)\n> ').upper()

        try:
            guns[firearm]()
        except KeyError:
            break

The gun names are used as keys of the dictionary, this is quite obvious. Depending on your Python knowledge, you might also know something about lambda expressions as well. If not, think of them as functions or whatevere you like that can be "called", but without a explicit name. That's how guns[firearm]() works: For a given key, say "ASSAULT", the dictionary returns a lambda expression likelambda: fire_gun(40, 130, 0.1, 7)in our example. You could also assign this to a variable likeparameterized_version_of_fire_gun = guns[firearm]. You can think ofparameterized_version_of_fire_gunas a function at that moment that you would call like you callreloading`, for example. If it helps you can also think of it as a "normal" Python function:

def parameterized_version_of_fire_gun():
    fire_gun(40, 130, 0.1, 7)

So the next logical step is now to call parameterized_version_of_fire_gun() (← Note the opening and closing parenthesis).

As a bonus, this version would allow you to print guns.keys() to easily show the user all the possibilites to choose from.


A package for communications between packages - v2

It looks good overall IMO. I won't comment on the bootstrap code as I'm not familiar with your library, but I would change a few things. Inside the closures that you create you could simply return the public object, without defining publik, it looks a bit cleaner. Then I added some annotation and changed the control flow a bit:

Pub.Reg = (function() {
  var register = {};
  return {
    get: function(key) {
      return register[key];
    },
    set: function(key, value) {
      register[key] = value;
    },
    setMany: function(o) {
      $A.someKey(o, function (val, key) {
        register[key] = val;
      });
    },
    getMany: function() {
      return register;
    }
  };
}());

Pub.Event = (function() {
  var events = {};
  return {
    add: function(name, callback) {
      // A bit more concise
      (events[name] = events[name]||[]).push(callback);
    },
    remove: function(name, callback) {
      // It's faster to set the value to `null`
      // than using the `delete` operator
      // but this depends on your use case;
      // the properties would still show up
      // in a `for..in` loop, but it's fine
      // if you use it merely as a dictionary
      if (!callback) {
        events[name] = null;
        return;
      }
      events[name][callback] = null;
    },
    trigger: function(name) {
      if (events[name]) {
        $A.someIndex(events[name], function (val) {
          val();
        });
      }
    }
  };
}());


Coding style

First, have a read through the Python style guide, PEP 8.
There's a lot of inconsistency in your coding style, and with the style guide, you should be able to remove all that. It will then also become consistent in style with a lot of existing Python code.

With that in hand, you can fix the following:

often, single space instead of double space.
Not if x  is True, but if x is True.
surround operators with a space, except as keyword arguments.
Not total =0, but total = 0.
Not  sum=0, but sum = 0.
leave a whitespace after a comma.
Not def  doubledigit(n,x) :, but def doubledigit(n, x):
(note: that also removed a double space, and remove the space before the :.)
remove parentheses from return statements and in conditions.
Not: return (sum), but return sum.
Not: if (n % 10 == 1 ):, but if n % 10 == 1:
avoid putting things on the same line after a colon.
Not else: sum = doubledigit, but

else:
    sum = doubledigit
If an argument in a condition (eg, if-statement) has a truthy or falsy value, or is simply True or False, don't compare it to anything (exceptions exist, but not so much here), but use the value itself.
Not: if x is  True: but if x:
Remove unnecessary line breaks for code that belongs together, such as in your if blocks. Do insert an extra line break after a function ends.
Thus: an extra line break after return sum and return total.
But remove the line breaks after print("the check digit is 8") and similar lines, because the next line definitely belongs to that if-clause.
Avoid overwriting built-int variables and functions.
Not: def sum():, but e.g. def calc_total()
and for the variable named sum, use a different name like total.
(I've used calc_total() here to avoid clashes with the variable named total, although such double naming will often work. It is, however, also a good idea to use a verb in your function name, to show it does something (calc is a bit generic, perhaps).

Here's the list with built-in functions
Use clearly named variables. n is just about acceptable (assuming it's short for number, but x is too generic. I don't know the algorithm well enough to come up with an appropriate name, but something like double_flag could be a decent name (tad long perhaps).

The same holds for function names: findx is rather generic, and from the name, I have no idea what we're trying to find here (relevant joke).

User input

Have a look at your input statements. There is a direct conversion to integer, which will cause a crash if someone accidentally enters, say 'a'. A crash is better than using, e.g., the value 97, but ideally, some user feedback is nice. Consider:

while True:
    n = input("Enter your digit: ")
    try:
        n = int(n)
        break
    except ValueError:
        print("Please enter a number", file=sys.stderr)

and similar for prop.
This costs more effort (and code), but when dealing with user interaction, there'll be a lot of extra code (never think "this will never happen for this code", because it will).
(Add an import sys at the top of your code, for the output to standard error.)

Note: I've re-used n here, first as the result of input() (being a str), then promptly assigning it to its actual, integer value. Since these lines are close together, and within the same while block, I don't feel this is an issue, but usually, it's better to use different variable names. E.g., answer = input(...) and then n = int(answer). See also Konrad Rudolph's comment below.

For the true or false input, avoid the ast.literal_eval.  Just compare directly to "True" or "False" input strings, and set x accordingly:

while True:
    x = input("Enter True or False: ").lower()
    if x in ['true', 'false']:
        x = True if x == 'true' else False
        break
total = total + doubledigit(n, x)

(I've taken the liberty to allow "true", "falSe" etc as input as well.)

I've added a short, ternary if-statement: x = True if x == 'true' else False. If that's new and confusing, it's exactly the same as:

if x == 'true':
    x = True
else:
    x = False

Alternatively, since a comparison yields a True or False value, you can also simply use:

x = x == 'true'

as Konrad Rudolph in the comments points out.

If chain

Your set of if statements all look remarkably similar. And if you check the operations inside the if statement and following lines, you may notice that while one set of digits increase, the other set decreases.

In fact, checkdigit = 10 - n % 10, and with that, all your if statements can be removed, and replaced with just this:

checkdigit = 10 - n % 10
print("the check digit is", checkdigit)
n += checkdigit

Of course, there is the n % 10 == 0 case, where the message changes, and no addition takes place. So:

checkdigit = 10 - n % 10
if checkdigit == 10:
    print("valid checksum:")
else:
    print("the check digit is", checkdigit)
    n += checkdigit

Using Python code as script or module

Your call to findx is at the top level of your code (at the bottom). That is, if you ever import your script (say, import luhn), the code will immediately execute. That is fine as a script (run as python luhn.py), but rarely when importing.

To avoid, a slightly fancy trick is applied, that'll you find in lots of places: we can check whether a file is imported or executed as a script. In the latter case, the special variable __name__ takes the value "__main__" (a string). Testing for that in an if statement avoids running the code when imported:

if __name__ == "__main__":
    print(findx(sum()))

Now you can import luhn without a problem, and then manually run luhn.findx(sum()) at your leisure (or, for example, just luhn.sum()).

Nested call

You call findx inside a print statement, and you calculate sum inside the call to findx. For clarity, it is nicer to separate this (there are cases where this is fine, but in general, separating them makes it easier to follow the program flow):

total = sum()
x = findx(total)
print(x)

Comments and doc strings

Python has the great ability to allow documentation inside the code, with so-called docstrings. Ideally, every script, function etc. has a docstring. Sometimes short, sometimes long. It describes what the function does, what inputs it expects, what errors can be raised. I haven't really bothered here with it, but it could be good to have them.
It would look a bit like:

def doubledigit(n, x):
    """Calculate the sum for double digits

    Calculate the sum for double digits, with the following algorithm:
    <brief description of algorithm>

    Inputs:
    - n: an integer
    - x: True or False

    Returns:
    The sum of double digits

    """

Have a read through the conventions used, or search around for more about Python docstrings: they are immensely useful if you start writing larger scripts, modules, packages, since they automatically provide documentation for both yourself (in a months time) and other users.

Algorithm

The one thing I haven't done, is verifying the correctness of the actual algorithm. Creating some automated tests (unit tests) would be good, but that's a step advanced.

With all the above applied, and some other minor fixes (e.g., sum = 0 is unnecessary, since it gets assigned either way in the lines below), my version of your code now looks as follows:

import sys

def doubledigit(n, double_flag):
    if double_flag:
        doubledigit = 2 * n
        if doubledigit >= 10 :
            total = 1 + doubledigit % 10
        else:
            total = doubledigit
    else:
        total = n
    return total

def calc_total():
    total = 0
    while True:
        prop = input("Enter how many digits you want: ")
        try:
            prop = int(prop)
            break
        except ValueError:
            print("Please enter a number", file=sys.stderr)
    for _ in range(0, prop):
        while True:
            n = input("Enter your digit: ")
            try:
                n = int(n)
                break
            except ValueError:
                print("Please enter a number", file=sys.stderr)
        while True:
            double_flag = input("Enter True or False: ").lower()
            if double_flag in ['true', 'false']:
                double_flag = double_flag == 'true'
                break
        total += doubledigit(n, double_flag)
    return total

def findx(n):
    checkdigit = 10 - n % 10
    if n == 10:
        print("Valid checksum")
    else:
        print("The check digit is", checkdigit)
        n += checkdigit
    return n

if __name__ == "__main__":
    total = calc_total()
    x = findx(total)
    print(x)


Simple cube that moves around the container with keys

It looks not bad at all. However, it could look more professional, and to my not very picky eye there seem to be errors.

HTML

There are no html-head-body tags, but every HTML document should have them. Nothing bad will happen, as modern browsers are really smart and will render your code correctly. These tags can be omitted by the HTML standards (e.g. WHATWG), but it is sort of a good style to have them always included. It will help whoever reads your code understand, that it is a document, not a part or template to be included somewhere else (if you didn't mean exactly this, of course).
The third DIV element is not closed, this is an error that will cause your HTML render not correctly. Use traditional

 or one-tag self-closing syntax:

Javascript

At the first glance, it is nice, but it doesn't look like Javascript. To look like Javascript, it should follow, or at least visually be close to one of coding conventions. Just a couple of things to be mentioned, that come to my mind:

No header. A header really helps you (some time later), or another person, to understand what it is, what it does, who and when wrote it, what language it is written in, and many other things you may want to let the future generations know. This is just a /**/-comment block on the top of the script.
Var-group. There are two main trends with defining the variables in JS - in the header / top of the script / block / function, or right before the place they are used. I personally prefer the first approach as more traditional, and besides that you assign initial values in your script, which makes it logic to do it as you did it. Var block can be grouped under the same var expression for better readability and more laconic and easier to transfer code. E.g.

var velocity = 2,
    acceleration = 0.002,
    //...
    key_up = false;

Separate the next logical paragraph (add listeners) with a blank line, don't keep it in the same paragraph with the "var" paragraph;
Function body is not indented well. The indentation should start with the first line of the function body. The rest is fine. E.g.

function example() {
    //first line indented
    //block opens: {
        //block indented
    //}
}
Good style is to put a block comment descriptor in front of every function to describe it.
Use strict comparison, instead of type-independent (e.g. a === b instead of a == b). This will help you avoid some issues later.
setInterval is missing the second argument - interval.
Defining function for a callback argument in the function call expression is not really a good practice, as it decreases readability and mantainability of your code and may lead to a "Callback hell", so I would recommend first define a named function and then specify it is an argument for the setInterval method. E.g.

function example() {
    //function body
}
setInterval(example, 1000);

And, in case if there are things that you don't know and which I mentined, but didn't reference here, you know how to search the web, right? =) Reading about coding conventions and a couple of articles about the good JS coding style may defenetely help.


Using an Array of Objects to Store Quiz Questions/Answers

How you're making the questions really looks ugly. How about this way?

var quiz = [{
    question: "Montgomery",
    answer: "Alabama",
    enabled: false,
    asked: 0
},{
    question: "Juneau",
    answer: "Alaska",
    enabled: true,
    asked: 0
}, {} /* ... */ ];

// Now instantiate every quiz
quiz = quiz.map(function(el) {
    return new quizConstructor(el.question, el.answer, el.enabled, el.asked);
});

Now if you're not doing anything more with your quizConstructor object, you can just as well use plain objects. (What's done before instantiating every quiz up there.)


Generate all combinations of certain digits

I think the code that you have is near best it can become.

I would however use a more functional/iterator based solution.

while True: no_of_digits += 1 can be replaced with a for loop.
This is by using itertools.count(1). (Careful infinite generator here)
all_digit_combinations would imply to me, that I get all of them, even 55555555.
Instead I would make all_digit_combinations an infinite generator.
else: raise StopIteration is kinda ugly. Personally I would use itertool.takewhile. (In this case it's better than filter, as infinite's are involved.)

As an alternate to itertools, you could just return. But due to that being implicit, it may be disliked.

And so I would re-write it into this:

def all_digit_combinations(allowed_digits):
    return (
        reduce(lambda rst, d: rst * 10 + d, digit_tuple)
        for no_of_digits in itertools.count(1)
        for digit_tuple in itertools.product(allowed_digits, repeat=no_of_digits)
    )

def digit_combinations(allowed_digits, maximum):
    return itertools.takewhile(
        lambda x: x < maximum,
        all_digit_combinations(allowed_digits)
    )

if __name__ == '__main__':
    print ', '.join(map(str, digit_combinations([1, 3, 7, 9], 100)))
    print ', '.join(map(str, digit_combinations([3, 5], 1000)))

As a performance is concern, your code is quite a bit faster than mine.
I used the following code:

import itertools
import timeit
from functools import wraps

def all_digit_combinations_original(allowed_digits, maximum):
    no_of_digits = 1
    while True:
        for digit_tuple in itertools.product(allowed_digits, repeat=no_of_digits):
            new_number = reduce(lambda rst, d: rst * 10 + d, digit_tuple)
            if new_number < maximum:
                yield new_number
            else:
                raise StopIteration
        no_of_digits += 1

def all_digit_combinations_enhanced(allowed_digits, maximum):
    for no_of_digits in itertools.count(1):
        for digit_tuple in itertools.product(allowed_digits, repeat=no_of_digits):
            new_number = reduce(lambda rst, d: rst * 10 + d, digit_tuple)
            if new_number < maximum:
                yield new_number
            else:
                raise StopIteration

def all_digit_combinations_answer(allowed_digits):
    return (
        reduce(lambda rst, d: rst * 10 + d, digit_tuple)
        for no_of_digits in itertools.count(1)
        for digit_tuple in itertools.product(allowed_digits, repeat=no_of_digits)
    )

def digit_combinations_answer(allowed_digits, maximum):
    return itertools.takewhile(
        lambda x: x < maximum,
        all_digit_combinations_answer(allowed_digits)
    )

def digit_combinations_enhanced(allowed_digits, maximum):
    return itertools.takewhile(
        lambda x: x < maximum,
        (
            reduce(lambda rst, d: rst * 10 + d, digit_tuple)
            for no_of_digits in itertools.count(1)
            for digit_tuple in itertools.product(allowed_digits, repeat=no_of_digits)
        )
    )

def timer_wrapper(*args, **kwargs):
    def wrapper(fn):
        @wraps(fn)
        def run():
            list(fn(*args, **kwargs))
        return run
    return wrapper

def timeit_(fn):
    print fn.__name__, timeit.timeit(fn)

if __name__ == '__main__':
    timer = timer_wrapper([1, 3, 7, 9], 100)
    timeit_(timer(all_digit_combinations_original))
    timeit_(timer(digit_combinations_answer))
    timeit_(timer(all_digit_combinations_enhanced))
    timeit_(timer(digit_combinations_enhanced))

    timer = timer_wrapper([3, 5], 1000)
    timeit_(timer(all_digit_combinations_original))
    timeit_(timer(digit_combinations_answer))
    timeit_(timer(all_digit_combinations_enhanced))
    timeit_(timer(digit_combinations_enhanced))

I obtained the following benchmarks.

all_digit_combinations_original 14.666793108
digit_combinations_answer 18.1881940365
all_digit_combinations_enhanced 15.228415966
digit_combinations_enhanced 17.9368011951

all_digit_combinations_original 14.4108960629
digit_combinations_answer 17.2161641121
all_digit_combinations_enhanced 14.8418960571
digit_combinations_enhanced 17.1169350147


I'm afraid there isn't much to remove. The $ after putStrLn and between app and pool are superfluous. You could write the last two lines run 8080 . app <$> getPool. I'd inline getPool. You may be interested in https://github.com/alevy/simple/blob/master/simple/src/Web/Simple.hs#L134 for boilerplate reduction.


Cards for Monster, Spell and Trap interfaces

As a general principle, instead of asking an object what its type is, tell it what you want to do, and let overridden methods handle the differences between types:

return card.getCardNode(nodeWidth, nodeHeight, imageWidth, imageHeight);

and add a getCardNode abstract method to Card, so that each Card subclass can implement its own piece of the get logic.


Print out numbers of increasing distance from center value in Python

Rather than maintaining the state of the iteration using three variables val, i, and neg_toggle, it would be more elegant to write a generator.  Then, the state of the iteration would be maintained by the flow of the execution of the generator itself.

def zoom_out(center):
    decr = center
    incr = center + 1
    while True:
        yield decr
        decr -= 1
        yield incr
        incr += 1

for n in zoom_out(24):
    if n in (30, 50, 90):
        break
    print(n)

Furthermore, fancy iteration can often be expressed more elegantly using itertools.  Here, I'd take advantage of itertools.count() to implement the generator, and itertools.takewhile() to detect when to stop executing the infinite generator.

from itertools import count, takewhile

def zoom_out(center):
    decr = count(center, -1)
    incr = count(center + 1)
    while True:
        yield next(decr)
        yield next(incr)

for n in takewhile(lambda n: n not in (30, 50, 90), zoom_out(24)):
    print(n)


You don't have to define the whole flow per route, this still leads you to the pyramid of hell.

  namespace :users do
    route_param :user_id do
      resource :activities do
        desc 'Create User + Activity associations'
        route_param :activity_id do
          post do
            #pyramid of doom
          end

          delete do
            #pyramid of doom
          end
        end
      end
    end
  end

However, you can register parts of the route in different files

namespace :users do
  register UserActivities
end

Then, within user_activities.rb you can add the rest of the code


The way you're handling add "modes" is a little clunky. It seems that only one of _add or _sub should ever be true at the same time. By making these two separate variables, you need to make sure that invariant is maintained everywhere. You've definitely helped make sure it's safe by using the add and sub functions, but those are band-aids on an awkward design.

The easiest way to simplify this is just to have one variable. Something like:

_is_adding = True

If this is true you're adding, if it's not, you're subtracting. Now find_mode can be much simpler:

def find_mode():
    return 0 if _is_adding else 1

And add and sub simply becomes:

def add():
    global is_adding
    is_adding = True

def sub():
    global is_adding
    is_adding = False

Although,

I think you're overusing globals here. In some cases, like UI callbacks, they may be the cleaner (but not only) option. find_mode for example though itself does not need to rely on globals. If you can cleanly pass data in instead of relying on globals, you should. I'd change it to:

def mode_number(is_adding: bool) -> int:  # I added some type hints in and renamed it
    return 0 if is_adding else 1

. . .

mode = simple_mode(mode_number(_is_adding))

The gain here is incredibly small because of how simple the functions involved are. In general though, it's a good habit to get into. Functions that explicitly take as arguments all the data they need, and return all the data that they produce are much easier to understand.

simple_mode and find_mode are kind of odd though if you think about them. Why translate add/sub into a number just to then translate it back to "Add"/"Subtract"? I think this makes more sense:

def format_mode(is_adding: bool) -> str:
    return "Add" if is_adding else "Subtracting"

. . .

mode = format_mode(_is_adding)

I think simplify is a bad name for a function. What's it "simplifying"? If I'm writing a function that turns something into a string, I usually call it format_* (although that's just a habit of mine). Give some description though. I'd probably call it format_time, and adding some simple type hints make the types clearer:

def format_time(_time: int) -> str:
    return time.strftime('%H:%M:%S', time.localtime(_time))

I'm not sure I 100% agree with calling the parameter _time to avoid the name collision, since a prefix _ typically means a "private" attribute, but I can't offhand think of a better name either, since the function is pretty broad in its purpose.

end_time-start_time-(-2211688800))

What the heck is -2211688800? That seems to offset the date by 70.1 years. Whatever it's purpose I see two problems:

If that's meant to offset today's date to reach a certain format, it'll be outdated from the second it's written. You should see if you can automate the creation of that number.
Magic numbers, especially large unusual like that should be named. Something like:

TIME_OFFSET = 2211688800

. . .

end_time - start_time - (-TIME_OFFSET)

Also, x - (-y) is the same as x + y (unless x and y are some custom type with odd math laws). It should just be:

end_time - start_time + TIME_OFFSET

The Flask import seems to be unneeded.