Single producer single consumer command queue

Order of public, protected, private

This is a personal preference but one that I find makes code easier to read. I always order my fields as: public then protected then private with the motivation that the person using the class is interested in seeing the public API and this should thus be the first thing you see so that you don't have to search for it.

Misuse of volatile

C++ (and C) has a thing called the "as-if rule". Which in essence says:

  The compiler is allowed to generate ANY code as long as all reads and writes to volatile memory happens in the same order and with the same values as if the program was execute according to the language specification.

This is the only use volatile has in C++, it means that writes and writes to volatile memory will always happen and will happen in the order specified. For example the compiler can, and frequently does re-order stores and writes. The compiler can remove memory writes and reads if it can determine that they will not affect any volatile memory read or write. The compiler can even remove memory allocations if it so pleases (clang does this some times).

For completeness, all inputs and outputs (files, std::cout, std::cin, std::cerr, std::clog, keyboard drivers, graphics display, sound buffers, networks packets) are volatile either directly or transitively. So the compiler cannot remove inputs or outputs of the program, but anything in-between basically.

When should I use volatile then?

Volatile should be used when you must be certain that a certain write or read is not removed by the compiler as dead. For example when you are writing a hardware driver, you would set control variables that must be written to some bus as volatile.

But volatile works for synchronising my threads just fine!

That is pure luck that it is working on your compiler. The compiler is allowed to change the order of reads and writes AROUND your volatile accesses as long as they don't affect the values of the volatile accesses. Also the CPU may or may not re-order some stores or loads depending on the CPU (x86 has a conveniently strict memory model which only has one case where memory accesses may complete out of order).

What you need is a memory barrier. A memory barrier forces both the compiler to generate code in such a way that all writes before the barrier happens before the barrier and tells the CPU to make sure all writes before the barrier has happened before the barrier completes. The above is a bit simplified, there are different memory types of barriers which say what must be completed before the barrier completes. If you're interested, see std::memory_order.

Does volatile affect my performance?

Yes, the compiler can do quite some fancy optimisations with re-ordering stores and loads and instructions so that they will effectively use the CPU's registers and to make sure that multiple issue kicks in on some CPUs. By using volatile you are prohibiting the compiler from doing some of these optimisations as you are forcing it to emit a read or write in a specific order.

In summary, don't use volatile unless you're absolutely sure that you need it.

Over-aligning basic types

You specify:

alignas(64) volatile unsigned       mHead = 0;
volatile bool                       mRuning = false;
Event                               mWaitEvent;
alignas(64) volatile unsigned       mTail = 0;
ThreadID                            mConsumerThreadID = 0;
alignas(64) CMDBase                 mElements[MaxCommand];

The compiler is required to store members of a struct or class in the order they are specified in the definition. And it is also required to respect the requested alignment. So the above code will form a structure in memory that looks something like this (depending on platform, unsigned is at least 16 bits but most often 32 bits):

Byte offset  Value
0-3         mHead
4           mRunning
Padding to respect basic alignment of mWaitEvent which believe is 4
8-?         mWaitEvent (I don't know how big it is)
Padding to make sure mTail starts on 64 byte boundary.
64-67       mTail
68-71       mConsumerThreadID (should be 32 bits)
72-127 Padding to make sure mElements start on a 64 byte boundary.
128 - 64127  mElements (assuming 64 bit binary)

Note that as CMDBase has `alignas(16)` and the structure is `MaxLamdaSize = 8*7 = 56 bytes` it has to be rounded up to the nearest multiple of 16 which is 64, so each CMDBase will occupy 64 bytes in that array.

Compare the above to the following:

unsigned       mHead = 0;
unsigned       mTail = 0;
ThreadID       mConsumerThreadID = 0;
Event          mWaitEvent;
bool           mRuning = false;
CMDBase        mElements[MaxCommand];

Byte offset  Value
0-3         mHead
4-7         mTail
8-13        mConsumerThreadID
14-21(?)    mWaitEvent (I don't know how big it is, assuming 8 bytes now)
22          mRuning
32 - 6431   mElements (assuming 64 bit binary)

Notice how the struct is 90 bytes shorter just by re-arranging the order of the members and removing the useless padding. Looking at it from a relative point of view 90 bytes out of 64127 is less than 0.2% storage reduction but that is not the point. Typically CPUs have a cache line that is 64 bytes long, i.e. the CPU can cache data in batches of 64 bytes. In this later variation all of the control variables fit in one cache line, where in your original code you needed two cache lines to hold the control variables, leaving less cache lines for the rest of the data.

Further more the alignment of data doesn't affect performance in any way as long as the data is aligned so that the CPU doesn't have to do an unaligned load (as long as you don't get an unaligned load but standard alignment requirements in C++ prevent this automatically).

Alignment is only useful to guarantee that hardware which requires a certain alignment can function and when you want to avoid false sharing. For example SSE instructions require 16 byte alignment on their loads. Don't just go randomly sprinkling alignas in your code. It will HURT your performance.

Enough about conceptual misunderstandings and on to the code

So it looks like you have implemented a circular buffer.  I recommend that you break out the circular buffer into it's own class and then use that in implementing your command queue. This will make your code clearer and easier to read. It will also make it possible to re-use the circular buffer.

Don't use the destructor to run the code like you do here:

       ~NewCMD()
        {
            mProc();
        }

If the lamda throws then you might have problems on your hands as destructors throwing exceptions is kind of a bad situation throwing from destructor. Not to mention that destructors are only for destroying the object, releasing any resources held and cleaning up.

Further since you're not removing the commands from the queue, when your application shuts down the mElements array will be destructed and each of the destructors on the elements will be executed again. Do I need to say this is bad? Not to mention that you never remove the objects from the queue when you're done with them.

I feel that you are overworking this in an effort to make it fast but in practice you're introducing problems and not actually improving speed. If you want your lamda to be 16 byte aligned so that your captures will work then just say so.

alignas(16) struct AlignedFunction{
    std::function<void(void)> function;
};

std::queue<AlignedFunction> mElements;

template<typename Callable>
void enqueue(Callable&& callable){
    mElements.emplace_back([](){callable();});
}

Don't preemptively optimise

Have you measured your application and have hard evidence that this command queue is the bottleneck of your application? If not you're just wasting time and creating bugs trying to write this complex class. I recommend that you take a simpler approach using standard library algorithms and functions and model the behaviour you want. If at a later point you get profiling data that points out this class as a bottle neck, then you can optimise.

In summary

I see that you are trying a lot of tricks that you think will improve performance. In reality these do no improve your performance, in fact I'd be willing to wager that you are in fact hurting your performance instead. Not only that but they are making the code hard to read and hard to work with.

Stop trying to be clever, you are hurting yourself. Write clean, maintainable code instead. The compilers today are pretty darn good when it comes to generating good code. Most likely they are way better than you are.


Implementing use of 'with CustomClass() as foo' in own class with DB-Connection

The reason to use a with clause is 1) clarity and 2) exception handling. Clarity because you have explicitly called out "right here, I am working with the object" and exception handling because you are guaranteed to have the exit handler called and any cleanup accomplished.

Canonical examples are:

with open(filename, "w") as fp:
    data = generate_some_data()
    fp.write(data)
    data2 = more_generation()
    fp.write(data2)

with lock:
    # all code in here is locked

You don't provide a lot of information about what you intend to accomplish in the with clause in your code. Typically the with block is not too long and focused on a task. If Client is meant to represent a player then you are probably putting the abstraction in the wrong place. A GameClient class could contain a DBConnection object. This way you could mock out the DB for testing for instance. Or switch to another DB type. If you meant Client to be DBClient I would rename it.


You should look into coroutines.
Coroutines are the Promises from JavaScript and the CompleteableFutures of Java.
It's basically Kotlin handeling the callbacks for you.

suspend fun getString() : String {
    return "t"
}
suspend fun main() {
    val t = getString()
    println(t)
}
//is roughly the same as:
fun getString(lamb: (String)->Unit){
    lamb("t")
}
fun main() {
    getString{
        println(t)
    }
}

You don't really need to know the implementation, but just some rules:

suspend functions can only be called from suspend-functions (because of the hidden parameter)
Suspend functions allow you to replace lammbda's with normal code, even try catch blocks!!!

in our case, we can change makeRequest to use suspension functions:

private inline suspend fun <reified T> makeRequest(url: String, p: Parameters) {
    val json = buildPath(url, p)
        .httpGet()
        .awaitObjectResult(jsonDeserializer()).obj()
    Log.i("json", json.toString())
    return deserialize<T>(json.get("results").toString())
}

change the search with:

suspend fun search(p: Parameters) = makeRequest("$API/search", p, callback)

then in MainActivity:

class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {
    override fun onDestroy() {
        cancel() // cancel is extension on CoroutineScope
    }

    //you can compare using launch with having a second thread.
    fun showSomeData() = launch {
        try {
            val text = XkcdClient(private val main: Activity).search(..)
        } catch (e : Exception) {
            Log.i("failed", "request failed")
            Toast.makeText(
                main,
                "Request Failed!",
                Toast.LENGTH_LONG
            ).show()
        }
    }
}

extra dependencies:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
implementation 'com.github.kittinunf.fuel:fuel-coroutines:'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'

extra info

https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb
https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html


Credit card verification: string conversion most optimal?

As @Keith says, credit card numbers should be treated as strings, not numbers, and definitely not floating-point numbers.  If you want to ensure that the input contains only digits (and maybe spaces), use strspn().  Squeeze out any spaces, then validate the length using strlen().

The Luhn checksum check should be in its own function.  The loop indexes would be more natural counting down, I think, since you are taking every other digit starting from the right.

int is_valid_luhn(const char *creditcard)
{
    int card_size = strlen(creditcard);
    int sum = 0;
    for(int i = card_size - 2; i >= 0; i -= 2)
    {
        int digit = creditcard[i] - '0';
        int prod = 2 * digit;
        sum += prod / 10 + prod % 10;      /* No special case needed */
    }
    for(int i = card_size - 1; i >= 0; i -= 2)
    {
        sum += creditcard[i] - '0';
    }
    return sum % 10 == 0;
}


I don't like that std::vector<Node*> neighbours; is a data member with public scope in Node. I would suggest doing it private and provide a getter for it, or provide a Node::push_back(), etc.

As for you question of adding a data member weight in Graph, I think that's not very nice, since - in my mind - weight is an attribute every node has, thus it should be a data member of Node.


Building a 2D array "month view" for a given date

I have only minor comments.

This logic appears twice, do is a good candidate to extract to a helper function to eliminate duplicate code:

(startDay.getDay() + 6) % 7;

Instead of this:

// If the month didn't start on a Monday, start from the last Monday of the previous month
startDay.setDate(startDay.getDate() - startDow);

It would be slightly more readable to move this code into a helper function with a descriptive name, for example:

function getStartingMonday(startDay, startDow) {
    // If the month didn't start on a Monday, start from the last Monday of the previous month
    return new Date(startDay.getDate() - startDow));
}

This way, the code in the caller will be shorter, and the implementation detail is not really important, it's enough to know that the returned date is the sizing day and it's a Monday.

The same goes for getting the last Sunday.

You're using semicolons inconsistently, sometimes omitting it. It would be better to use a consistent style, for example put it always.

The === is redundant here:

    if (week.length === 7){

You create week yourself, inside the function, so you know it's an array, and therefore must have an integer .length property, so a simple == is enough.


If you choose to manually parse the Xml document for loading only, I would prefer not to use the XmlDocument classes. They have a performance penalty. Instead use the XPathDocument and the XPathNavigator class to navigate trough your document.

    void ReadXml(XmlReader reader)
    {
        XPathDocument document = new XPathDocument( reader );
        XPathNavigator navigator = document.CreateNavigator();

        foreach (XPathNavigator nav in navigator.Select( "/*/*" ))
        {
            string keyValue = nav.GetAttribute( "SomeAttribute", navigator.NamespaceURI );
        }
    }

Second, i would prefer not to manually parse XML at all but create strong-typed classes in your project that you can serialize and deserialize. That makes the usage of you configuration more easy.


I think your idea is good, just try to use less ID and more classes with atomic classes, for example:

Site header

Site description

CSS :

    body, html{
        margin: 0;
        height: 100%;
    }
    .m0{margin:0;}
    .p0{padding:0;}
    .f100{width: 100%;height: 100%;}
    .abs{position: absolute;}

    #topOverlay{
        background-color: rgba(26, 188, 156, 0.98);
        z-index: 2;
    }
    #topImage{
        background: url("../images/workspace.jpg") cover center center;
        z-index: 1;
    }
    #topTextWrapper{
        z-index: 3;
    }
    #topText{
        position: relative;
        top: 40%;
        transform: translateY(-50%);
        font-family: 'Josefin Slab', serif;
        text-transform: uppercase;
        text-align: center;
        color: white;
    }
    #topText h1{
        font-size: 3.2em;
    }
    #topText h2{
       font-size: 1.4em;
    }

See especially how these 4 classes are used in the above example:

.m0{margin:0;}
.p0{padding:0;}
.f100{width: 100%;height: 100%;}
.abs{position: absolute;}

I was able to reduce the CSS from 53 line to 35 ( 35% )
plus its more simple


Is a unit test which uses LINQ to check multiple values acceptable?

What you need is passing parameters to common test method and supplying it with informative error message.

    [TestMethod]
    public void SubmitShortText()
    {
        var colorCodes = new[] { "#", "#f", "#ff" };
        DoAssertion(colorCodes);
    }

    private void DoAssertion(string[] colorCodes)
    {
        var parser = new ColorParser();
        foreach (var code in colorCodes)
        {
            var hasValue = parser.Parse(code).HasValue;
            Assert.IsTrue(hasValue, string.Format("Failed to parse color code '{0}'.", code));
        }
    }

Parametrized tests are also supported in XUnit:

    [Theory]
    [InlineData("#")]
    [InlineData("#f")]
    [InlineData("#ff")]
    public void SubmitShortText(string code)
    {
        var parser = new ColorParser();
        var hasValue = parser.Parse(code).HasValue;
        Assert.True(hasValue, string.Format("Failed to parse color code '{0}'.", code));
    }

Tests will be executed one by one. Execution will be stopped on the first failed test.


I think Bethan has the best approach, but you could take it one step further and use a generic Type:

public void OnNavigatedTo(NavigationParameters parameters)
{
    if (!IsNavigationFrom<MyCustomView>(parameters))
    {
        EventDateTime = DateTime.Today;
    }
}

private bool IsNavigationFrom<T>(NavigationParameters parameters)
{
    return parameters != null
        && parameters.ContainsKey(PARAM_NAVIGATEDFROM)
        && parameters[PARAM_NAVIGATEDFROM] == typeof(T);
}

This makes the method applicable to multiple view models.


Swift Attempt To Reduce Massive View Controller

You should read more up on MVVM, It would be better for your ViewModel to have no UIKit Dependencies. Testing your implementation will be difficult too.

Ideally, public properties on your ViewModel  i.e titleText and color and in your VC;

self.titleLabel.text = viewModel.titleText
self.titleLabel.backGroundColor = viewModel.titleBackgroundColor


This is a very interesting question.

First, I would reconsider the name. safe_static_cast implies that it is more general than it is. The types must have std::numeric_limits specializations in your implementation, so clearly you are thinking of numeric types. Maybe safe_numeric_cast or even numeric_cast would be a better name.

Secondly, assert is too often compiled out, so I would ask to consider alternatives which aren't. One alternative is throwing std::out_of_range. Another alternative is to saturate the destination type: if the source value is larger than the largest destination value, return the largest destination value.

Consider FromType = int, from = -1, ToType = unsigned int. Note that -1 >= 0u is true.

Consider the range of floating point types: min() is the lowest positive floating point value.

Consider floating point infinities: numeric_cast<double, double> should always be fine, right? But the comparison will fail for infinity.

Consider floating point nans: similarly, all comparisons fail for nans.


Python - checking if phrase appears on a list

Clarifying terms makes both code and documentation easier to understand.  You use the word "phrase" (which usually refers to an arbitrary group of words) to refer to both a line (one of a set of linebreak-delimited strings) and a word (one of a set of whitespace-delimited strings).  If you're talking about a single word, say "word".  :)
Give your function a descriptive name!  Maybe has_unique_words?
Type annotations and a docstring also make functions easier to understand.

Here's what we've got so far:

def has_unique_words(phrase: str) -> bool:
    """Checks whether any (whitespace-delimited) words in the phrase are repeated.
    Returns True only if all words are unique."""
    words = phrase.split()

Mutating an iterable as you iterate over it is an easy way to confuse yourself, and it's usually better to iterate over the elements of an list rather than the range of its indices (although because you're mutating it that might not work well here).  It might be better to find a solution that doesn't involve mutating the list.  Here are a few possibilities that are all simpler alternatives to popping/searching/re-inserting:

# Count the number of occurrences of each word.
# If each occurs exactly once, all words are unique.
word_counts: Dict[str, int] = defaultdict(int)
for word in words:
    word_counts[word] += 1
return all(count == 1 for count in word_counts.values())

# Iterate through each word and check whether we've already seen it.
seen_words: Set[str] = set()  # this could be a list, but a set is faster to check
for word in words:
    if word in seen_words:
        return False
    seen_words.add(word)
return True

This one-line check is what I would do:

# Build a set (which guarantees uniqueness) out of the list of words.
# If the number of elements is the same, all the list elements are unique.
return len(set(words)) == len(words)

In the interest of brevity I'd use sum and a comprehension to build the count rather than a named variable:

with open('file_with_phrases.txt', 'r') as file:
    print(sum(1 for line in file if has_unique_words(line)))


Optimizing for data import in Neo4j using py2neo

Here is the updated solution with batching. I found that the request times out of the batch size is much larger than 1000, unfortunately and I'm not sure what causes that:

import csv
from py2neo import Graph
import time

def main():

    f = "C:file_path/file.csv"
    graph = Graph("http://localhost:7474/db/data/")
    with open(f, 'r+') as in_file:

        reader = csv.reader(in_file, delimiter=',')
        next(reader, None)
        batch = graph.cypher.begin()

        try:
            i = 0;
            j = 0;
            for row in reader:
                if row:
                    character = strip(row[0])
                    first_name = strip(row[1])
                    last_name = strip(row[2])
                    actor = strip(row[3])
                    character_birth = strip(row[4])
                    character_death = strip(row[5])
                    allegiance = strip(row[6])
                    house = strip(row[7])
                    territory = strip(row[8])
                    region = strip(row[9])
                    query = """
                        merge (character:Character {Character: {a}, First_Name:{b}, Last_Name:{c}, Actor:{d}, Birth:{e}, Death:{f}})
                        merge (house:House{House:{g}, Allegiance:{h}})
                        merge (territory:Territory {Territory: {i}})
                        merge (region:Region {Region: {j}})
                        merge (character)-[:Of_House{House:{k}}]-(house)-[:Is_From]->(territory)-[:Is_In]->(region)
                    """
                    batch.append(query, {"a":character, "b": first_name, "c": last_name, "d":actor, "e":character_birth, "f":character_death, "g":house, "h": allegiance, "i":territory, "j":region, "k":house})
                    i += 1
                    j += 1
                batch.process()

                if (i == 1000): #submits a batch every 1000 lines read
                    batch.commit()
                    print j, "lines processed"
                    i = 0
                    batch = graph.cypher.begin()
            else: batch.commit() #submits remainder of lines read
            print j, "lines processed"

        except Exception as e:
            print e, row, reader.line_num

def strip(string): return''.join([c if 0 < ord(c) < 128 else ' ' for c in string]) #removes non utf-8 chars from string within cell

if __name__ == '__main__':
    start = time.time()
    main()
    end = time.time() - start
    print "Time to complete:", end


Your code doesn't follow the Single Responsibility Principle.

What do you need to do :

Check the text change
Verify if the input contains a number
Potentially change the state of the input (disable/turn red the input)
Re-enable it.

Right now, you have one function that takes care of all this, we should split it. Because, checkIfNumber shouldn't disable a textbox, that doesn't make sense! :)

You need to have functions that aren't coupled to your inputs, so we'll try to introduce parameters instead of accessing the document all the time.

function isNumber(value) {
    return !(isNaN(parseInt(value, 10)));
}

Notice I could have create a isNotANumber function, but that's not good as it's confusing. Also, this function doesn't need to be in the window.onload scope, it could very well be reused anywhere else.

Next, we want to disable the input and turn it red. I wouldn't write a function only to disable it. But, writing a function to disable an element for a time span seems like a good plan :

function disableFor(input, time) {
    input.readOnly = true;
    setTimeout(function() {input.readOnly = false;}, time);
}

Finally we need to run the time out for 10 seconds.

window.onload = function(){
    //or document.getElementsByName("numberinput")[0];
    var numberInput = document.formex.numberinput;

    numberInput.onChange = function() {
        if(isNumber(numberInput.value)) { return; }

        //I'm not sure why you do this.
        numberInput.innerHTML = numberInput.value;
        disableFor(numberInput, 10000);
    };
}

function isNumber(value) {
    return !(isNaN(parseInt(value, 10)));
}

function disableFor(input, time) {
    input.readOnly = true;
    setTimeout(function() {input.readOnly = false;}, time);
}

Notice that I inverted your condition to reduce nesting. So I just return if the value is a number, there's less nesting and well.. That's more readable!


Duplicates in array elements and sorting

Since it's an interview, they're probably looking for one of two things:

You show that you understand logic
You know PHP

It's never advisable to "recreate the wheel", and PHP has built-in methods to do what you're looking for - for example:

// Count how many times each array value occurs in the array
$occurrences = array_count_values($numbers);
// Filter out any that aren't duplicates
$duplicates = array_filter($occurrences, function($count) { return $count > 1; });
// Format the output as requested
$output = implode(',', array_keys($duplicates));

I note you don't say you have a requirement to sort anything, so don't bother.

If I were hiring you I'd obviously prefer you had both of the points above, but I'd rather that you used PHP to its ability as much as possible. Aside from that, this is a code review site, so the same answer would stand in that case. Example.


Potential type-safety issues on object parsing function in DXL

Of course, it's bad mojo to use predefined key words as variable names, and yes, this might bring you into trouble.

About "key": key is only defined for skip lists (perm: _x key (Skip)) and for the internal perm HttpHeaderEntryString_ key (). It is not possible to cast a Skip list to a string, the code Skip sk = create(); string s = "hello " sk "!" will not be valid, so there is almost no danger that the interpreter wants to make a string concatenation when you have the code xx = key sk, even when key is defined as a string variable.

So, in this case, you are more or less safe.string key key2 key3 will give you a plain old syntax error that you can easily detect.


Do you mean the default access modifier (i.e. none specified) by package-private? If you can offer your CalculatorEngine's code as another review then I'm sure some of us can give you good-quality advice there. As pointed out by OP, it's actually in this question: Simple calculator in Java using Swing and AWT. :)

Running down your list of tests...

First, why do all your tests throws Exception? Are they expected to? If they are, shouldn't you want JUnit to catch it and assert the right Exception is thrown? Your tests should be written in the minimal way possible, as you can also think of it as a form of documentation describing what your methods can or cannot do. If another developer (e.g. "You" six months down the road) sees the throws Exception, they may be mislead into thinking "an Exception may be thrown here... somehow.".

@Before
public void runBeforeEveryTest() {
    calcEngine.currentTotal = 0;
}

Your CalculatorEngine should probable have a reset() method for this. Manipulating a field directly in this way is prone to errors.

@Test
public void testGetTotalStringDouble() throws Exception {
    calcEngine.equal("50.5");
    assertTrue(calcEngine.currentTotal % 1.0 != 0);
}

So what does this do? Presumably, equal("50.5") sets currentTotal as 50.5, and we're testing that it's not an integer...? I wouldn't be worried about this. If the intention is to test whether equal() accepts a decimal-number-as-a-String, test that directly.

@Test
public void testMultiplyByZero() throws Exception {
    calcEngine.multiply(10);
    assertEquals(calcEngine.currentTotal, 0.0);
}

@Test
public void testDivideByZero() throws Exception {
    calcEngine.divide(10);
    assertEquals(calcEngine.currentTotal, 0.0);
}

The method names are misleading here, because the argument you use isn't zero, and your other method names do not read as e.g. addToZero(). Originally, I thought the division test was a division by zero test, and wanted to point out that doesn't give 0.0... Testing should involve edge cases too.

@Test
public void testMultiply() throws Exception {
    calcEngine.add(10);
    calcEngine.multiply(10);
    assertEquals(calcEngine.currentTotal, 100.0);
}

@Test
public void testDivide() throws Exception {
    calcEngine.add(10);
    calcEngine.divide(10);
    assertEquals(calcEngine.currentTotal, 1.0);
}

Ok, so now these are the 'normal' multiplication and division tests... It's still slightly odd that you have to do an 'add' first, which seems to be a merely convenient method (pun intended) of 'initializing' currentTotal as 10. You may want to look into this particular API design too.


Look up parameters based on a numpy array of input values

So you are doing a lookup over many intervals.  A repeated pattern like that can be turned into a loop or vectorized

The repeated boilerplate suggests an iterative solution - looping over an array (or list) of dates and values.  It doesn't save on run time, and may, or may not, be more maintainable.

def lookup_DNI_parameters1(day_of_year):
    """solution based on iterating over ranges of dates
    """
    A = np.empty_like(day_of_year)
    dates = [1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    Avalues = [1230.0, 1215.0, 1186.0, 1136.0, 1104.0, 1088.0, 1085.0, 1107.0, 1152.0, 1193.0, 1221.0, 1234.0]
    for i in range(len(dates)-1):
        interval = np.logical_and(day_of_year >= dates[i], day_of_year < dates[i+1])
        A[interval] = Avalues[i]
    # similarly for B and C
    return A

The operation can also be vectorized (in MATLAB as well as numpy), by constructing a matrix that compares the whole day_of_year array against the dates intervals array(s).  The [:,None] broadcasting may be novel to a MATLAB user.

def lookup_DNI_parameters2(day_of_year):
    """solution based on vectorized matching of days
    """
    dates = [1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    dates1 = np.array(dates[:-1]) # interval start
    dates2 = np.array(dates[1:]) # interval stop
    Avalues = [1230.0, 1215.0, 1186.0, 1136.0, 1104.0, 1088.0, 1085.0, 1107.0, 1152.0, 1193.0, 1221.0, 1234.0]
    Avalues = np.array(Avalues)
    I = (dates1[:,None] <= day_of_year) & (day_of_year < dates2[:,None]) # boolean index array
    I = np.where(I)[0]  # convert to numeric index
    return Avalues[I]

Or this could be generalized to use a dates parameter, and a values array that has information for A, B and C:

def lookup_DNI_parameters3(day_of_year, dates, values):
    """solution based on vectorized matching of days
    """
    dates1 = np.array(dates[:-1]) # interval start
    dates2 = np.array(dates[1:]) # interval stop
    I = (dates1[:,None] <= day_of_year) & (day_of_year < dates2[:,None]) # boolean index array
    I = np.where(I)[0]  # convert to numeric index
    return values[...,I]

dates = [1, 32, 60, 91,...]
values = np.array([[1230.0, 1215.0,...], [142., 144., ...], [...]])
lookup_DNI_parameters3(day_of_years, dates, values)


Solving Knight's Travails Problem without using vector for position

I'll be commenting just on the code itself, not on improvements to the algorithm. I'll also be removing your docs for brevity here.

First, I see a ton of repetitious code here. board and knight-moves contain a lot of duplicate code that can be generalized and cleaned up.

First, board:

(defn board [side-length]
  (->> (range (* side-length side-length)) ; Create all the numbered cells
       (partition side-length) ; Split them into rows
       (mapv vec))) ; Turn the board into a 2D vector

I turned it into a function that accepts the side length, and made it so it can handle whatever valid values you throw at it.

The different arity versions of knight-moves are almost identical. The only difference is that parent defaults to nil. This can be easily reduced:

(defn knight-moves
  ([node]
   (knight-moves node nil)) ; Default parent to nil

  ([node parent]
   (let [a (- node 17)
         b (- node 15)
         c (- node 10)
         d (- node 6)
         e (+ node 6)
         f (+ node 10)
         g (+ node 15)
         h (+ node 17)
         all-neighbours [a b c d e f g h]
         possible-neighbours (vec (remove #(or (neg? %) (> % 63)) all-neighbours))]
     {:neighbours possible-neighbours :current-node node :parent-node parent})))

That's still super bulky though. I bet there's a way to handle this without hardcoding all the numbers, but I can't think of it right now. A significantly more succinct version however could be:

(defn knight-moves
  ([node]
   (knight-moves node nil)) ; Default parent to nil

  ([node parent]
   (let [offsets [6 10 15 17]
         pos (map #(+ node %) offsets) ; Just map over the offsets so you aren't writing them twice.
         neg (map #(- node %) offsets)

         ; I'm reversing neg here so it matches your previous output. It seems valid without,
         ;  it just gives different answers.
         all-neighbours (vec (concat (reverse neg) pos)) ; Then stick the two together.
         possible-neighbours (vec (remove #(or (neg? %) (> % 63)) all-neighbours))]
     {:neighbours possible-neighbours :current-node node :parent-node parent})))

Note how I'm reversing neg. If I don't, the -main will return different results. The results without the call to reverse should be valid, they're just different from what you were getting before.

In nodes, I think you're trying too hard to use both arities of knight-moves, which is leading to duplicate code. Why not just pass nil? I'd also use mapv here instead of for. for is really only beneficial when you need to make use of it's ability to generate combinations, or make use of :when/:while:

(defn nodes
  ([starting-node]
   (nodes starting-node nil)) ; Default to nil, just like before

  ([starting-node parent]
   (let [movements (knight-moves starting-node)]
     ; You could use a full fn here instead of relying on the function macro
     ;  if you want a better identifier than %
     (mapv #(knight-moves % (knight-moves starting-node parent))
           (:neighbours movements)))))

I honestly couldn't find anything glaringly wrong with the rest of the code, so I left it as-is. This is the final result that I ended up with:

(ns irrelevant.knights.corrected)

(defn board
  [side-length]
  (->> (range (* side-length side-length)) ; Create all the numbered cells
       (partition side-length) ; Split them into rows
       (mapv vec))) ; Turn the board into a 2D vector

(defn knight-moves
  ([node]
   (knight-moves node nil)) ; Default parent to nil

  ([node parent]
   (let [offsets [6 10 15 17]
         pos (map #(+ node %) offsets) ; Just map over the offsets so you aren't writing them twice.
         neg (map #(- node %) offsets)

         ; I'm reversing neg here so it matches your previous output. It seems valid without,
         ;  it just gives different answers.
         all-neighbours (vec (concat (reverse neg) pos)) ; Then stick the two together.
         possible-neighbours (vec (remove #(or (neg? %) (> % 63)) all-neighbours))]
     {:neighbours possible-neighbours :current-node node :parent-node parent})))

(defn nodes
  ([starting-node]
   (nodes starting-node nil)) ; Default to nil, just like before

  ([starting-node parent]
   (let [movements (knight-moves starting-node)]
     ; You could use a full fn here instead of relying on the function macro
     ;  if you want a better identifier than %
     (mapv #(knight-moves % (knight-moves starting-node parent))
           (:neighbours movements)))))

(defn backtracking
  ([final-node] (backtracking final-node []))
  ([final-node path]
   (if (:parent-node final-node)
     (recur (:parent-node final-node) (merge path (:current-node final-node)))
     (reverse (distinct path)))))

(defn find-path
  ([starting-node goal-node]
   (find-path (knight-moves starting-node) goal-node []))
  ([starting-node goal-node path]
    ;; If not yet arrived at goal
   (if-not (= (:current-node starting-node) goal-node)
     ;; Create a new node with the current-node as parent and add it to path.
     ;; Iterate through all nodes to find the path.
     (let [new-node (nodes (:current-node starting-node) starting-node)
           path (concat path new-node)]
       (recur (first path) goal-node (vec (concat (rest path) new-node))))
     ;; If path found, return the path
     (backtracking starting-node))))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (find-path 27 28))

(-main)
; => (27 12 18 28)


This is not meant to be a comprehensive answer:

If you do not want a bug that happens only in some browsers and only some of the time, use a safe, conservative format as an id

checkBox.setAttribute( 'id',   unique + '_id' );

If id is a random 64-bit integer or a GUID in the following form (b362e877-95c3-4e88-99dc-ceb4600639b5), then you would want id to be 'id_' + unique instead of unique + '_id'


The answer, which may not be what you were hoping to hear, is that for generating more than a couple lines of HTML, partials are a much better fit than content_tag et al. Put your table code in a partial in e.g. views/shared/_semantic_table.slim.html:

table class="ui basic striped table"
  thead
    tr
      - headers.each do |header|
        th = header
  tbody
    = yield

...and then make your helper render it with the given arguments:

def semantic_table(headers, &block)
  render partial: "shared/semantic_table",
    locals: { headers: headers }, &block
end

Helpers are great for encapsulating logic that doesn't belong in a view/partial or in the controller, or adds a lot of noise: formatting data, choosing/combining several attributes, that sort of thing. But when you just want to spit out a bunch of boring HTML, you can't really beat a simple partial.

Edit

Re: your comment, that's interesting. I'm guessing Rails is using instance_eval somewhere, so your block with render @users is being evaluated in some different context where @users is nil. This is surprising, but I don't have a computer in front of me to dig further.

There may be a workaround that I'm not thinking of, but barring that, the simplest solution is to drop the helper entirely and just use the partial directly in your view:

= render partial: "shared/semantic_table", locals: { headers: headers } do
  = render @users

I'm not 100% sure that'll work, since didn't anticipate the other issue, but I think it will.

Another solution is to get rid of the block and pass in the objects directly:

def semantic_table(headers, objects)
  render partial: "shared/semantic_table",
    locals: { headers: headers, objects: objects }
end

...and then in the partial call render objects instead of yield.

Of course, this is more constraining than a block, but it may suffice for your use case.


Pass in parameters instead of multiple functions

I'd put the cookies into an object so they can be named.

var userCookies = {
    height: {
        name: 'user-height',
        options: {
            path: '/',
            expires: 365
        }
    },
    weight: {
        name: 'user-weight',
        options: {
            path: '/',
            expires: 365
        }
    }
};

Then you only need read/write cookie methods: (I've not used $.cookie so I'm only guessing I haven't broken it.)

function readCookie(cookieName) {
    var userData = $.parseJSON($.cookie(userCookies[cookieName].name));
    return(userData);
};

function writeCookie(userInfo, cookieName) {
    $.cookie(weight_cookie.name, JSON.stringify(userInfo),userCookies[cookieName].options);
};

If you want to be really modular (like all the cool kids) you might do something like:

var CookieMonster =(function ($) {
    var userCookies = {
        height: {
            name: 'user-height',
            options: {
                path: '/',
                expires: 365
            }
        },
        weight: {
            name: 'user-weight',
            options: {
                path: '/',
                expires: 365
            }
        }
    };
    return {
        readCookie: function readCookie(cookieName) {
            var userData = $.parseJSON($.cookie(userCookies[cookieName].name));
            return(userData);
        },
        writeCookie: function writeCookie(userInfo, cookieName) {
            $.cookie(weight_cookie.name, JSON.stringify(userInfo),userCookies[cookieName].options);
        }
    };
})(jQuery);

var userInfo = CookieMonster.readCookie('height');
var userInfo2 = CookieMonster.readCookie('weight');


Porcelain format

As @Vogel612 noted, the --porcelain format is the right one to use for scripting:

  The porcelain format is similar to the short format, but is guaranteed not to change in a backwards-incompatible way between Git versions or based on user configuration. This makes it ideal for parsing by scripts.

For the purposes of reviewing your code, though, I'll stick with the human format.

Redirection

There seems to be unusual concern placed on the handling of the standard error streams.  For the most part, you shouldn't need to worry about standard error that much.  As a rule of thumb, standard error contains out-of-band error messages that aren't really part of the output, and therefore aren't worth parsing unless you are interested in capturing those messages.  It may or may not be a good idea to redirect it to /dev/null.

As an example of that concern, I see git status 2>&1.  What sorts of messages might be in git's standard error.  One example would be

fatal: Not a git repository (or any of the parent directories): .git

Is that something that we would be interested in parsing?  Not really.  Is that a message that we want to make sure that the user never sees?  Maybe.  Therefore, standard error should either be left alone or redirected to /dev/null; lumping it together with standard output produces little benefit.

The standard error redirection in echo -n "${status}" 2> /dev/null is just superfluous.  Echoing a string should never produce anything on standard error.  As for grep … &> /dev/null, consider doing grep -q instead.

I don't understand why you need to | tee.

One pass, no buffering

Instead of buffering the $status and doing many command substitutions with echo -n "${status}" … | grep …, I suggest doing it all in one pass in pure Bash.

git status | (
    unset dirty deleted untracked newfile ahead renamed
    while read line ; do
        case "$line" in
          *modified:*)                      dirty='!' ; ;;
          *deleted:*)                       deleted='x' ; ;;
          *'Untracked files:')              untracked='?' ; ;;
          *'new file:'*)                    newfile='+' ; ;;
          *'Your branch is ahead of '*)     ahead='*' ; ;;
          *renamed:*)                       renamed='>' ; ;;
        esac
    done
    bits="$dirty$deleted$untracked$newfile$ahead$renamed"
    [ -n "$bits" ] && echo " $bits" || echo
)


Joining datatables to create a new datatable

I have managed to run some tests (I was very curious about LINQ on objects vs. SQL processing performance):

1) Setup

-- drop table t1
create table t1 (id INT PRIMARY KEY CLUSTERED, name NVARCHAR(1000))
go
-- drop table t2
create table t2 (id INT PRIMARY KEY CLUSTERED, name NVARCHAR(1000))
go
-- drop table t3
create table t3 (id INT PRIMARY KEY CLUSTERED, name NVARCHAR(1000))
go
-- drop table t4
create table t4 (id INT PRIMARY KEY CLUSTERED, name NVARCHAR(1000))
go

insert into t1 select top 200000 ROW_NUMBER() OVER (ORDER BY (SELECT 1)), CAST(text AS NVARCHAR(1000)) from sys.messages
insert into t2 select top 200000 ROW_NUMBER() OVER (ORDER BY (SELECT 1)), CAST(text AS NVARCHAR(1000)) from sys.messages where message_id > 1000
insert into t3 select top 200000 ROW_NUMBER() OVER (ORDER BY (SELECT 1)), CAST(text AS NVARCHAR(1000)) from sys.messages where message_id > 2000
insert into t4 select top 200000 ROW_NUMBER() OVER (ORDER BY (SELECT 1)), CAST(text AS NVARCHAR(1000)) from sys.messages where message_id > 3000

All tables have 2 Lakhs (200K)

Application and SQL run on the same machine (PC).

2) C# code

        public static DataTable fillDataTable(SqlConnection sqlConn, string table)
        {
            return fillDataTableByQuery(sqlConn, "SELECT * FROM " + table);
        }

        public static DataTable fillDataTableByQuery(SqlConnection sqlConn, String query)
        {
            DataTable dt = new DataTable();
            using (SqlCommand cmd = new SqlCommand(query, sqlConn))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);

                da.Fill(dt);
            }

            return dt;
        }

            var dt = new DataTable();
            for (int i = 0; i < 4; i ++ )
            {
                dt.Columns.Add(String.Format("Id{0}", i), typeof(int));
                dt.Columns.Add(String.Format("Name{0}", i), typeof(String));
            }

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                var sw = new Stopwatch();
                sw.Start();

                var dt1 = fillDataTable(con, "t1");
                var dt2 = fillDataTable(con, "t2");
                var dt3 = fillDataTable(con, "t3");
                var dt4 = fillDataTable(con, "t4");
                Console.WriteLine("Loaded in " + sw.ElapsedMilliseconds);
                sw.Reset(); sw.Start();

                var row = from r0w1 in dt1.AsEnumerable().AsParallel()
                          join r0w2 in dt2.AsEnumerable().AsParallel()
                            on r0w1.Field<int>("ID") equals r0w2.Field<int>("iD")
                          join r0w3 in dt3.AsEnumerable().AsParallel()
                            on r0w1.Field<int?>("ID") equals r0w3.Field<int?>("id")
                          join r0w4 in dt4.AsEnumerable().AsParallel()
                            on r0w1.Field<int?>("ID") equals r0w4.Field<int?>("id") into ps
                            from r0w4 in ps.DefaultIfEmpty()
                            select r0w1.ItemArray.Concat(r0w2.ItemArray.Concat(r0w3.ItemArray.Concat(r0w4 != null ? r0w4.ItemArray : new object[] { }))).ToArray();

                foreach (object[] values in row)
                    dt.Rows.Add(values);

                Console.WriteLine("Processed in " + sw.ElapsedMilliseconds);
                sw.Reset(); sw.Start();

                var directDt = fillDataTableByQuery(con, @"
select t1.*, t2.*, t3.*, t4.*
from t1
    join t2 on t2.id = t1.id
    join t3 on t3.id = t2.id
    left join t4 on t4.id = t3.id
");

                Console.WriteLine("Sql process + fetch in " + sw.ElapsedMilliseconds);

3) Results

No parallel

Loaded in 4370
Processed in 3249
Sql process + fetch in 3033

With parallel

Loaded in 4240
Processed in 1904
Sql process + fetch in 3160

So, including fetch, SQL performs better in this case (IDs are all clustered indexes). Also, using AsParallel makes a difference, at least on my machine (eight-core).

[later edit] - Dictionary version

Since you have to deal with fwk. 3.5. (VS 2008) and you said that you load data once and do more processing, I think you can try out the following:

    class AggrData
    {
        public int Id1 { get; set; }
        public String Name1 { get; set; }
        public int Id2 { get; set; }
        public String Name2 { get; set; }
        public int Id3 { get; set; }
        public String Name3 { get; set; }
        public int Id4 { get; set; }
        public String Name4 { get; set; }
    }

    // value is defined as anonymous type for extensibility
    var dict1 = dt1.AsEnumerable().ToDictionary(r => r.Field<int>("ID"), r => new { Name = r.Field<String>("Name") });
    var dict2 = dt2.AsEnumerable().ToDictionary(r => r.Field<int>("ID"), r => new { Name = r.Field<String>("Name") });
    var dict3 = dt3.AsEnumerable().ToDictionary(r => r.Field<int>("ID"), r => new { Name = r.Field<String>("Name") });
    var dict4 = dt4.AsEnumerable().ToDictionary(r => r.Field<int>("ID"), r => new { Name = r.Field<String>("Name") });

    Console.WriteLine("Dictionary setup took " + sw.ElapsedMilliseconds);
    sw.Reset(); sw.Start();

    var aggrList = new List<AggrData>();
    foreach (var key in dict1.Keys)
    {
        if (!dict2.ContainsKey(key) || !dict3.ContainsKey(key))
            continue;

        var newAggr = new AggrData()
            {   Id1 = key, Name1 = dict1[key].Name,
                Id2 = key, Name2 = dict2[key].Name,
                Id3 = key, Name3 = dict3[key].Name
            };
        if (dict4.ContainsKey(key))
        {
            newAggr.Id4 = key;
            newAggr.Name3 = dict4[key].Name;
        }

        aggrList.Add(newAggr);
    }

    Console.WriteLine("Aggregate POCOs fill took " + sw.ElapsedMilliseconds);
    sw.Reset(); sw.Start();

Results:

Dictionary setup took 3654
Aggregate POCOs fill took 202

So, setup is expensive, but the actual fill is much faster, as checking and retrieving data from Dictionary is very fast - O(1).


There is a lot simpler way to do this. You can use list slicing and the zip function.

List slicing essentially cuts up a given list into sections. The general form is list[start:stop:step]. The start section of a slice designates the first index of the list we want to included in our slice. The stop section designates the first index of the list we want excluded in our slice. The step section defines how many indices we are moving as well as in which direction (based on whether it is positive or negative). An example:

>>> x = [1, 2, 3, 4]
>>> x[1:3]
[2, 3]
>>> x[2:]
[3, 4]
>>> x[0:4]
[1, 2, 3, 4]
>>> x[0:4:1]
[1, 2, 3, 4]
>>> x[0:4:2]
[1, 3]
>>> x[0:4:3]
[1, 4]
>>> x[0:4:4]
[1]
>>> x[0:4:5]
[1]

The zip function takes sequences and creates a zip object that contains tuples of their corresponding index elements:

>>> for pair in zip([1, 2, 3], ['a', 'b', 'c']):
...    print(pair)
(1, 'a')
(2, 'b')
(3, 'c')

You can combine these two strategies to simplify your function. Here is my version of your lindexsplit function:

def lindexsplit(some_list, *args):
    # Checks to see if any extra arguments were passed. If so,
    # prepend the 0th index and append the final index of the
    # passed list. This saves from having to check for the beginning
    # and end of args in the for-loop. Also, increment each value in
    # args to get the desired behavior.
    if args:
        args = (0,) + tuple(data+1 for data in args) + (len(some_list)+1,)

    # For a little more brevity, here is the list comprehension of the following
    # statements:
    #    return [some_list[start:end] for start, end in zip(args, args[1:])]
    my_list = []
    for start, end in zip(args, args[1:]):
        my_list.append(some_list[start:end])
    return my_list


JavaScript switch statement to make an AJAX call

I don't really think putting the URL in your HTML is a good idea; Separating presentation from functionality and all that...

However, instead of using a switch statement, you should be using an object literal to map the URLs to the clickedOptionId key:

var searchURLs = {
    'btUsername'    : 'SearchByUsername',
    'btLastName'    : 'SearchByLastName',
    'btStudentID'   : 'SearchByStudentID'
};

var search = {
    url: searchURLs[clickedOptionId],
    data: { criteria: $search.attr('value') }
};


BBCode to HTML converter using functional programming

Overall, it's interesting, but quite hard to read. The indentation is kinda funky, and it would be easier to parse with all those ternary branches. For instance, this:

var htmlTemplate = (isClosing ? rules[key].map(function(rule) {
                                    return rule.filter(isIndexEven)
                            }).reverse()
                    : rules[key]);

Could be

var htmlTemplate = rules[key];
if (isClosing) {
  htmlTemplate = htmlTemplate.map(function (rule) {
    return rule.filter(isIndexEven);
  }).reverse();
}

Similarly, a few more local variables wouldn't hurt. E.g.

return input.replace(new RegExp(escapeString(search), "g"+(ignore?"i":"")), replacement);

Could be

var flags = "g" + (ignore ? "i" : ""),
    regex = new RegExp(escapeString(search), flags);
return input.replace(regex, replacement);

More micro-level: The pattern in escapeString can be simplified a great deal; you don't have to escape everything inside a character class, nor do you need the capture group. I get something like this

/[\\,!^${}[\]().*+?|<>&-]/g

The only things that need escaping is the backslash, the close square bracket, and the dash - unless you just put the dash at the end (if it's in the middle somewhere, it'll be interpreted as a range like 0-9).

There's a similar thing in your rules; you don't need to escape double quotes inside single-quoted strings.

I should add, though, that I haven't had the time to do a high-level review of all the regexp magic; I've looked a the individual patterns, not whether some can be combined, elided, or otherwise refactored.
Speaking of the rules: Whenever possible use class names or simply rely on HTML tag names instead of hardcoded style attributes. For instance, the <big> tag exists in HTML, just like <small>, so you don't need a styled span element. And the img tag doesn't need a style attribute; just declare the style for img tags in a CSS file. The point is, as with all things CSS, that you won't have to change your code (behavior) to change the look (presentation).
Some function names are pretty terse. E.g. eleFragsToHtml is a bit too truncated, if you ask me (especially considering the 2nd argument is spelled out as elementFragments)
I'd define the unchanging regex patterns outside the functions they're in now, since they're static - or define some more functions, to make it more descriptive. For instance, this

var attrs = tag.replace(/\[\w+|\]/g, '').trim().split(' ');
var key = tag.replace(/\[\/?| .+|\]/g, '');
var isClosing = /\//.test(tag);

Could be

var attrs     = tagAttributes(tag),
    key       = tagName(tag),
    isClosing = tagIsClosing(tag);

(yes, I've combined the var statements).
The tag* prefix on all those functions is of course a hint that they might benefit from being namespaced in an object. Or just have one parseTag function that returns an object with name, attributes, and closing properties.
Lastly, it'd be nice to stick all of this in an IIFE, like

var bbCodeToHtml = (function () {
  // shared variables, regex patterns here

  // various helper functions

  return function (string) {
    // the function that ties it all together
  }
}());

The idea is that the global namespace isn't polluted with a lot of "niche" functions; all you'll see is a function called bbCodeToHtml.

FYI, it's a toss-up whether the function should be bbCodeToHTML or stay as it is. The DOM is inconsistent in this regard (you have the innerHTML and namespaceURI properties, but you also have functions like getElementById - and I doubt they mean the Freudian "id" but rather "ID".


Perl script to print multi line log entries which has a match for given pattern

The code definitely isn't bad. I'd still use strict and warnings, though. Minor remarks:

Why do you use " for qr? / or {} are canonical.
$_ is good for short loops, and its advantage is you don't have to type it. So, I'd name the main loop's variable, as its scope is rather wide.
Avoid deep indentation. Use subroutines.
defined @fh is deprecated.

My version:

#!/usr/bin/env perl
use warnings;
use strict;

use Term::ANSIColor;

my $pattern = qr/[.a-zA-Z0-9]*Exception/;

sub output {
    my @buffer = @_;
    my $hilight = 'black on_yellow';
    for (@buffer) {
        if (my ($matched) = /($pattern)/) {
            for (split /($pattern)/) {
                print $_ eq $matched ? colored($matched, $hilight) : $_;
            }
        } else {
            print;
        }
    }
}

my $begin   = qr/^\d\d:\d\d/;

my ($found, @buffer);
open my $fh, '<', $ARGV[0] or die "Could not open file '$ARGV[0]' $!";
while (my $line = <$fh>) {
    if ($line =~ /($begin)/) {
        output(@buffer) if @buffer && $found;
        @buffer = ();
        undef $found;
    }
    push @buffer, $line;
    $found = 1 if $line =~ /$pattern/;
}

# Output the last match if it ends with an EOF instead of a timestamp.
output(@buffer) if @buffer && $found;


Tidying scaffolded Rails controller spec with subject/let

Check the answer from Pavel Druzyak for a different question. It answers your question as well.

Your code can be refactored to this;

describe ProjectsController do
    let(:project) { Project.create! }

    describe "GET index" do
      before(:each) { get :index }
      it { should respond_with(:success) }
      it { should assign_to(:projects).with([project]) }
    end

    describe "GET show" do
      before(:each) { get :show, {:id => @project.to_param} }
      it { should respond_with(:success) }
      it { should assign_to(:projects).with(project) }
    end
end


Why not just cast the field to lesser precision when querying from the database?

For example:

SELECT CAST(time_field AS TIME(2)) FROM table


A refactored functional programming that is evil.

public static class ObjectExtension
{
    public static Tout IfNotNull<Tin, Tout>(this Tin source, Func<Tin, Tout> func)
        where Tout : class
        where Tin : class
    {
        if (source == null)
        {
            return null;
        }
        else
        {
            return func(source);
        }
    }
}

public static class stringExtension
{
    public static int ToIntDefault(this string str, Func<int> def)
    {
        if (!string.IsNullOrEmpty(str))
        {
            return int.Parse(str);
        }
        return def();
    }
}

Consumer:

private int GetFirstLineFrameCount(XDocument doc, string _xmlns, string _xmlnsEc)
{
    int result = 0;
    var subElement = (from res in doc.Descendants(_xmlns + "subelements")
                      where res.Element(_xmlns + "object")
                                 .Element(_xmlns + "metadata")
                                 .Element(_xmlns + "identifier").Value == "1"
                      select res)
                      .FirstOrDefault()
                      .IfNotNull(k =>
                          k.Descendants(_xmlnsEc + "start").Select(x => x.Element(_xmlnsEc + "editUnitNumber")).FirstOrDefault()
                      )
                      .IfNotNull(k =>
                          {
                              result = k.Value.ToIntDefault(
                                  () => {
                                          Logger.Error<SubtitleNormalizer>("no offset found");
                                          return 0;
                                      }
                                  );
                              return (object)null;
                          }
                      );
    return result;
}

No, don't follow this. It is evil.

I just demonstrate something that can be done with functions. What you can do is as dreza's suggest to accept _xmlns and _xmlnsEc as parameter. Otherwise, I found that both of the variable is legal to exists, just make them readonly and do constructor injection. Otherwise, create a configuration for both variable so you can use myXmlConfiguration.Xmlns and myXmlConfiguration.XmlnsEc.


Support for JSONP and CORS is a must for any modern web framework.

APIwise, I think you'd want to reduce the arguments to your method to a single object, similar to how jQuery does it. It gives an opportunity to give defaults, and simplifies it from the API perspective.  As it stands, it will be painful to use, in that you need to remember a lot of arguments.  A simple GET ajax with your's:

ajax('GET', 'index.html', null, null null function(evt) {
    console.log("Success!")
})

vs jQUery or similar:

ajax({method:'GET', url:'index.html'}, success:function(evt) {
    console.log("Success!")
})


Computational verification of Collatz conjecture using OpenCL

The lookup table lut should be hard-coded in the source code and defined outside the kernel function as a __constant space global variable. As it is now, every thread would have to recalculate the entire table. Also they take too much space for thread's private memory space. Alternately, maybe pre-calculate it on the host and pass it to the kernel in a __constant space argument.
The outer for loop should be reformulated so that every thread has the same values for the counter variables, and the number of iterations is a compile-time constant. Then applying #pragma unroll may accelerate it.
When code diverges (on NVIDIA), it can become as slow as if the diverging section (i.e. the inner do loop) on threads within each warp (= 32 adjacent threads) were executed sequentially. Maybe somehow change it so that there is no divergence inside warps.

Edit:

Maybe hardcoding the LUT and putting it into __global memory instead. The GPU would put it into global memory anyways because it is too large for the per-thread private memory. And like that the values don't have to be calculated inside the kernel.
It that does not accelerate it, maybe make a copy of it in __local memory (per work group). And copy it from global to local inside the kernel. Then use the shared lut.
Do this copy in a coalesced manner, using multiple work items. For example on NVIDIA, each n'th work item of 32 must access the n'th item of 32 from the global memory table.
Take the first (always-executed) iteration of the inner do loop outside the loop, and make it execute the next iterations (in a loop), only if it is needed for at least one work item the subgroup, using the subgroup functions.
Use an OpenCL profiler (one exists for AMD) to see where the performance losses are. Or port it to CUDA, and use the NVidia Visual Profiler (from the CUDA SDK).
Pre-calculate if 128 bit integers are needed for each work item, or if 64 bit (or 32 bit) are sufficient. Then only use 128 bit integers when any work item in the subgroup needs it.


Php how to properly connect functions with pagination

Assuming you have a BOOL/BOOLEAN column called visible, you might consider using a more recognized syntax like visible <> 0 or visible = 0 as advised here: MySQL: “= true” vs “is true” on BOOLEAN. When is it advisable to use which one? And Which one is vendor independent? After all, BOOLEAN columns are really just TINYINT columns.

I have to assume that confirm_result_set($result); is fetching the rows and preparing them in some manner.  Perhaps you'd like to adjust the variable name to be more intuitive/descriptive.

Some developers, myself included, do not recommend the use of global as a means of transferring variables into a function's scope.  IMO, it is cleaner to pass the connection variable as a parameter in the function call (like you do with $sql).

I don't know what db_escape() is doing, but the surest advice is to urge you to use prepared statements with placeholders.  As a less classy alternative, so long as $category_id is an integer, you can cast it as an integer ((int)$category_id) before using it in your query. Joomla, for instance, doesn't offer prepared statements yet (available in the next major version) so they use integer/float casting for security on numeric values.  Also, numeric values do not need to be quoted in queries.

ASC is not necessary in your query, it is the default sorting direction and can be omitted.

The LIMIT clause string can be written without concatenation: $sql .= "LIMIT $p, $rowperpage";


I can see several issues in your code:

Days
I guess the row with code days = dd % 7; is some historic rest of code when converting to weeks (?).

Boundaries
If you call Time(0, 0, 0, 60), the condition if (ss > 60) is not true and the addition minutes++; is not executed. You should use if (ss >= 60). The same error is repeated in other if statements.

Incorrect additions
Try to call your constructor with Time(0, 0, 0, 86400). If my understanding is correct, you should get 1 day, but you get only 1 minute.

The correct logic should be something like this:
public Time(int dd, int hh, int mm, int ss)
{
    seconds = ss % 60;
    minutes = mm % 60;
    hours = hh % 24;
    days = dd;

    if (ss >= 60)
    {
        minutes = mm + ss / 60;
    }
    if (minutes >= 60)
    {
        hours = hh + minutes / 60;
        minutes %= 60;
    }
    if (hours >= 24)
    {
        days = dd + hours / 24;
        hours %= 24;
    }
}

But, as Jamal mentioned, the constructor is for setting data members and other logic should be splitted into other method(s). That's why my example is not perfect from the design point of view. I also used your variable names in my example. I can imagine better names for them.


Your function is very much more complicated than it needs to be.
As I understand it, the function should check if it is possible to build a row of exactly the goal size, that goal is not a "minimum" requirement, but the exact requirement.
Futhermore, I assume it would be OK to make a row that is of size 14, for example, completely out of 14 small bricks, and 0 large bricks, as long as the row has the size of goal.

We test for the small bricks first:

// check minimum number of small bricks required.
if (goal % 5 > small) return false; // not enough small bricks.

If the target is something like 14, then no matter what, we will absolutely need at least 4 small bricks, or the goal is impossible.

Then we test to see if there is enough length, in total, to make the goal:

if (small+big*5 < goal) return false; // not enough
else return true; // passed both tests

And if we pass both of these checks, then we know it is possible to reach the goal with the bricks that were supplied.

Here is how you could write the entire funcion:

bool make_bricks(int small,int big,int goal)
{
    if (goal % 5 > small) return false;
    if (small+big*5 < goal) return false;
    else return true;
}

As suggested by user "200_success", you could further simplify this to:

bool make_bricks(int small,int big,int goal)
{
    return (goal % 5 <= small) && (small+big*5 >= goal);
}

This version does cut down on the number of code lines, if that matters to you. Performance wise, there is no reason to think it will actually make a difference which one you use. The first, longer version, is perhaps clearer and easier to comment.

Note that, of course, none of these versions take into account what would happen if the function was called with nonsensical arguments, such as a negative number of small bricks.

Perhaps as a side-note, note that modulus % calculation is costly, though, so don't use it when you can avoid it. If you're writing x % 10, for example, then you might save performance by first checking if x < 10, and possibly avoid a few modulus calculations. That is, if you expect ´x´ to often be less than 10. If you expect the opposite, then don't make such a check.

When it comes to the design/interface choices, I would criticize the choice of the name of the function. The name seems to imply that the function "makes bricks". Good practice suggests that you name your functions in a way that makes it possible to deduce what the function does. And as  Scott Meyers explained in a talk, it's about what people who see the function/interface expect about it.
Even if you are the only one who will ever use this function, I'm talking about good practice, and I hope and assume you'll appreciate the input/feedback, since you posted it here.

Common practice for functions whose primary role is to return a bool is to have the function name be a statement about the thing in question, such as is_ready() or was_released(), or something of that style, since this fits with the idea of true or false.
I suggest you consider something like bool can_make_row(int numSmall, int numBig, int rowSize).


Don't use bare types

It seems you forgot to specify the type parameter here:

firstElement = new ListElement(element);

It should have been (as of Java 7):

firstElement = new ListElement<>(element);

Avoid duplicated logic

Notice the duplicated logic here:

if (empty()) {
    firstElement = new ListElement<>(element);
    size++;
} else {
    firstElement.nextElement = firstElement;
    firstElement = new ListElement<>(element);
    size++;
}

size++ appears at the end of both branches: it could be done after the conditional.

The assignment firstElement = new ListElement<>(element); is right before size++ at the end of both branches, so that too can be done after the conditional.

Without these duplications, the code becomes simpler:

if (!empty()) {
    firstElement.nextElement = firstElement;
}
firstElement = new ListElement<>(element);
size++;

Unnecessary statements

In pop, this statement is unnecessary, you can delete it:

T element = top();

And since the if branch throws an exception,
you can eliminate the else branch, like this:

public void pop() {
    if (empty()) {
        throw new RuntimeException("stack is empty");
    }
    firstElement = firstElement.nextElement;
    size--;
}

Follow good examples in the JDK

Take a look at the pop and peek methods of the Javadoc of Stack:
when the stack is empty, they both throw EmptyStackException.
I advise you do likewise.

Working with inner classes

The inner class ListElement holds a reference to the enclosing class
(as all non-static inner classes do).
In your example, this is unnecessary.
Make this inner class static, so that it becomes independent from the enclosing class.
This improves performance,
and also solves another problem that the type parameter T in ListElement<T> shadows the type parameter T of the enclosing Stack<T>.

Keep your toolbox clean

A Stack is a utility class,
potentially a useful element in your programming toolbox.
This method doesn't belong in it:

public static void main(String[] args) {
    // TODO Auto-generated method stub
}

The method does nothing, so it's pointless.
It has a default TODO comment,
which you should always delete when you're done working,
for example before asking for a code review.
If later you want to demonstrate the functionality of the stack by creating a runnable class with a main method,
do it in another class (say, StackDemo), not in this one.


Operating on a list of files using recursion

Fake for-loops and comprehensions
At the beginning of your post, you say that you can't always achieve everything with looping in one line in CoffeeScript. When you say that, I assume you are taking about the each_file:

  each_file: (index = 0) ->
    length  = @files.length
    file    = @files[index]
    if index < length
      Types.read file, @next.bind @
      @each_file index + 1

This is kinda ugly right now because you seem to be using a method to fake a for-loop. Luckily, with CoffeeScript's comprehensions, we can turn this into a simple 1-line expression.
First, we need to be iterating through all of the @files. That can be written simply like this:
Types.read(file, @next.bind this) for file in @files

This is a comprehension that will go through all of the @files and substitute the file in the Types.read call with the current file it's looping over.
Now that we have this, you can remove that

file = @files[index]

line, along with that single index parameter. Why? Because, now that we have this loop, we no longer have any of that method-recursion-fake-for-loop-idness.
Along with those, since this is now a comprehensions that loops through all the values in an array, we don't need to do any checking to make sure the index is less than the length.

if index < length

Can be removed. Guess what your method looks like now?
  each_file: () ->
    Types.read(file, @next.bind @) for file in @files

The above method will do exactly what it was doing before: it will go through all of the files in @files and pass it into Types.read along with @next.bind @.
What's different now?

It's much shorter and much simpler than what you were doing before. As I already stated, you seemed to be reinventing the for loop with that recursion you were doing.

It's more idiomatic. CoffeeScript has those comprehensions so you can simplify long tasks into a few small and readable lines.

Misc.

  init: (files, cb) ->
    @files              = files
    @cb                     = cb

This can be shortened to this:
  init: (@files, @cb) ->

The CoffeeScript compiler treats parameters with a @ before them as a name of a property to set to the parameter. For example, @files will become:
this.files = files

in the method body.


Similar code, so similar answer.

Please take these things to heart; I feel like I'm wasting my time otherwise.

    return maxElementOfArray (arr);

You have a space between the function name and the parentheses.

Finalize your arguments if you're not gonna do anything with them. Final your locals if you're not gonna do anything with them.

I feel your approach is completely wrong. Why load the whole tree structure into memory? Because you're copying the same code over and over. And that turns you into a blind programmer.

Instead, try this:

Add depth to TreeNode. private int depth;

Add depth to the constructor of TreeNode as the second argument.

Then declare root to be at depth 1.

Declare an array of int (we'll call it widths). Size 32; you can't get deeper with your syntax for defining a tree. (Maybe you can, I'm not sure how well a list containing 2^32 items will function).

Next, parse the list.

Whenever you add a new node to the queue, widths[current.depth+1]++. Whenever you create a new node, pass current.depth+1 as the second argument.

When you're done parsing the list, return maxElementOfArray(widths).

That might be considered cheating though; we're not really using a tree. Anyway.

    if (items.isEmpty())  {
        throw new NullPointerException("The input array is not empty.");
    }

Erm... yes it is. Maybe "The input list shouldn't be empty". Also NullPointerException is NOT valid here; use IllegalArgumentException instead (I didn't pass null! I passed empty list! If I get NullPointerException back when I pass in non-null objects then I spend a lot of time debugging, trying to find my null.)

    int h = getHeight(root);
    int[] arr = new int[h + 1]; // NOTE: h + 1

Use int height, it's more descriptive. Get rid of the comment or write WHY. Right now it could have been //<--- important! too, and that doesn't help anyone. Maybe consider using int[] arr = new int[getHeight(root) + 1]; as you don't reuse this h anywhere.

Your maxElementOfArray function returns Integer.MIN_VALUE. There's no such thing as a negative width. Return 0 instead; the top level contains 0 items. There are no other levels.

You perform three traversals of the entire tree; create is one, getHeight is two, computeWidth is three. I'd combine getHeight and computeWidth. You'll have to rewrite a couple things for this... but I believe I gave some pointers already.


There are several issues in your code that make it error-prone:

you are using a single byte array to feed all memory streams, thus the same data may be sent in different chunks. Same stands for count.
the order of chunks in blockids can be different to the one you've sent so resulting BLOB will have incorrect order of blocks.
there is a potential thread contention on blockids as different threads may add a new element at the same time causing all sorts of problems like missing blocks in resulting list, incorrect block IDs etc.
use Task.Factory instead of new TaskFactory()
if you create a task and immediately wait for it then you don't need that task, so you can replace the last BeginPutBlockList with synchronous version

Other than that I don't see memory leak from the graphs you provided. Threads may still be alive in a thread pool, and memory may not be collected by GC yet.

Here is what I've got as a result (note that it may consume more memory as you need to store all the chunks that are currently being sent in memory):

    private static Task PutBlockAsync(CloudBlockBlob blob, string id, Stream stream, RetryPolicy policy)
    {
        Func<Task> uploadTaskFunc = () => Task.Factory
            .FromAsync(
                (asyncCallback, state) => blob.BeginPutBlock(id, stream, null, null, null, null, asyncCallback, state)
                , blob.EndPutBlock
                , null
            );
        return policy.ExecuteAsync(uploadTaskFunc);
    }

    public static Task ChunkedUploadStreamAsync(CloudBlockBlob blob, Stream source, BlobRequestOptions options, int chunkSize, RetryPolicy policy)
    {
        var blockids = new List<string>();
        var blockid = 0;

        int count;

        // first create a list of TPL Tasks for uploading blocks asynchronously
        var tasks = new List<Task>();

        var bytes = new byte[chunkSize];
        while ((count = source.Read(bytes, 0, bytes.Length)) != 0)
        {
            var id = Convert.ToBase64String(BitConverter.GetBytes(++blockid));
            blockids.Add(id);
            tasks.Add(PutBlockAsync(blob, id, new MemoryStream(bytes, 0, count), policy));
            bytes = new byte[chunkSize]; //need a new buffer to avoid overriding previous one
        }

        return Task.Factory.ContinueWhenAll(
            tasks.ToArray(),
            array =>
            {
                // propagate exceptions and make all faulted Tasks as observed
                Task.WaitAll(array);
                policy.ExecuteAction(() => blob.PutBlockList(blockids));
            });
    }


I have a few issues with your code before I get into your actual question:

Your indentation is inconsistent and wrong, you should be using two or four space indentation, not three-space indentation.
Your usage of quotation marks is inconsistent, use either " or ', but stay consistent.
BUG: you're missing a close html tag character in here: <div class="card waves-effect waves-block waves-light"
.
Instead of pushing it into the block as one big lump, consider pushing it through at each category, that way it'll actually look like it's loading, and you can avoid storing a massive html string. You can use jQuery's .append to do this

As for your specific question, I would style it better by splitting it into parts, and joining each part like so:

$.getJSON('/api/get_categories', function(data){
    $.each(data.categories, function(key, value){
        $('#categories').append(
            '
' +
            '

' +
            '
' +
            '' +
            value + '

'
        );
    });
});


Setting aside that you won't go with a Mapping framework like Jeroen Vannevel suggested in his comment, this basically looks good but can still be improved.

I don't see any value added by creating an abstract class which implements the IMapper<T> interface. So you better just do it like

public class UserDtoMapper : IMapper<UserDto>
{
    public UserDto Map(SqlMapper.GridReader reader)
    {
        return reader.Read().Select(x => new UserDto()
        {
            Id = x.Id,
            Name = x.Name
        }).SingleOrDefault();
    }
}

But if you travel this route you should do it right and also make QueryObject class generic like

public class QueryObject<T>
{
    private IMapper<T> mapper;

    public QueryObject(IMapper<T> mapper)
    {
        this.mapper = mapper;
    }

    public T Query(int id)
    {
        ..........
         return mapper.Map(reader)
        ...
    }
}


Get users from groups in active directory, disposing of everything

You can remove braces between using statements, leaving the last one. That would help you to remove a few of lines, but still not so deeply.
Wrapping the IDisposable interface is a good choice to do as an alternative to a dozen of using statements.
I'd suggest you using more appropriate names, maybe by lowercasing just a character of your class/method when you instantiate/call them.

Add this class to your project:

    public class IDisposableList : List<IDisposable>, IDisposable
    {
        public void Dispose()
        {
            if (this.Count > 0)
            {
                List<Exception> exceptions = new List<Exception>();

                foreach (var disposableItem in this)
                {
                    try
                    {
                        disposableItem.Dispose();
                    }
                    catch (Exception ex)
                    {
                        exceptions.Add(ex);
                    }
                }

                base.Clear();

                if (exceptions.Count > 0)
                    throw new AggregateException(exceptions);
            }
        }

        public T Add<T>(Func<T> item) where T : IDisposable
        {
            var disposable = item();
            base.Add(disposable);

            return disposable;
        }
    }

usage:

            var data = new List<ExpandoObject>();

            using (var disposables = new IDisposableList())
            {

                var gp = disposables.Add(() => new GroupPrincipal(pc));

                var ps = disposables.Add(() => new PrincipalSearcher(gp));

                var psr = disposables.Add(() => ps.FindAll());

                foreach (var g in psr.GetGroupPrincipals())
                {

                    var gpsr = disposables.Add(() => g.GetMembers());

                    data.AddRange(
                            gpsr.GetUserPrincipals().Select(
                                u => GenerateData(g, u))
                                .Cast<ExpandoObject>());

                }

            }

this is just a more elegant way to do what you asked.

Remember that using a foreach is not as performant as a for loop.


I haven't used NPOI and I would believe you have valid reasons for using it (I'll take a wild guess at saying the thing is running on a server that doesn't have Excel installed), but for the record, if my memory isn't failing me if you used Microsoft VSTO / Excel Interop, you could use a plain & simple Copy+Paste and let Excel do the hard part.

Your code shows how much of a pain this could be otherwise.

That said @ANeves' comment about using Regular Expressions, along with @Zonko's comment about R1C1 references, could make your code much simpler:

Here's the magic regex: (\$?[A-Z]+\$?\d)(?=([^"]*"[^"]*")*[^"]*$)

...and the proof (using Expresso):

So the above regex pattern will spoonfeed you all A1 cell references that you need to analyze - those that aren't surrounded by quotes.

I don't know if NPOI facilitates this in any way (is there a Range object to play with?), but I would highly recommend getting the equivalent R1C1 cell references, so instead of AB$1 you get R1C[28]; then you can easily run a [much, much simpler] regex on these addresses to get the rows and columns and add your offsets, rebuild the addresses and rebuild the formulas.


Extracting maximum values from each of the subsets of an array

Single pass algorithm (~2n)

You can do it with a single pass over the array (which I shall denote as lst).

Maintain a maximum value (I shall denote this as max_val) once you hit a non-zero value. When we reach a zero, add (i, max_val) to the list of maximum values and reset the maximum value.
Build the new list using the list of maximum values.

This should give you pretty good performance (~2n since you iterate 2 times). However, if you need a parallel version...

Parallel algorithm

This is the first parallel algorithm I've ever designed, so pardon me if I screwed up somewhere. We use the MapReduce model which is quite simple to write.

Let k be the number of processes which you want to divide the work among and i be the number of each process where 0 <= i < k.

In the Map() procedure:

Each process starts at n/k * i indice and iterates till it hits n/k * (i+1).
Follow the algorithm as described in step 1 of the single pass algorithm.
If the first or last value is non-zero, it indicates that the values we have obtained may not be the maximum values of the subset as we may have only monitored a portion of the subset. Hence, we add it to the portions list.

When we flush, we mark the start and end indice that we have scanned and the maximum value, so as to indicate that we have not finished scanning that subarray.

For k = 3 and our array being [0, 0, 0, 0, 1] + [2, 3, 4, 0, 0] + [0, 2, 1, 0, 2] with a length of 15 (split into 3 segments for convenience):

i = 0: lst[0] = 0
       lst[1] = 0
       lst[2] = 0
       lst[3] = 0
       lst[4] = 1 # is_portion = True, max_val = 1
                  # add (4, 5, (4, 1)) to the list of portions
       return [] and [(4, 5, (4, 1))]
i = 1: lst[5] = 2 # is_portion = True, max_val = 2
       lst[6] = 3 # max_val = 3
       lst[7] = 4 # max_val = 4
       lst[8] = 0 # add (5, 8, (8, 4)) to the list of portions
       lst[9] = 0
       return [] and [(5, 8, (8, 4))]
i = 2: lst[10] = 0
       lst[11] = 2 # max_val = 2
       lst[12] = 1
       lst[13] = 0 # add (11, 2) to the list of maximum values
       lst[14] = 2 # is_portion = True, max_val = 2
                   # add (14, 15, (14, 2)) to the list of portions
       return [(11, 2)] and [(14, 15, (14, 2))]

In the Reduce() procedure, we merge the arrays we have together to form two lists:

1. Maximum values: [(11, 2)]
2. Portions not yet finished scanning: [(4, 5, (4, 1)), (5, 8, (8, 4)), (14, 15, (14, 2))]
  We merge the tuples (4, 5, (4, 1)) and (5, 8, (8, 4)) together and compare the maximum value found. (8, 4) > (4, 1), so we get a maximum value (8, 4).
  The last tuple, (14, 15, (14, 2)), ends at the boundary of the array, so we immediately return the maximum value (14, 2).

We now get [(11, 2), (8, 4), (14, 2)]. We build the list using step 2 and we're done!

The time complexity should be around ~2n if you choose a good k value.


Yes but...

The synchronization goes against the same bus, that means that every thread in the JVM must wait for other threads who are in the synchronization-block for this bus-instance.

You solved the problem but it realy needs a review:

The prof asked you to use a API. Even if there really is an API you did not named it. The prof must have a solid and clean evidence that you know what exactly an API is.
A seat is not a boolean, the state of a seat can be an boolean. Please wrap the boolean in a class named "Seat".
A passenger neither inherits an Thread nor is to Book a seat the only work a passenger will have. If a Passenger like to book two seats, one for himself and one for his stuff. From documentation of thread this is not possible because: It is never legal to start a thread more than once. Rename the class Passenger to Booking, you can book only once but you can book for multiple persons.
As GreenNovice reason pointedly: The synchronization is not the responsibility of the Passenger, its the responsibility of the Busdriver (lets say the Bus). As GreenNovice clearly worked out, please move the synchronization into the signature of the bookSeat or into the code of bookSeat.
The synchronization works well, no need for the Thread.sleep().
The variable-name of a bus is someCompany? If i read a variable is named someCompany i like to sell all my stocks before i try to call someCompany.stop(). A better name of the variable might be someCompanysCar!

Theese are problems who must occour - because scientific programming is always collective work. No need for blame you.


Improving the performance of interpolating between two arrays

There are some easy wins here. Your interpolate_points doesn't need a loop:

def interpolate_points(p1, p2, n_steps=3):
    """Helper function that calculates the interpolation between two points"""
    # interpolate ratios between the points
    ratios = np.linspace(0, 1, num=n_steps)
    # linear interpolate vectors
    vectors = (1.0 - ratios) * p1 + ratios * p2
    return vectors

Also, even without further vectorization, you should be making use of range in your main function:

def interpolate_arrays(start_array, end_array, n_steps=10):
    """final function that interpolates arrays"""
    array_interpolation = []
    for n in range(n_steps):
        x = []
        for i in range(len(start_array)):
            e = interpolate_points(start_array[i], end_array[i], n_steps)[n]
            x.append(e)
        array_interpolation += [x]
    return array_interpolation

However, all of that can be replaced with a call to interp1d:

import numpy as np
from scipy.interpolate import interp1d

def interpolate_arrays(bounds, n_steps=10):
    """final function that interpolates arrays"""
    bounds = np.array(bounds)

    fun = interp1d(
        x=[0, 1],
        y=bounds.T,
    )
    y = fun(np.linspace(0, 1, n_steps))

    return y

def test():
    X1 = [1.5, 1]
    X2 = [5.5, 3]

    y = interpolate_arrays([X1, X2], n_steps=3)
    assert y.T.tolist() == [[1.5, 1.0], [3.5, 2.0], [5.5, 3.0]]

Even easier:

def interpolate_arrays(X1, X2, n_steps=10):
    """final function that interpolates arrays"""
    return np.linspace(X1, X2, n_steps)

def test():
    X1 = [1.5, 1]
    X2 = [5.5, 3]

    y = interpolate_arrays(X1, X2, n_steps=3)
    assert y.tolist() == [[1.5, 1.0], [3.5, 2.0], [5.5, 3.0]]

Notes:

If you use interp1d, it would be better if your inputs and outputs are both two-dimensional np.ndarray; in their current form they need a transposition
Write some unit tests such as the one shown, although it would be a better idea to call isclose since this is floating-point math
If you want, it is trivial to make this extrapolate as well as interpolate

Basically: if there is a math thing in your head, before even thinking about what it would take to implement it yourself, do a search through scipy/numpy to see if it has already been done for you.


Should I create an abstract runnable? I've 4 sub-classes which perform similar work but only 3 of them have identical constructors

You have field shutdown that you mutating in a multithreaded code, this field can be cached and might ignore you changing it. You can declare it as volatile to avoid this behavior.

private volatile boolean shutdown;

What makes your abstraction leaky is the fact that BackgroundTask is not abstract enough, that is, Manager and client shouldn't be there.

 public abstract class BackgroundTask implements Runnable {

   abstract void executeTask();
   private boolean shutdown;

   @Override
   public void run() {
    while (!shutdown) {
        executeTask();

        // sleep for msSyncInterval
    }
  }
 }

And now we can have an abstract class that does Task involving clients and managers

 abstract class AbstractManagerClientTask extends BackgroundTask { // not sure about the name
   protected final Manager manager;
   protected final Client client;
   .....
 }

ExchangeData is more specific than a BackgroundTask, it is a AbstractManagerClientTask

  class ExchangeData extends AbstractManagerClientTask{
   ...
  }

It's much easier now, RefreshData can extend BackgroundTask with its own Manager field

 public class RefreshData extends BackgroundTask {
  private final Manager manager;
  ....
 }


Checking if a booking can be cancelled or not based on three conditions

You can simply assign the if conditions to the canCancel property of the MyBookingModel like so

mb.canCancel = mb.status != "Cancelled" && ( deptAdmin || isAdmin );

While we are at the properties of the MyBookingModel: Properties should be named using PascalCase casing.

canCancel -> CanCancel  and so on.

and while we are at naming things, why is it MyBookingModel and not just BookingModel ? What does the My buy you ?


A short review

This code passes jshint perfectly, well done. Besides the obvious warning that you did not provide swap of course
The name arrayCopy is perhaps unfortunate, since this works on any array whether it is a copy or not
The name bubbleSort also does not perfectly describe what is going on, it not only bubble sorts the array, but it also tracks the swaps in an animations array
I keep thinking that providing the animations array in the function call is weird, I would return the animations instead, the caller can concat if needed
I see little point in providing an array with i and i+1 unless you animate with different kind of sorting algorithms, so you could just animations.push(i)
Still, very maintainable, correct code.


User guesses the number generated by computer

Preface
I'm going to ignore your teacher's code, at least for the moment, and just review yours.
Based on what you've said, I'm guessing you're still pretty close to the beginning of the learning curve. Based on that, I'm going to go into a little more detail that normal about how to move in a direction I think you'll find beneficial, rather than just talking about where you might like to end up.
Approach
First of all, you currently have all your code in main. It can be extremely helpful to define small, self-contained functions to carry out the overall task, instead of having it all inline in a single function like this.
To do this, I'd start with a really basic outline of what the program is supposed to do:

generate a random number
While they haven't used up their guesses or gotten the right answer:

get a guess at the random number from the user
check whether their guess is high, low, or correct

print out the result

Then I'd consider which of those is easily turned into a separate, self-contained piece of code (hint: most of them).
Then I'd write code in main that worked at pretty much that level, and have it delegate the details to other code. A first stab at it might look something like this:
int main() {
    int secretNumber = generate_random();
    int maxTries = 3;

    for (int guessCount = 0; guessCount < maxTries; guessCount++) {
        int guess = get_guess();
        if (check_guess(guess, secretNumber))
            break;
    }
}

Initially, I wouldn't worry a lot about getting every detail precisely correct. Just try to get something that fits reasonably well with the outline you write in English.
From there, you have a couple of choices. One is to start by writing "mock" versions of most of those. They need to do roughly the right sort of thing, but don't put any effort into really making them do the job correctly. For example, we can write a "mock" "generate a random number" as something like:
int generate_random() {
    return 7;
}

That obviously won't do in the long term, but it's enough that we can use it to write and test the rest of the code. Then do roughly the same with the other functions:
bool check_guess(int guess, int secretNumber) {
    // Todo: add code to print out current result
    return guess == secretNumber;
}

int get_guess() {
    static int guess;

    return guess++;
}

Now we have enough that we can test the basic flow of the program. For example, we can check that when we run it, it doesn't get stuck in a loop; it runs to termination. Once we've established that, we can add enough more to print out each guess, and whether it was right or wrong, and see that as-is, it guesses values for 0 through 10, then quits because it used up the allotted number of guesses. If so, great. If not, we figure out why not and fix that.
Then we change the random number to (say) 5, so it should guess correctly before it runs out of guesses. Then we run that to be sure it does what it should (like, print out the message that you got the right answer, and then quit asking for more guesses once 5 is guessed).
Once we're done verifying that the basic flow of the code in main works correctly, we can expand out those subordinate functions to do their jobs correctly, so generate_random() actually generates a random number, get_guess() really asks the user for input, and do on.
The important point here so to break the large, somewhat complex task down into a number of smaller tasks, each of which is quite simple. This way, it's much easier to define and understand what each piece needs to do, and test the code so we can be sure that it does what it's really supposed to.
Other Points
I think it's worth pointing out that I'm positively impressed with a number of things about your code. You've chosen good, clear variable names, and structured the code so it's really quite clean and understandable. It's longer than your teacher's, but length is rarely a good measure of much of anything, and its length doesn't seem (to me) particularly excessive for what it does. A fair amount of the extra length is simply because your teacher's code is closer to what I've recommended as the first step on the way toward better code--for example, it chooses the same "random" number every time it's run. That's simple and easy to test with, but yours is clearly a more complete program in this regard.
As far as the specific question of whether to use a Boolean variable: it doesn't strike me as necessary in this case, but it's also fairly harmless. I can see writing the code either with or without it, and doubt that either is necessarily much better than the other.