I'd do your code like this. It's a bit cleaner imo, and it has translatable strings in it, if you ever want to translate your theme/plugin:

add_action('add_meta_boxes', 'add_custom_meta_box');

function add_custom_meta_box() {
    add_meta_box('demo-meta-box', esc_html__('Featured Article', 'your_theme_slug'), 'custom_meta_box_markup', 'post', 'side', 'high', null);
}

//create the boxes html markup
function custom_meta_box_markup() {
    global $post;
    $checkbox_value = get_post_meta($post->ID, 'meta-box-checkbox', true);
    wp_nonce_field(basename(__FILE__), 'meta-box-nonce');
    ?>

            <input id="meta-box-checkbox" type="checkbox" name="meta-box-checkbox" value="1" <?php checked( $checkbox_value, 1); ?>/>
            <?php esc_html_e('Featured Article', 'your_theme_slug') ?>

    <?php
}

// save checkbox meta
function save_custom_meta_box($post_id) {
    if (!isset($_POST['meta-box-nonce']) || !wp_verify_nonce($_POST['meta-box-nonce'], basename(__FILE__)))
        return $post_id;

    if(!current_user_can("edit_post", $post_id))
        return $post_id;

    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;

    if( isset( $_POST['meta-box-checkbox'] ) ){
        update_post_meta( $post_id, 'meta-box-checkbox', true );
    } else{
        update_post_meta( $post_id, 'meta-box-checkbox', false );
    }
}

add_action('save_post', 'save_custom_meta_box', 10, 3);

Now, as for creating several rows in the database. It creates one additional field per post in the wp_postmeta table, because you are storing your value in a post meta. This is ok behavior, and shouldn't have any adverse performance effects on your website.

Now what you want is to automatically delete this post meta, if the same is set on a different post. The first thing that comes to my mind is a custom SQL query placed on save.

First you'd need to check to see if any of the posts have this field

global $wpdb;
$wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = 'meta-box-checkbox' AND meta_value = 1", ARRAY_A);

This query will return array of all posts that have your meta-box-checkbox set to 1.

You'll have to check if the current post id is the same as the one in this  query, if it is, you can continue to save, and if it isn't you'd remove (with SQL query) this entry from the postmeta table. Also you could only check if the meta key exists, and if the post id is different, remove it. This will ensure the deletion of the database entry even if the value is 0 (unchecked checkbox).

The other thing that comes to mind is delete_post_meta(). But I think you'd still need to sieve through posts with this post meta key, see if the key exists and the post id's are different, and then delete it with delete_post_meta().


Its unfortunate that roundRobin doesn't work here, as it sounds just right for the task. Some functions (e.g. std.range.zip) have a StoppingStrategy that allows you to determine whether to stop at the shortest or longest range, and I'm not sure why roundRobin doesn't support this.

As @sigod pointed out, the issue with roundRobin was just a simple typo (I missed it too!).
It is probably the best option, but I'll leave my alternative anyways:

import std.range, std.algorithm;

auto translateToSwedish(immutable string english) pure
{
    return english.map!(c => only(c, 'f')).joiner;
}

void main()
{
    assert(translateToSwedish("Hello").equal("Hfeflflfof"));
}

map replaces each character c with the sequence c'f'.
joiner links these pairs of character into a single range.

Note the use of the auto return type. Returning a string would imply eagerly committing the result within translateToSwedish. However, we don't know what the user of translateToSwedish will do with the result; if they are just passing it to another range-manipulating-function, they'd much rather we give them a range.

You'll notice many D functions are written like this. You generally want to keep passing around ranges until it is absolutely necessary to evaluate the result.

With that in mind, lets allow translateToSwedish to operate on a range as well:

import std.traits, std.range, std.algorithm;

auto translateToSwedish(R)(R english) pure if (isSomeString!R)
{
    return english.map!(c => only(c, 'f')).joiner;
}

void main()
{
    assert(translateToSwedish("Hello").equal("Hfeflflfof"));
}

Now translateToSwedish is well equipped to be used in a lazily evaluated function chain:

auto result = "Hello"
    .translateToSwedish
    .translateToGerman
    .translateToPigLatin
    // and so on


JavaScript breadth-first search algorithm

Just going to make a few comment on your Queue implementation.

  Should your data be an object this.data = {};?

This is a matter of taste, but I would have opted for an array or a linkedlist data structure if I were you. Using an array, you can easily push items without a key . From my perspective ,you are basically passing the same name for the key/value pair in the enqueue.

  How to retrieve the total number of items enqueued?

I believe your class should  data should only be private to your class. hence the data count should be accessed using a getter function e.g

this.count = function() {
    return this.data.length;
  };

  What should your enqueue look like?

basically, your Queue class is not reusable as it's dependent on having key/value pair has an input. I reckon the enqueue function should take only one value .  In this case John. A pseudocode

    enqueue(value) {
      // created an empty if statement - note if value is undefined this will evaluate to true as well as null ==null
      if (value == null);
      else {
        if ( //data enqueued has exceeded the current array length) {
          let newcapacity = Math.floor(this.count() * this.growfactor / 100);
          // create a new array with the capacity and copy the old array elements to a new one.
        }

        this.size++;
        // assign the item to an empty index
        this.data[index] = value;
      }
    }
    }

Although, the above is more or less a C# equivalent but the main idea is you only enqueue items when they are not null/undefined - hence I used == as opposed to === as undefined== null results in true and null==null results in true . This is equivalent to

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}

The newCapacity is simply a strategy to increase the size of an array.

  How to easily delete an item using an array?

Constantly, you need to check if your array's size is zero then throw an exception else call the array's shift() function to delete the first item and update the array.

dequeue() {
  if (size === 0) {
    throw "the queue contains no items";
  }
  this.data.shift();
}

  Note: there are some very useful Queue functions that can be added to your class :

peek() : returns the first item in the queue
contains : Check if an item exist
isempty()- checks if an item is empty

I hope this helps.


Alias notation
Your table aliases a1/a2 and c1/c2 are not good. In this very short query it may not matter, however names for aliases, variables, parameters, etc. should be descriptive enough to say something about what they represent. Besides, with 4-5 character table names, is it really that much to type? I would use Actor1/Actor2 and Cast1/Cast2.
In fact, given the nature of your query, you could give them even more useful names... how about MaleAct/MaleCast and FemAct/FemCast!
Old style JOIN
This JOIN syntax should not be used:
FROM Actor AS a1, Actor AS a2, Cast AS c1, Cast AS c2
WHERE c1.mid = c2.mid AND
      a1.id = c1.pid    AND
      a2.id = c2.pid    AND

Instead:
FROM Actor AS MaleAct
    INNER JOIN Cast AS MaleCast ON MaleAct.id = MaleCast.pid
    INNER JOIN Cast AS FemCast ON MaleCast.id = FemCast.id
    INNER JOIN Actor AS FemAct ON FemAct.id = FemCast.pid

Multiple counting
I see you COUNT(*) 3 times within your query. Since you're already selecting the COUNT(*) into your result set, and MySQL will allow you to use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
This:
HAVING COUNT(*) > 0
ORDER BY COUNT(*) DESC;

Instead:
HAVING num_films > 0
ORDER BY num_films DESC;

That should speed up your query a bit too.
Everything together
SELECT MaleAct.fname, MaleAct.lname, FemAct.fname, FemAct.lname, count(*) AS num_films
FROM Actor AS MaleAct
    INNER JOIN Cast AS MaleCast ON MaleAct.id = MaleCast.pid
    INNER JOIN Cast AS FemCast ON MaleCast.id = FemCast.id
    INNER JOIN Actor AS FemAct ON FemAct.id = FemCast.pid
WHERE
      MaleAct.gender = 'M' AND
      FemAct.gender = 'F'
GROUP BY MaleAct.id, FemAct.id, MaleAct.fname, MaleAct.lname, FemAct.fname, FemAct.lname,
HAVING num_films > 0
ORDER BY num_films DESC;


Thread pausing/resuming/canceling with Qt

The code you have is unsafe, because pause() and cancelWork() are called from outside the worker's thread, and they use no locking when modifying the worker's members.

In general, prefer to interact with objects in other threads by invoking their slots via queued connections, unless there's a pressing reason to act immediately.  This means you don't need any of the synchronization facilities inside the worker.  This simplifies the coding, and makes it easier to test.

To do that, the worker needs to periodically process events.  I prefer to put this in a function of its own:

bool isCancelled() {
    auto dispatcher = QThread::currentThread()->eventDispatcher();
    if (!dispatcher) return false;
    dispatcher->processEvents();
    return m_cancelRequested;
}

In the work method, this can be called every time you want to poll for cancellation.

You need some protection against re-entering doWork() from this event queue.  One way to manage this is with a tiny state-machine:

private:
    enum State { IDLE, RUNNING, PAUSED };
    State state = IDLE;

Used like this:

void MyWorker::doWork()
{
    if (state == RUNNING)
        return;

    state = RUNNING;
    emit started();

Here's my complete, tested version - no locks or atomics, all the synchronization is managed by Qt:

#include <QAbstractEventDispatcher>
#include <QObject>
#include <QThread>
#include <QDebug>

class Worker : public QObject
{
    Q_OBJECT

public:
    explicit Worker(QObject *parent = 0)
        : QObject(parent)
    {
    }

signals:
    void started();
    void finished();

public slots:
    void pause()
    {
        auto const dispatcher = QThread::currentThread()->eventDispatcher();
        if (!dispatcher) {
            qCritical() << "thread with no dispatcher";
            return;
        }

        if (state != RUNNING)
            return;

        state = PAUSED;
        qDebug() << "paused";
        do {
            dispatcher->processEvents(QEventLoop::WaitForMoreEvents);
        } while (state == PAUSED);
    }

    void resume()
    {
        if (state == PAUSED) {
            state = RUNNING;
            qDebug() << "resumed";
        }
    }

    void cancel() {
        if (state != IDLE) {
            state = IDLE;
            qDebug() << "cancelled";
        }
    }

protected:

    enum State { IDLE, RUNNING, PAUSED };
    State state = IDLE;

    bool isCancelled() {
        auto const dispatcher = QThread::currentThread()->eventDispatcher();
        if (!dispatcher) {
            qCritical() << "thread with no dispatcher";
            return false;
        }
        dispatcher->processEvents(QEventLoop::AllEvents);
        return state == IDLE;
    }

};

class MyWorker : public Worker
{
    Q_OBJECT

public:
    explicit MyWorker(QObject *parent = 0)
        : Worker(parent)
    {
    }

    void doWork()
    {
        if (state == PAUSED)
            // treat as resume
            state = RUNNING;

        if (state == RUNNING)
            return;

        state = RUNNING;
        qDebug() << "started";
        emit started();

        // This loop simulates the actual work
        for (auto i = 0u;  state == RUNNING;  ++i) {
            QThread::msleep(100);
            if (isCancelled()) break;
            qDebug() << i;
        }

        qDebug() << "finished";
        emit finished();
    }
};

#include <QCoreApplication>
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    QThread thread;
    auto worker = new MyWorker();
    worker->moveToThread(&thread);
    QObject::connect(&thread, &QThread::started, worker, &MyWorker::doWork);
    QObject::connect(worker, &MyWorker::finished, worker, &QObject::deleteLater);
    QObject::connect(worker, &QObject::destroyed, &thread, &QThread::quit);
    QObject::connect(&thread, &QThread::finished, &app, &QCoreApplication::quit);

    thread.start();

    // To saved defining more signals, I'll just use invoke() here.
    // Normally, we connect some "driver" object's signals to the
    // pause/resume/cancel slots.
    auto const m = worker->metaObject();
    QThread::sleep(1);
    m->invokeMethod(worker, "pause");
    QThread::sleep(4);
    m->invokeMethod(worker, "resume");
    QThread::sleep(1);
    m->invokeMethod(worker, "cancel");

    app.exec();
}

Sorry this is a bit rushed; I hope the principle is clear.


LinkedList implementation with Iterators in Java

Use (at least parts of) the source, Luke

You mentioned that you decided to implement iterators on your own, but you could at least use the standard Iterator interface. It's almost the same as what you did, having only two methods, hasNext, and next. Not only it's standard so that it should be familiar to all readers, those are better names too, and follow the camelCase convention of the language.

What's in a name?

Using a common vocabulary helps programmers understand each other's code. It's OK to implement a common library class on your own for practice, but to facilitate communication, it's good to stick to the common vocabulary. So in the future I suggest to use the same names for methods used by the JDK, unless there is a good reason to deviate.

Inner classes

When possible, it's good to make inner classes static, so that instances of those classes don't hold a reference to the enclosing class. You could make ListIterator static by passing mBase to its constructor.

Performance

The getSize method had \$O(n)\$ time complexity, because it iterates over the elements every time it's called. (Btw, it's a bit ironic that the implementation doesn't use the iterator, what a missed opportunity!) You could do better, at the expense of an integer field, incremented when you add a new item, decremented when you remove an item. The there time complexity would become \$O(1)\$.

Simplify

This can be written simpler:

   boolean isNext(){
        if (next == null) return (false);
        return (true);
    }

Like this:

   boolean isNext() {
        return next != null;
    }


Improving efficiency for finding longest contiguous non-decreasing substring

Your algorithm is basically fine, but it is expressed in the code clumsily.

The biggest problem is the interface of the function: it should accept a string parameter and return a string.  Instead, your function takes s from its environment and uses the global variable largest to store the answer.  Although there is a return largest statement, it is very misleading.  What actually happens is that s[index] raises an IndexError, so that the return largest is never reached, and the answer is passed back using the global variable instead.

The root cause for the IndexError is that there are too many variables, causing confusion.  With each iteration through the loop, you increment index, prev_index, and count.  That means that those three variables could be reduced to one, which could just be called i.  (If you think about it, you'll find that count is always one less than index.  Since the loop condition is count < len(s), s[index] will go one position beyond the end of the string.)

The next observation to make is that your if and elif blocks are almost identical.  You can combine them by using >= for the test.

Python strings are immutable, so largest = test[:] could just be largest = test.

Putting everything together…

def longest_nondecreasing_substring(s):
    if s is None or len(s) <= 1:
        return s

    longest = test = s[0]

    for i in range(1, len(s)):
        if ord(s[i]) >= ord(s[i - 1]):
            test += s[i]
        else:
            if len(longest) < len(test):
                longest = test
            test = s[i]
    if len(longest) < len(test):
        longest = test
    return longest


For cases like this:

if padding < 0:
        print "Image too small to encode the file. \
You can store 1 byte per pixel."
        exit()

It's probably better to define a custom exception and raise that:

class SizeError(Exception):
    pass

...

if padding < 0 :
    raise SizeError("Image too small to encode the file. \
    You can store 1 byte per pixel.")

I'm no security expert, but is it ok to use the string you want to encode as salt in kdf? This looks like security through obscurity (because it means you just double the input before encrypting).


Ok, given that you're after some CR on your understanding (and usage) of OO techniques, I'll go through your code almost line by line. If my criticisms strike you as blunt, please keep in mind that my goal is to help, not to offend.

Coding standards
This has become a bit of a hang-up of mine, but I can't stress enough how important it is to write code that conforms to some form of standard. PHP, of course, does not (yet) have an official standard as such, but the unofficial PHP-FIG standard is widely accepted, and all major players (Zend, Symfony, CakePHP, ... the list is on the site) subscribe to this standard. As should you.

This entails, among other things:

property names don't start with an underscore to indicate visibility (private, protected). That's what we did in the PHP4 days. I think none of us is willing to go back to that era.
Opening braces for methods, functions and classes go on a new line
Code is indented by spaces, 4 of them, tabs are not to be used. If you use nothing but tabs, then that's an acceptable deviation from the standard, but be consistent. SVC's like Git will give you grief otherwise.
access modifiers aren't optional, they are required.
Method names are camelCased, variables/properties are either camelCased or you can use underscores. Either way: be consistent. I prefer camelCased properties.

Type-hinting all the way
I see you use the occasional type-hint. That's great! Fantastic even, but you're not using them as much as you can. You can't hint for primitive types, but you can use doc-blocks, casts and you can hint for array variables.
More on this later.

Your code, at a glance
Rather than listing my recommendations and linking to the wiki of the SOLID principles, let's get stuck in and review your actual code. I'll already change a thing or 2 to make your code more readable (ie conforming to the PHP-FIG standards):

class SchoolSoap
{
    /**
     * @var array
     */
    protected $config = array();

Stop here (yes, already). I've removed the underscore, but I wonder: why are you initializing your property to an empty array, if you have a constructor that will always re-assign that property? Just initialize the properties to null if you don't need them to have a specific default value.
I've also added a doc-block that makes it clear to everyone what this property is expected to be, what you'll assign it to, and how it'll be used. This will help your IDE provide you with useful auto-completion info, and error reporting.

    /**
     * @var \SoapClient
     */
    public $soap = null;
    /**
     * @var string|null
     */
    public $error = null;
    //add your own doc-blocks from now on :)
    public $params = null;
    public $result = null;

Now, the methods:

    /**
     * Some info about the construct, will show in auto-complete
     * with any decent IDE
     * @param array $params = array()
     * @return $this
     */
    public function __construct(array $params = array())
    {
        $this->config = $params;
        try
        {//this is non-standard, but I use allman indentation
         //that's my guilty pleasure
            $this->soap = new SoapClient(
                $this->config['url'],
                    array(
                        'trace' => 1,
                        'exception' => 1
                    )
                );
        }
        catch (Exception $e)
        {
            $this->error = $e->getMessage();
        }
    }

So, I've cleaned up a bit, but there are still quite a few issues left. For starters: you allow for the user to pass an array $params to the constructor. If he fails to do so, then that's fine, but the array defaults to an empty array. That, too, isn't a problem, but what is problematic is that you create the instance of SoapClient using $this->config as though it is an associative array and as though it has certain keys set!. You don't do any isset checks (meaning your code might emit notices).

Then, if the SoapClient could not be constructed, you catch any Exception that might have been thrown. But SoapClient doesn't throw Exception instances, it throws a specific type of exceptions: SoapFault.
Catching any higher (as in parent of a particular exception) type of exception is known as pokemon exception handling. It reads as if the code was written by somebody who didn't really know what to expect.

Not that this really matters, because your entire class revolves around this SoapClient instance being set. If it fails, then your class shouldn't be allowed to exist. It's likely that the code creating the instance contains a bug, and provided faulty data. That kind of thing should be communicated immediately: the error shouldn't be caught by you, because you can't fix it: the error should be thrown back to the user! That's Why I'd suggest you write this as a constructor:

/**
 * Simple wrapper constructor
 * @param string $wsdl
 * @param array $options = null
 * @return $this
 * @throw SoapFault
 */
public function __construct($wsdl, array $options = null)
{//make options null by default, but force wsdl to be passed explicitly
    $this->config = $options
    $this->soap = new SoapClient(
        $wsdl,
        $this->config
    );
}

We end up with less code, but again: with a decent IDE, you'll get more information about what this constructor does when you type new SchoolSoap(.
You no longer need the $this->error property, and don't have to hope that the user will check that property's value: if an error occurred, he'll get an exception thrown at him, which is as it should be!

The other methods should be easy to improve, along the same lines:

/**
 * Perform a soapCall to $function, passing $parameters
 * If no parameters are provided, $this->params will be used
 * @param string $function
 * @param array $parameters = null
 * @return bool
 * @throw SoapFault
 */
public function actionSoap($function, array $parameters = null)
{
    if ($parameters === null)
        $parameters = $this->params;
    //assign to property directly, don't use temp var... no need
    $this->result = $this->soap->__soapCall(
        $function,
        array(
            'parameters' => $parameters
        )
    );
    return true;//wouldn't return $this->result; be more usefull?
}

The setter methods are a great idea. I especially like their being fluent (chainable), nothing but formatting needs to change there:

public function setParam($params)
{
    $this->params = $params;
    return $this;
}

A wrapper is best when it exposes its object
What you have written here is, essentially, a wrapper object: it wraps an instance of SoapClient, to offer a different (possibly neater, safer and clearer) API.
However, I need a reason to use a wrapper, it should allow me to do what I want. This wrapper severely restricts my usage of the SoapClient class. What's to stop me from simply writing this:

$schoolSoap = new SoapClient($wsdl, $options);
$result = $schoolSoap->__soapCall($function, $params);

A wrapper should somehow expose some of the internals of the wrapped object, but perhaps check the arguments that the user is trying to pass, or at least offer constants that the user can use to facilitate the manipulation of the wrapped object. The blindest, slowest, but easiest way to do so is by implementing a magic __call method in your SchoolSoap class:

public function __call($method, array $args)
{
    if (method_exists($this->soap, $method))
    {//perhaps add an is_callable check here, too
        $return = call_user_func_array(
            array($this->soap, $method),
            $args
        );
        if ($return === $this->soap)
            return $this;//don't return the wrapped object
        return $return;
    }
    throw new \BadMethodCallException(
        sprintf(
            "Method '%s' does not exist in classes %s and %s",
            $method,
            __CLASS__,
            get_class($this->soap)
        )
    );
}

Of cours, a safer way is to implement certain methods of the wrapped objects in your wrapper, check the arguments and then call the wrapped object's method:

public function getLastResponse($fromObject = false)
{
    if ($fromObject === false)
        return $this->result;//as set in the `actionSoap` method
    return $this->soap->__getLastResponse();//from wrapped object
}

This is a clean, easy to maintain and safe way to expose your wrapped object, and it doesn't give me, as a user, a reason not to use your class.
Of course, if you do this, then you don't need that slow magic __call method anymore, and you can simply do away with that (as well you should).
An in-between solution is to have a private property, holding an array with methods that can be called by the user, and use those in your __call method. That saves you some method_exists calls.

Ok, I'll leave you with this final recommendation concerning the first of your classes:

Passing arrays to constructors is easy, and shortens the number of arguments your methods take. I can see why one would do this. However, if you are going to write OO code, then it can be safer/better still to pass data objects containing that same information. You can type-hint for those specific objects, and be sure that the properties you need will exist.

I could post an example here, but instead I'd invite you to check this github fork of mine, and in particular the Config class. The Config is what, logically, configures the behaviour of all classes that make API calls. By hinting for an instance of that object in the constructor, I can rest assured that things like the url, usage mode, user and API-KEY will be set, and ready to be used. I use getters and setters throughout the code, to ensure my data is correctly formatted and sanitized, too.
there are some magic getters and setters, and I thing also a magic __call method somewhere, but I'm still working on the code, to get rid of them.

If you compare my fork to the code I started off with, I think it's pretty clear that passing data objects is a big step forwards.

There are other things in your code that I will discuss further (like your use of the dreaded static keyword), so I will be adding to this answer from time to time. For now, though, I think I've given you sufficient food for thought.

Update

As promised: Back for some more reviewing-stuff. I'll start off with that one helper class you've included, and take it from there. I already mention the static keyword isn't to my liking. Why isn't it? Well, static properties/variables are variables that retain their state. That means that, if a function has a static variable, and you assign a value to that var, that value is kept in memory in between function calls.
Class properties work similarly, but that value is shared between all instances of that class. You can also access that property at without an instance, as though it were a global variable. And that's the problem with statics: they are, essentially globals in OO disguise, and we all know globals are bad.

Same goes for your method: it works like a function, and is globally accessible, like a global function. Only, static method calls are slower than function calls! Then why bother with a class, and not simply create a function?
That would, indeed be better than what you have now, but it's not in tune with your wanting to write more OO code

So let's make it object oriented, and make good use of the advantages of OOP: you can use properties to store certain things, and like, for example your SoapClient instance. At the moment, you create a new SoapClient instance every time you instantiate SchoolSoap. Wouldn't it be nice if we only had to do that once? Your static method now creates a new SchoolSoap instance every time it is called, without being passed an existing instance already, because its functionality depends on that SchoolSoap being there. What's more: it's function in your program is a specific use-case of the capabilities of SchoolSoap. So its job is the same (performing a SOAP call), only its a specific type of call.

In OO code, it wouldn't be uncommon to see StudentHelper being a child of SchoolSoap. Therefore, I suggest you go down that route, and use inheritance:

class StudentHelper extends SchoolSoap
{
    public function getStudentList($params)
    {
        $result = $this->setParam($params)
            ->actionSoap('studentList');
        if (!$result)
            return $result;
        return $result->studentList;//or $this->_result->studentList;
    }
}

All the calls you have, that deal with students go in this class, and for each group of calls, you can create a new child class of SchoolSoap.
The usage is very simple:

$student = new StudentHelper($config);//what you pass to SchoolSoap's constructor
$studentList = $student->getStudentList($params);
$student->addStudent($params);//if that call exists

All of the goodies that SchoolSoap (methods and properties) are also properties of StudentHelper now (except for private properties), same goes for methods.

Of course, now the name StudentHelper is a bit weird, because it isn't a helper anymore: it's a full-blown wrapper, too, so I'd change the name of SchoolSoap to BaseSoap, because it's your base class, and change StudentHelper to StudentSoap or something, to better reflect what the class is.

I've posted a review of a singleton class on this site a while back. In it, I go into more details on why statics are to be avoided, feel free to check it out:

Singleton design pattern


jQuery plugin to cycle through text and "typewrite" it out

The API design is rather weird.  You expect your plugin to be called like

$().typeText({ selector: '.words' })

But a design like this would be much more natural for jQuery:

$('.words').typeText()


Bidirectional BFS on a matrix in Python 2.7

isValidIndex handling two "indices" seems wrong. At least the condition you spell becomes too long. Besides, the condition looks somewhat inside-out. Consider

def isValidIndex(index, grid):
    return 0 <= index[0] < len(grid) and 0 <= index[1] < len(grid[0])

That said, AFNP principle tells that you don't really need this function at all:

    for (x1,y1,x2,y2) in queries:
        try:
            result.append(findPath(x1,y1,x2,y2,grid))
        except IndexError:
            results.append(0)

find_path_from_source has an execution path which returns nothing. Here you can get away with it, but the practice is in generally dangerous and indicates sloppy coding.
The repetitive code in find_path_from_source should be wrapped in the loop:

    for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        try:
            if bool_grid[x + dx][y + dy] == other_val:
                return 1
            if bool_grid[x + dx][y + dy] == 1:
                bool_grid[x + dx][y + dy] = val
                queue.append([x + dx, y + dy])
        except IndexError:
                pass

The bool_grid name is misleading. What is bool about it?
Copying a large grid may hurt the performance. An alternative is to compare visited cells: once they have a common element, the path is found. Implementing them as sets may make it quite fast. Of course, when in doubt, profile.


Avoid using namespace std.
Assuming sizeof(int) is 4, the height array takes more than 40 MB of space. I understand that by modern standards it is a small change, but still a good citizen should not request more than is really needed.

I recommend a stream-like processing: read 2 bytes, convert them, and print out. This way you only need 2 bytes of storage.
The program terminates each row with a dangling comma. I don't know what the RFC says about it. Consider however

    for(int x = 0; x < SRTM_SIZE; x++) {
        for(int y = 1; y < SRTM_SIZE - 1; y++) {
            meinFile << height[x][y] << ",";
        }
        meinFile << height[x][SRTM_SIZE - 1] << std::endl;
    }

You test reading errors. Writing may also fail.
Error detection is important. Error reporting is equally important.

Can't open file - why? Is it insufficient permission? file not found? corrupted media?

Can't read file - why? Can't write file - why?

Check out strerror, perror or similar facilities.


I have refactored some of your code, please note that I am ignoring pre-existing libraries since I assume there's a particular reason (educational or otherwise) behind implementing Clock, tick, etc. this way on your own.
class Clock:
class Clock:
    def __init__(self, hours: int, minutes: int, seconds: int):
        self.hours = self.normalize_time_in_range(hours, 0, 23)
        self.minutes = self.normalize_time_in_range(minutes, 0, 59)
        self.seconds = self.normalize_time_in_range(seconds, 0, 59)

    @staticmethod
    def normalize_time_in_range(value: int, lower_bound: int, upper_bound: int) -> int:
        if value < lower_bound:
            return lower_bound
        elif value > upper_bound:
            return upper_bound
        else:
            return value

    def start_ticking(self):
        while True:
            self.tick()

    def tick(self):
        print(f"{str(self.hours).zfill(2)}:{str(self.minutes).zfill(2)}:{str(self.seconds).zfill(2)}")
        self.seconds += 1
        time.sleep(1)
        if self.seconds == 60:
            self.seconds = 0
            self.minutes += 1
            if self.minutes == 60:
                self.minutes = 0
                self.hours += 1
                if self.hours == 24:
                    self.hours = 0

normalize_value_in_range: Notice you have a lot of duplicated logic in set_time and set_alarm. Most of the logic can be extracted to this more generic implementation.
start_ticking and tick: In your case I found it useful to seperate the loop from the actual tick logic so you can change the loop conditions in subclasses while reusing tick. You will see why this is useful in AlarmClock.
Type annotations: As you can see in the method heads I added some type hints to the newly added methods. This is generally a good idea in regards to documenting your code for yourself and others.

class AlarmClock:
class AlarmClock(Clock):
    def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):
        super().__init__(hours, minutes, seconds)

        self.alarm_hr = self.normalize_value_in_range(alarm_hr, 0, 23)
        self.alarm_min = self.normalize_value_in_range(alarm_min, 0, 59)
        self.alarm_sec = self.normalize_value_in_range(alarm_sec, 0, 59)

        self.ticking = False

    def start_ticking(self):
        self.ticking = True
        while self.ticking:
            self.tick()

    def tick(self):
        super().tick()
        if self.hours == self.alarm_hr and self.minutes == self.alarm_min and self.seconds == self.alarm_sec:
            print("ALARM ALARM ALARM ALARM ALARM!!!!")
            self.ticking = False

normalize_value_in_range: We can now reuse this method to set our alarm time as well.
start_ticking and tick: Since we seperated the loop from the actual tick we can use Clock.tick() in our AlarmClock without the need for duplicate code. Adding the attribute self.ticking to AlarmClock allows us to break out of the loop across methods. The reason we could not reuse tick() before was because it contained the infinite while True loop, thereby not allowing us to intercept when the alarm_time is reached.

class Time:
Lastly, I would suggest seperating time logic from clock logic. This makes the clocks more concise and allows you to extend the functionality of the Time class as needed. You could also say it allows the clocks to focus on their main functionality. Again, I am ignoring the existence of libraries for this task, since I presume you want to implement the entire logic on your own. Specialized libraries like datetime are worth looking into since they provide a lot of comfortable functionality. One implementation might be the following:
class Time:
    def __init__(self, hours: int, minutes: int, seconds: int):
        self.hours = self.normalize_value_in_range(hours, 0, 23)
        self.minutes = self.normalize_value_in_range(minutes, 0, 59)
        self.seconds = self.normalize_value_in_range(seconds, 0, 59)

    @staticmethod
    def normalize_value_in_range(value: int, lower_bound: int, upper_bound: int) -> int:
        if value < lower_bound:
            return lower_bound
        elif value > upper_bound:
            return upper_bound
        else:
            return value

    def increment(self):
        self.seconds += 1
        if self.seconds == 60:
            self.seconds = 0
            self.minutes += 1
            if self.minutes == 60:
                self.minutes = 0
                self.hours += 1
                if self.hours == 24:
                    self.hours = 0

    def __eq__(self, other):
        return self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds

    def __str__(self):
        return f"{str(self.hours).zfill(2)}:{str(self.minutes).zfill(2)}:{str(self.seconds).zfill(2)}"

class Clock:
    def __init__(self, hours: int, minutes: int, seconds: int):
        self.time = Time(hours, minutes, seconds)

    def start_ticking(self):
        while True:
            self.tick()

    def tick(self):
        print(self.time)
        self.time.increment()
        time.sleep(1)

class AlarmClock(Clock):
    def __init__(self, hours, minutes, seconds, alarm_hr, alarm_min, alarm_sec):
        super().__init__(hours, minutes, seconds)
        self.alarm_time = Time(alarm_hr, alarm_min, alarm_sec)

        self.ticking = False

    def start_ticking(self):
        self.ticking = True
        while self.ticking:
            self.tick()

    def tick(self):
        super().tick()
        if self.time == self.alarm_time:
            print("ALARM ALARM ALARM ALARM ALARM!!!!")
            self.ticking = False


You can use rowMeans with indexing.

k <- which(is.na(cancer1), arr.ind=TRUE)
cancer1[k] <- rowMeans(cancer1, na.rm=TRUE)[k[,1]]

Where k is an indices of the rows with NA values.


HTML page listing product characteristics

HTML has elements that carry semantics. For example ol is an ordered list, ul an unordered one. Programs can use that meaning for ease of navigation, reader mode, better search results and so on. Certain elements don't carry that semantic, and
 is one of them.

Let's have a look at one of your snippets to see what one can improve.

c) Delicate

1.Uneven dot surface enlarges the heating area.

2.Die casting aluminium alloy and far-infrared coating.

3.Even heating.

4.Clear print effect; accurate color rendition.

First of all, that's invalid markup. The  and the
 tag intersect, which must not happen. Next, we have a list. It's apparently ordered, therefore we should use an
. And last, the
…
 looks like a headline, so it should be a h*. For this small snippet, we see that the following snippet contains all the semantics:

Delicate

Uneven dot surface enlarges the heating area.

Die casting aluminium alloy and far-infrared coating.

Even heating.

Clear print effect; accurate color rendition.

This is especially important to screen readers or other users that look for a structure. A blind person can decide to jump over a list; it's much more harder to jump over breaks in a paragraph.

So check what tags like
,
 and so on mean. Not only do they carry some kind of representation (this should look like a paragraph, this should look like a headline), but also meaningful semantics (this is a paragraph, this is a headline). Also, the code gets easier to read.

If you want to change they appearance, use CSS afterwards, e.g.

/* just an example to make it slightly more smoother */
body { line-height: 1.4; margin: auto; max-width: 80ex; }
h1 { font-size: 1.5em; }
h2 { font-size: 1.25em; }
li { padding-left: 1ex; }
li+li { margin-top: 0.4ex; }

3D Sublimation Vacuum Heat Transfer Press Printer Machine ST-3040

It is a all-in-one machine that can transfer many sublimation blanks, mug, latte mug, plate, hat, t-shirt, iphone/ipad case, metal, glass, crystal, etc.

Feature / Intelligent

Easy operation. You can only need to set the temperature and time.

Well-designed user interface.

Needs no operations other than placing the workpieces in and taking them out.

Multi-functional

It can widely print on mug, glass, crystal, acrylic, plastic, wood, metal, stone, fabric, etc.

It can print on mugs of different shape and size with corresponding fixtures.

large print size; clear print effect; accurate color rendition; better performance than traditional heat transfer printers.


Count of request per second, minute in java

The first thing I noticed.
The calendar in the constructor. If you wanted to test this class it would be really difficult because you
are dependent on the Calendar implementation, and you have no control over the value it will return. It would be better to inject the calendar in to the
constructor, or Abstract the desired functionality in to an interface and inject that. This will also allow you to use one instance for your entire application.
instead of constructing a separate one in the count method.
injecting the calendar:
public StatisticService(final Calendar calendar) {
        this.calender = calendar;
        this.currentSecond = new AtomicInteger(calendar.get(Calendar.SECOND));
        this.currentMinute = new AtomicInteger(calendar.get(Calendar.MINUTE));
        this.count = new AtomicInteger();
        this.minutesCount = new AtomicInteger();
    }

Creating an interface:
Using an interface gives you flexibility around the implementation of the counter. If in the future you want to change from using
a Calendar to something else only the code implementing the interface will change and classes dependent on it will be unchanged.
public interface TimeProviderService {
    Integer getSecond();

    Integer getMinute();
}

Second
It is a lot more expensive to create a new AtomicInteger class then to just set it to zero.
So here instead of constructing a new class just reset the integer.
//if it is new second, then clear second count and set new current second
            if (newSecond != prev) {
                count.set(0);
                return newSecond;
            } else {
                count.incrementAndGet();
                return prev;
            }

Third suggestions for locking.
Atomic classes are great but in this instance since you are wanting the entire count method to
be atomic I would suggest using your own lock. It simplifies the code for people trying to read it later and the entire
method would be synchronized instead of just when you're accessing the atomic integers.
Also, locking inside of a lock is asking for a deadlock. See Here.
currentMinute.getAndUpdate(prev -> {
            ...
                minutesCount.incrementAndGet();
            ...
        });

Finally
Here is what the class would look like if you implemented the suggestions I am proposing.
Time Providers
public interface TimeProviderService {
    Integer getSecond();

    Integer getMinute();
}

public class CalendarTimeProviderService implements TimeProviderService {
    private final Calendar calendar;

    public CalendarTimeProviderService(Calendar calendar) {
        this.calendar = calendar;
    }

    @Override
    public Integer getSecond() {
        return this.calendar.get(Calendar.SECOND);
    }

    @Override
    public Integer getMinute() {
        return this.calendar.get(Calendar.MINUTE);
    }
}

Statistic Service
public class StatisticService {
    private final TimeProviderService timeProviderService;
    private final Lock lock = new ReentrantLock();
    private int currentSecond;
    private int currentMinute;
    private int count;
    private int minutesCount;

    public StatisticService(TimeProviderService timeProviderService) {
        this.timeProviderService = timeProviderService;

        this.currentSecond = this.timeProviderService.getSecond();
        this.currentMinute = this.timeProviderService.getMinute();

        this.count = 0;
        this.minutesCount = 0;
    }

    public void count() {
        this.lock.lock();

        try {
            int newSecond = this.timeProviderService.getSecond();
            int newMinute = this.timeProviderService.getMinute();

            // seconds
            if (newSecond != currentSecond) {
                this.count = 0;
                this.currentSecond = newSecond;
            } else {
                this.count = this.count + 1;
            }

            // minutes
            if (newMinute != currentMinute) {
                this.minutesCount = 0;
                this.currentMinute = newMinute;
            } else {
                this.minutesCount = this.minutesCount + 1;
            }

        } finally {
            // make sure we are unlocking no matter what happens
            this.lock.unlock();
        }
    }
}

one final note
I did not change anything about how you were calculating the time I just changed the way you are doing it. I do not the problem you
are trying to solve, so I cannot speak on the best way.


Calculating population standard deviation

The easiest way to make mean() more pythonic is to use the sum() built-in function.

def mean(lst):
    return sum(lst) / len(lst)

Concerning your loops on lists, you don't need to use range(). This is enough:

for e in lst:
   sum += e

Other comments:

You don't need parentheses around the return value (check out PEP 8 when you have a doubt about this).
Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative ("returns the mean of lst").
Why do you use "-1" in the return for stddev? Is that a bug?
You are computing the standard deviation using the variance: call that "variance", not sum!
You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)
You shouldn't use pow() anyway, ** is enough.

This would give:

def stddev(lst):
    """returns the standard deviation of lst"""
    variance = 0
    mn = mean(lst)
    for e in lst:
        variance += (e-mn)**2
    variance /= len(lst)

    return sqrt(variance)

It's still way too verbose! Since we're handling lists, why not using list comprehensions?

def stddev(lst):
    """returns the standard deviation of lst"""
    mn = mean(lst)
    variance = sum([(e-mn)**2 for e in lst]) / len(lst)
    return sqrt(variance)

This is not perfect. You could add tests using doctest. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.


Defining transpose on a collection of irregular collections

Yes, traspose defined such that it shrings the result to the size of the shortest list isn't an involution. Your idea of viewing lists as maps is nice, but I suppose once you leave Lists, there are other easier options.

As you observed, List[A] is also a PartialFunction[Int,A] that works on integers that are between 0 and the size of the list. Now if we have a list of lists, it's PartialFunction[Int,PartialFunction[Int,A]]. Now we can convert such functions into a single function by a process called un-currying. While Scala has uncurried for plain functions, it lacks it for PartialFunctions. But it's not difficult to define it:

def uncurried[A,B,C](f: PartialFunction[A,PartialFunction[B,C]]):
    PartialFunction[(A,B),C] =
  Function.unlift((x: (A,B)) => f.lift(x._1).flatMap(_.lift(x._2)));

So we can apply uncurried immediately on List[List[A]] (or rather to Seq[Seq[A]] to avoid O(n) access for lists) and we get a functional representation that accepts a pair of indices and gives the result. If we swap the indices in a pair, we get a transposed view.

The problem with this representation is that we can't enumerate all matching indices easily. If this is required, we could instead convert a list of lists into Map[(Int,Int),A], perhaps a SortedMap so that we can enumerate the indices in a proper order.  Again, this will be a PartialFunction[(Int,Int),A], but also with this additional ability.


Looks fine (maybe some stricter formatting could help readibility, but not an issue), so I'll suggest completely optional improvements that might help spotting important improvements.

As a general principle, try to be ready for bogus values in your input so you can avoid generating nonsense. Being more robust will also make reusing your code for somewhat different tasks easier.

$.ajax({
/// [...]
    success:function(results){
/// [...]
        $(results).find("[nodeName=w:p]").each(function(){
            if($(this).find("[nodeName=w:pStyle]").attr('w:val') == 'ListParagraph'){
                var liValue = $(this).find("[nodeName=w:t]").text();
/// -^ What if the input has an empty value here? Skip?

                var hyper = $(this).find("[nodeName=w:hyperlink]").attr('r:id');
                var placeAtDepth = parseInt($(this).find("[nodeName=w:ilvl]").attr('w:val'), 10);
/// -^ parseInt can return a NaN, maybe you want to bail out in that case?
///    Should also handle some bogus results for .find.

                if(placeAtDepth > currentDepth){
                    $(".menuLvl"+ currentDepth).append('
');
                }

                currentDepth = placeAtDepth;

                //Determine if we have an hyperlink
                if(hyper != null){
                    var link = $(results).find('Relationship[Id='+hyper+']').attr('Target');
/// -^ This can result in an invalid link for broken input. But what if
       the input is malicious (JS hrefs)?

                    liValue = ''+ liValue +'';


Generate a find command with pruned directories based on a config file

You can use subcommands in a command:
echo "This $(date) is a date calculated in the echo command"

When you don't need additional control statements, you can use combined code like:
find /data/data/com.termux \
   $(awk '{printf("-path %s%s -prune -o ", "/data/data/com.termux/", $0)}' conf.file) \
   -print >> output

The awk command might be new for you, it is a replacement for your loop over the conf file. The same result can be found with sed:
sed 's#.*#/data/data/com.termux/& -prune -o #' conf.file

I think awk is the best here.


Accessing deep properties and methods of an object with using a path

If we're talking functional-programming, I'd use .forEach() instead of a for loop. It abstracts the iteration process.

if (!curProp[paths[i]]) return does not seem quite right to me, because it will work funny with falsy values. It's better to rely on object.hasOwnProperty(), or Object.keys() depending on the way you want it to work.

Example:

var obj = {};
obj["property1"] = 0;
obj["property2"] = "";

obj["property1"] ? obj["property1"] : "No property1 is available";
  // --> "No property1 is available", isn't right from the humans perspective noramally

obj["property2"] ? obj["property2"] : "No property2 is available";
  // --> "No property2 is available"

I think, it's always good to spell out the return value. In other words, return undefined is better than return in this function.

Slightly different variant:

function get(targetObject, targetPropertyPath) {
    const pathPartList = targetPropertyPath.split('.');
    let currentProperty = targetObject;

    pathPartList.forEach(pathPart => {
        if (!currentProperty.hasOwnProperty(pathPart)) return undefined;

        const property = currentProperty[pathPart];
        currentProperty = (typeof property !== 'function') ? property : property();
    });

    return currentProperty;
}


functional javascript - how could I generalize this code that correlates parallel async requests with their results?

Here's a sample in jsFiddle, with some values and functions mocked-up to use jsFiddle API.

Here's the actual code, with notes in the comments:

//personally, I like comma separated variables preferrably the
//"comma-before style". But it's personal preference.

//JS "hoists" up variable and function declarations higher in the scope.
//To avoid unexpected behaviour, and so that they are easier to find,
//we move them to the top of their scopes
var locale = 'en-US'
  , componentRoot = '/api/components'
  , components = ['facets', 'header', 'DocumentList']
  ;

function buildDocumentListPage(locale, componentCfgs) {}

//load our components
function asyncLoadComponents(componentRoot, components) {

      //our configuration collector
  var componentCfgs = {}

      //we create a promises array by mapping each value to a function
    , promises = _.map(components, function (component) {

        //we use the promise of a getJSON request (Assuming this is jQuery).
        //since you just concatenated the url values, we can just concatenate with +
        return util.getJSON(componentRoot+'/'+component).done(function (data) {

          //when getJSON resolves, we put the data in the collector
          componentCfgs[component] = data
        });
      });

  //as of jQuery 1.8, pipe is deprecated in favor of then. However, then
  //is designed to act like pipe, and instead of resolving with the value
  //we return the value instead
  return $.when.apply(null, promises).then(function () {
    return componentCfgs;
  })
}

//we model the function to return a promise that we'll listen to instead
//of having a $.when here. That way, we'll deal with less code and promises
asyncLoadComponents(componentRoot,components).done(function(componentCfgs) {

  //here, all configs have loaded and stored to componentCfgs
  buildDocumentListPage(locale, componentCfgs);
});

Packed code looks like this, tons shorter:

var locale = 'en-US',
  componentRoot = '/api/components',
  components = ['facets', 'header', 'DocumentList'];

function buildDocumentListPage(locale, componentCfgs) {}

function asyncLoadComponents(componentRoot, components) {
  var componentCfgs = {}, promises = _.map(components, function (component) {
      return util.getJSON(componentRoot + '/' + component).done(function (data) {
        componentCfgs[component] = data
      })
    });
  return $.when.apply(null, promises).then(function () {
    return componentCfgs
  })
}

asyncLoadComponents(componentRoot, components).done(function (componentCfgs) {
  buildDocumentListPage(locale, componentCfgs)
});


Thoughts.

Define a Line type and rename getLinePoints to mkLine. A list of points may represent anything but a Line [Points] implies the Points within the line. Where possible let the type system work for you. Of course you could get cute and have Line (m -> x -> b -> [Points]) or List Point Point.

You could define Eq and Ord instances for the Point and maybe Line types.

What if getSlope is passed a vertical line? Should it perhaps use Maybe?

I'd move the non-vertical line support into its own function. Perhaps add a horizontal line function as well.

Why use a list comprehension for the vertical one and map for the other type of line? It can all be done with a comprehension.


You can simplify it by replacing all those streams with a call to encrypter.TransformFinalBlock.
You don't have a MAC, so an attacker who can send a modifier message to the decrypter can probably exploit a padding oracle to decrypt the message
Why ask the caller for an IV? You could generate it internally. If you want to keep a deterministic implementation around, at least create an overload without IV.
Helper.ByteArrayToString and StringToByteArray should have a name that says which encoding (hex, Base64, etc.) they use. I'd use BytesToHexString and HexStringToBytes.


There is a good overview of string reversal algorithms in this answer. It should explain how special characters like é can be handled. I don't see what's your problem with "\n" and "\t". These are strings already.


Return combined DTO from async controller

Short answer would be yes. However you have a few other issues with the code shown.

There is no need for the Task.Run in the example TestMethod.

public async Task<CombinedDTO> TestMethod(SummonerDTO summonerData, MatchListDto matchData) {
    return await Task.Run(() => {
        return new CombinedDTO {
            summoner = summonerData,
            matches = matchData
        };
    });
}

For a simple object like your model there really is no need to throw that on to a new thread. The DTO can be constructed inline.

[HttpGet("[action]/{name}")]
public async Task<CombinedDTO> GetSummonerData(string name) {
    SummonerEndPoint endPoint = new SummonerEndPoint();
    SummonerDTO summonerData =  await endPoint.GetSummonerData(name);
    MatchesEndPoint endPoint2 = new MatchesEndPoint();
    MatchListDto matchesData =  await endPoint2.GetMatches(summonerData.accountId.ToString());
    return new CombinedDTO {
        summoner = summonerData,
        matches = matchData
    };
}

With that out of the way, this code is ripe for refactoring.

Starting from the bottom RiotApiRequestBase should not constantly create and dispose of HttpClient as this can have adverse effects (socket exhaustion).

public interface IRiotApiClient {
    Task<HttpResponseMessage> GetAsync(string url);
}

public class RiotApiClient : IRiotApiClient {
    static Lazy<HttpClient> client = new Lazy<HttpClient>(() => {
        //later this may be moved elsewhere
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("X-Riot-Token", "Token");
        return client;
    });

    protected Task<HttpResponseMessage> GetAsync(string url) {
        return client.Value.GetAsync(url);
    }
}

Keep an instance for the lifetime of the application. Alternatively, if you are using a more recent version of .net core consider using IHttpClientFactory.

Note the abstraction of the client, it will come into play later on.

The response in MakeAsyncRequest is already going to be disposed by its using. No need to wrap it again in GetResponseContentAsync. This also breaks Single Responsibility Principle as GetResponseContentAsync has no business disposing of the response.

Based on the abstraction of the client, that functionality can be refactored to extension methods.

public static class RiotApiClientExtensions {

    public static async Task<TResult> GetAsAsync<TResult>(this IRiotApiClient client, string url) {
        var data = await client.GetStringAsync(url);
        return JsonConvert.DeserializeObject<TResult>(data);
    }

    public static async Task<string> GetStringAsync(this IRiotApiClient client, string url) {
        using (var response = await client.GetAsync(url).ConfigureAwait(false)) {
            return await ReadContentAsStringAsync(response).ConfigureAwait(false);
        }
    }

    protected static async Task<string> ReadContentAsStringAsync(HttpResponseMessage response) {
        using (var content = response.Content) {
            return await content.ReadAsStringAsync().ConfigureAwait(false);
        }
    }
}

You appear to be following a format similar to CQRS (Command Query Responsibility Segregation), with your end points acting as queries.

I've used the following abstractions to help standardize queries.

using System.Threading.Tasks;

public interface IAsyncFunction<TResponse> {
    Task<TResponse> ExecuteAsync();
}

public interface IAsyncFunction<T, TResponse> {
    Task<TResponse> ExecuteAsync(T parameter);
}

public interface IAsyncFunction<T1, T2, TResponse> {
    Task<TResponse> ExecuteAsync(T1 parameter1, T2 parameter2);
}

public interface IAsyncFunction<T1, T2, T3, TResponse> {
    Task<TResponse> ExecuteAsync(T1 parameter1, T2 parameter2, T3 parameter3);
}

A similar format could be used for Actions/Commands

Using the above, look at the transformation of SummonerEndPoint and MatchesEndPoint

public interface ISummonerEndPoint : IAsyncFunction<string, SummonerDTO> { }

public class SummonerEndPoint : ISummonerEndPoint {
    private readonly string baseUrl;
    private readonly IRiotApiClient client;

    public SummonerEndPoint(IRiotApiClient client) {
        this.client = client;
        baseUrl = @"https://eun1.api.riotgames.com/lol/summoner/v3/summoners/by-name/";
    }

    public Task<SummonerDTO> ExecuteAsync(string summonerName) {
        return client.GetAsAsync<SummonerDTO>(baseUrl + summonerName);
    }
}

public interface IMatchesEndPoint : IAsyncFunction<string, MatchListDto> { }

public class MatchesEndPoint : IMatchesEndPoint {
    private readonly string baseUrl;
    private readonly IRiotApiClient client;

    public MatchesEndPoint(IRiotApiClient client) {
        this.client = client;
        baseUrl = @"https://eun1.api.riotgames.com/lol/match/v3/matchlists/by-account/";
    }
    public Task<MatchListDto> ExecuteAsync(string accountId) {
        return client.GetAsAsync<MatchListDto>(baseUrl + accountId + "?beginIndex=0&endIndex=10");
    }
}

Controller actions should be kept as lean as possible. It should really have only one purpose (SRP).

The initialization of the end points can now be inverted out of the controller and explicitly injected. This reduces the responsibilities of the controller and simplifies the action.

[Route("[controller]")]
public class MyController : Controller {
    private readonly IMatchesEndPoint getMatches;
    private readonly ISummonerEndPoint getSummonerData;

    public MyController(ISummonerEndPoint getSummonerData, IMatchesEndPoint getMatches) {
        this.getMatches = getMatches;
        this.getSummonerData = getSummonerData;
    }

    [HttpGet("[action]/{name}")]
    public async Task<IActionResult> GetSummonerData(string name) {
        SummonerDTO summonerData =  await getSummonerData.ExecuteAsync(name);
        MatchListDto matchesData =  await getMatches.ExecuteAsync(summonerData.accountId.ToString());
        var combinedDto = new {
            summoner = summonerData,
            matches = matchData
        };
        return Ok(combinedDto);
    }
}

Ideally the controller could have been simplified even more with a service that encapsulates the combining of the DTO for reuse but that is totally up to you.

With that all abstractions and their implementations should be registered at the composition root on startup


JavaScript jQuery plugin options. Defaults, User Options, and immutable settings pattern?

Not a lot ( of context ) to review;

this.options = $.extend(true, $.fn.myPlugin.Defaults, options); <- This will modify the defaults of the plugin, if you did not want that, then you should do

this.options = $.extend(true, {}, $.fn.myPlugin.Defaults, options);

You are talking about passing a third parameter for immutable settings/options/parameters, the 3rd parameter in your $.extend call will do no such thing, you will not even know which properties come from the 3 object.
myPlugin <- as plugin names go, not very original ;)
datatype is probably an unfortunate name, I would expect a function with that name to return a data type, also I would expect it to follow lowerCamelCase ( dataType )
It is risky to not check for jqGrid in self.options ? self.options.jqgrid : {},, I would have gone for (self.options && self.options.jqgrid) ? self.options.jqgrid : {},
Finally, I have to say that the last code block looks like a large amorphous blob, I would have much rather seen chained setters.

All in all, I am sure that you could have gotten more out of codereview if you had posted a bit more code.


Here is a lovely way to do it using only one nested for-loop:
for (int i = 0; i < 7; i++) {
    for (int numStars = 0; numStars < 4 - Math.abs(3 - i); numStars++) {
        System.out.print("*");
    }
    System.out.println();
}

This uses the Math.abs function to perform the calculation of how many stars to print.
If we take a look at a plot of the classic Math.abs we can see that it looks useful. We need to flip it upside-down though, this is done by taking 4 - abs(x) which would look like this. Finally, we need to switch it to the right a bit, so we modify the input to the function call and end up with this: 4 - abs(3 - x)
Images courtesy of wolframalpha.com
4-abs(x)

4-abs(3 - x)

Finally, here is a very flexible solution, which also works with even numbers:
int rows = 20;
double maximumValue = Math.ceil(rows / 2.0);
double shifted = maximumValue - 1;
for (int i = 0; i < rows; i++) {
    int count = (int) (maximumValue - Math.abs(shifted - i));
    if (i >= rows / 2 && rows % 2 == 0) // slight fix for even number of rows
        count++;

    for (int numStars = 0; numStars < count; numStars++) {
        System.out.print("*");
    }
    System.out.println();
}

This will output:
*
**
***
****
*****
******
*******
********
*********
**********
**********
*********
********
*******
******
*****
****
***
**
*


It is indeed better component design as @Tyriar mentioned, but it is also very common that the namespaces are being used among the projects. This is not always a wrong design.

Let assume that you are implementing plug-ins. And every plug in has own assembly (normally). There, namespaces can be shared.

PluginA.dll

Namespace CompanyName.SolutionName.ProjectName.PlugInNamespace
{
    Class PlugInA {}
}

PluginB.dll

Namespace CompanyName.SolutionName.ProjectName.PlugInNamespace
{
    Class PlugInB {}
}

Better practice for your case would be the sub-namespacing.

ClassLibrary1

Namespace Com.App.Test.FunctionalityGroupA
Public Class Class1

End Class
End Namespace

ClassLibrary2

Namespace Com.App.Test.FunctionalityGroupB
Public Class Class2

End Class
End Namespace

WindowsApplication1

Imports Com.App.Test.FunctionalityGroupA
Imports Com.App.Test.FunctionalityGroupB

Public Class Form1
    Dim c1 As Class1
    Dim c2 As Class2
End Class


Project Euler Q2 - Sum of even Fibonacci numbers

Daniel's solution to another question applies here equally.

On another question, I showed that the sum is equal to

$$
\frac{F_{3n+2} - 1}{2}
$$

where \$3n\$ is the largest multiple of \$3\$ not to exceed the maximum.

If you wish to use this for asymptotic improvements, note that since the Fibonacci sequence has a closed-form solution, you can use it to find an approximate bound for \$3n\$, and then use fast exact mechanisms to find the exact value of \$F_{3n+2}\$.

$$
F_{3n} \approx \phi^{3n}/\sqrt 5 \\
3n \approx \log_\phi \left(F_{3n} \sqrt 5 \right)
$$

Finding a lower bound for \$n\$ thus takes very little time.

Personally I'd stick with the simple, slower solution, but it's interesting to note how far you can get with a bit of mathematical analysis.


Clearing duplicates from an Excel 2007 sheet

If you are trying to get zero-length strings left after reverting formulas (that may have resulted in "" ) to their values, the quickest way is to spin through the columns and apply a quick Text-to-Columns, Fixed Width, Finish to each.

Dim c As Long
With worksheets("Sheet1")
    With .Range("A1").CurrentRegion  `<~~ set to the desired range of one or more columns
        For c = 1 To .Columns.Count
            .Columns(c).TextToColumns Destination:=.Columns(c), _
                DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
        Next c
    End With
End With

This process will take zero-length strings and make then truly blank cells. This is an important step in preppinga worksheet for direct non-CSV import to MS-SQL.


You can use a temporary array, see for example here or here.

As this would change quite a lot, I'm not going to rewrite your code to match those examples.

But I do have some additional comments which might improve the readability and ease of use of your code:

Constructor

A constructor should only construct an object. Your constructor also gathers user input. This makes it extremely hard to test your class.

Just let MergeSort accept an array, which you created in a ConsoleInput class (or main).

Or pass the array directly to the sort method and just use an empty constructor.

Merging

Your merging code is a bit confusing, because you are using for loops when while would be a better fit:

    int l = 0;
    int r = 0;
    int arrayPosition = 0;
    while (l < left.length && r < right.length) {
        if (left[l] >= right[r]) {
            result[arrayPosition] = right[r];
            r++;
        } else {
            result[arrayPosition] = left[l];
            l++;
        }
        arrayPosition++;
    }

    // copy rest
    while (l < left.length) {
        result[arrayPosition] = left[l];
        l++;
        arrayPosition++;
    }
    while (r < right.length) {
        result[arrayPosition] = right[r];
        r++;
        arrayPosition++;
    }

With this code, you can probably also better see the similarities to the code that uses a temporary array.

And to copy the rest, you could also use arraycopy, which is probably faster:

    if (l == left.length) {
        System.arraycopy(right, r, result, arrayPosition, right.length - r);
    } else if (r == right.length) {
        System.arraycopy(left, l, result, arrayPosition, left.length - l);
    }

Other

naming: mergeSort2 why 2? And just write beginning instead of beg, it's not that long.
private: fields should be private (unless there is a good reason to make them public), same with methods.
create a merge method, it makes your code easier to read.
the caller shouldn't need to know with what parameters to call mergeSort2. I would create a public method without arguments (or which accepts the array) which then calls mergeSort2 with the correct parameters.


After some research, I ended to a better and faster solution. Here is the code:

# import packages
import numpy
import mahotas.polygon
import shapely.geometry as shageo
import cv2
import numpy as np

def get_mask(dims, pts):
    # create a numpy array of zeros with the same dimensions of the image
    canvas = numpy.zeros((dims[0], dims[1]), dtype=int)
    # the points coords in the form of pt(y, x)

    # fill the polygon with ones.
    mahotas.polygon.fill_polygon(pts, canvas)
    return canvas

def find_polygon(img):
    # get the gray image and do binaryzation
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    gray[gray < 20] = 0
    gray[gray > 0] = 255

    # get the largest boundry of the binary image to locate the target
    contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    rect = cv2.minAreaRect(contours[0])
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    poly = shageo.Polygon(box)
    # return the polygone coords in a list
    return list(poly.exterior.coords)

def main():
    img = cv2.imread('filename.jpg')
    # get the coords of the polygon containing (around) the image.
    coords = find_polygon(img)
    poly_coords = []
    # the coords are floats and sometimes are negaive (-1), so transform them into positive ints.
    for element in coords:
        poly_coords.append(tuple(map(int, map(abs, reversed(element)))))

    mask = get_mask(img.shape, poly_coords)
    # convert the mask into array of 0 and 1.
    binary_mask = np.logical_not(mask).astype(int)
    # reshape the array to be similar to the image dimenstions
    binary_mask = binary_mask.reshape(img.shape[0], img.shape[1], -1)
    # sum the binary mask with the image
    cv2.imwrite('res.jpg', img + binary_mask * 255)

main()

I am sure this code can be optimized more, any suggestions are welcome.

Credits:
1- Drawing polygons in numpy arrays
2- Whiten black contours around a skewed image opencv

Here is the result:


what is Null Test in java? and how to rewrite the code to do the same by avoiding null test

The null test is the input != null condition here.

In your code if the constructor of the stream throws an exception the reference remains null so there is no way to call close on it, therefore the constructor call could be before the try-catch block. The generic pattern is the following:

    final InputStream input = new FileInputStream(new File("foo.txt"));
    try {
        // do something with the stream
    } finally {
        input.close();
    }

Please note that I've changed new InputStream(...) to new FileInputStream(...). InputStream an interface, you cannot instantiate it.

In Java 7 it's a little bit simpler:

try (final InputStream input = new FileInputStream(new File("foo.txt"))) {
    // do something with the stream
}

References: Guideline 1-2: Release resources in all cases in the Secure Coding Guidelines for the Java Programming Language, Version 4.0 documentation.


Is this a good example of the strategy pattern?

It seems like a you should implement Chain of responsibility as you are passing the same string to different kind of processor with a particular sequence

http://www.dofactory.com/Patterns/PatternChain.aspx#_self1

This is a gud pattern in your scenario.

One more thing your StringProcessorChain might not be needed in this case....

Let me know if you need a more highlight on same


Computing average without overflows and with half-decent precision

First, having a forward-iterator is good enough, don't ask for more. Yes, it might mean you have to go over the range twice (once to measure its size), but that's a minor irritant.
Just please, verify it is a forward-iterator like this:

std::forward_iterator_tag = std::iterator_traits<ForwardIt>::iterator_category{};

Use the right loop for the job. It's more readable, and more concise.
Mark any variable you can const to help comprehension and error-checking.
Next, you really have to improve your overflow-handling, as res += static_cast<long double>(accumulator) / static_cast<long double>(size); might loose a small amount of precision.
Stay in the integer-realm by adding / subtracting enough multiples of size to change the sign of accumulator.
Don't cast to long double unless you can guarantee perfect accuracy.
You can easily supplant the builtin with a bit of logic:
Test the sign of accumulate and depending on the result check whether MAXVALUE - accumulate > *first or MINVALUE - accumulate < *first.
Not sure whether the compiler can optimize that as well as the builtin though...
Consider whether making it SFINAE-friendly by avoiding hard errors might be worth the more verbose error-messages.

Modified code:

#include <cstdint>
#include <iterator>
#include <type_traits>
#include <limits>

template<typename ForwardIt>
long double average(ForwardIt first, ForwardIt last)
{
    static_assert(std::is_integral<typename std::iterator_traits<ForwardIt>::value_type>(),
        "average only available for built-in integer types");
    std::forward_iterator_tag = std::iterator_traits<ForwardIt>::iterator_category();

    const auto size = std::distance(first, last);
    if (!size) return 0;

    std::intmax_t accumulator = 0;
    long double res = 0;
    do {
        using snl = std::numeric_limits<decltype(accumulator)>;
        if (accumulator < 0 && snl::min() - accumulator > *first) {
            res += accumulator / size - 1;
            accumulator = accumulator % size + size;
        } else if (accumulator > 0 && snl::max() - accumulator < *first) {
            res += accumulator / size + 1;
            accumulator = accumulator % size - size;
        }
        accumulator += *first;
    } while (++first != last);
    res += accumulator / size;
    res += static_cast<decltype(res)>(accumulator % size) / size;
    return res;
}


Input memory buffer exceeding situation handling

I'm not familiar with the "ucuc format", or what such an output format could be useful for.  A Google search for md5 ucuc format shows this question itself as the only relevant hit.

What are the expected inputs?  A 32-character string of hexadecimal digits?  If so, the longest possible output should be 32 repetitions of uc102, corresponding to an input of ffffffffffffffff.  (If the input can contain arbitrary characters, then allow for 6 bytes of output per byte of input, since there might be a negative sign.)  Why not just document the requirement for the caller to pass you an output buffer capable of storing 161 bytes?  Then do away with the size parameter.  You could return the number of bytes of output (excluding the \0 terminator).

Printing the error messages is not advised; it contaminates the output, and side effects limit the ability to reuse your code.  If you must print diagnostics, print to stderr instead.  You can use the __FILE__ and __FUNCTION__ macros for the error message.

A more common way to handle null inputs is to either let it crash, or use assertions.  An assertion failure message typically already includes the line number.  If you use assertions, use three separate assertions, not a combined one.  Calling exit() is unusual; calling exit(0) to exit successfully is even weirder.

Checking for possible buffer overflow at the end of the function is useless.  The damage would already be done, and your program could very well have crashed before reaching the check.

Your use of strlen() and strcat() is inefficient, especially when done in a loop.  Each of those calls is an O(n) operation, as it scans the buffer for the \0 terminator.  You already know exactly where those terminators are, since you composed the output string yourself.

/**
 * Encodes the input_md5 in ucuc format, whatever that means.
 * The caller must provide an output capable of holding 5 bytes
 * per byte of input, plus 1 byte for a null terminator.
 *
 * Returns the length of the output in bytes, excluding the null
 * terminator.
 */
static int md5_encode(const char *input_md5, char *output)
{
    // Check preconditions
    assert(input_md5);
    assert(output);

    int out_offset = 0;
    for (const char *in = input_md5; *in; in++)
    {
        // Encode it. sprintf() already adds a \0 terminator.
        out_offset += sprintf(output + out_offset, "uc%d", *in);
    }

    return out_offset;
}

In my opinion, two spaces of indentation per level is too stingy for readability, and also encourages inappropriately deep nesting.


Moving files to an output directory, with instructions on missing files

You are right in that most of your code is very similar, except for the file that you are checking. Since only a small part of the code changes, and the same actions are made at every step, this asks for a loop that iterates over the different files that you want to check:

paths_to_check = [".\image_1_01.bmp", ".\image_1_01.raw", ".\image_1_01_hist.csv", ".\image_1_02.bmp", ".\image_1_02.raw", ".\image_1_02_hist.csv", ".\scan_stats.csv"]

for p in paths_to_check:
    if not os.path.exists(p):
        print(p + 'not generated\n' 'for mor info check the log file' )
        return 1
    else:
        shutil.move(p, output_directory)


Javascript inheritance: is my solution correct?

It's generally a bad idea to try writing code in one language as if it were a different language.

Don't fight your tool; use it as it was designed. JavaScript has prototype-based OO rather than class-based OO, so use it like that.

Read "Javascript - the Good Parts" and learn to write actually good JavaScript rather than "Java in JavaScript" (for which other developers working with your code will hate and/or mock you).


Print the length of words as input as a histogram with horizontal bars

Looks good. There's really not a lot to review. About the only thing I can think of is that I'd like a little breathing space in the block, i.e.

{ |word| "*" * word.length }

But that's about it :)

Of course, there are also other ways to go about this, for instance:

puts gets.chomp.gsub(/\S/, "*").gsub(/\s+/, "\n")

Not that that's necessarily any better.


You have a couple of PEP8 style problems:

Functions should have an empty line above and below them.
Function calls should have their bracket immediately after the name. So fn( not fn (.
Assignment operators should have a space either side of them.
Try to keep code less than 80 characters long.

You also have a couple of naming problems:

compar should be compare or comparer, since compar is not a word. If you wanted to shorten it comp would be the best shortened version, but is worse than both the written out versions.
Lists and arrays don't have IDs, they have indexes. And so element_id is confusing. At first I used item_index or element_index, but decided to instead use parent and child to better describe the parent child relationship.
In heapify I'd change el_id to child and element_id to parent. (And you should use child rather than parent * 2)
For better readability, and for a minor performance boost, I used heap = self.heap.

Other things I'd change:

Your constructor shouldn't need to be passed compare, and so it could default to operator.lt. You may also want to take a heap as input, but you may need to add more code so it works correctly.
Add a __repr__, so that you can more easily tell what the object is.
In del_min when you add the two lists, it runs in \$O(n)\$ time. Where you can do the same with heap.pop(), which runs in \$O(1)\$ time.
You may want to look at heapq's source code to find other things you can do. It for example uses; _siftup, and _siftdown, and; _siftup_max, and _siftdown_max. Where you only write two of these.

Combining the above together gets you:

import operator

class Heap(object):
    """"
    Attributes:
        heap: List representation of the heap
        compare(p, c): comparator function, returns true if the relation between p and c is parent-chield
    """
    def __init__(self, heap=None, compare=operator.lt):
        self.heap = [] if heap is None else heap
        self.compare = compare

    def __repr__(self):
        return 'Heap({!r}, {!r})'.format(self.heap, self.compare)

    def _inv_heapify(self, child_index):
        """
        Do heapifying starting from bottom till it reaches the root.
        """
        heap, compare = self.heap, self.compare
        child = child_index
        while child > 0:
            parent = child // 2
            if compare(heap[parent], heap[child]):
                return
            heap[parent], heap[child] = heap[child], heap[parent]
            child = parent

    def _heapify(self, parent_index):
        """
        Do heepifying starting from the root.
        """
        heap, compare = self.heap, self.compare
        length = len(heap)
        if length == 1:
            return
        parent = parent_index
        while 2 * parent < length:
            child = 2 * parent
            if child + 1 < length and compare(heap[child + 1], heap[child]):
                child += 1
            if compare(heap[parent], heap[child]):
                return
            heap[parent], heap[child] = heap[child], heap[parent]
            parent = child

    def del_min(self):
        heap = self.heap
        last_element = heap.pop()
        if not heap:
            return last_element
        item = heap[0]
        heap[0] = last_element
        self._heapify(0)
        return item

    def min(self):
        if not self.heap:
            return None
        return self.heap[0]

    def add(self, element):
        self.heap.append(element)
        self._inv_heapify(len(self.heap) - 1)

Rather than implementing this yourself, you can use Pythons heapq, which may be written in C.
Since it's not a class you can easily make it one by wrapping it in one. But it doesn't have your custom comparisons, it is instead always a min heap.
If you need the custom comparisons, you could instead look into writing your own comparison object that does what you want, and use the heap class.

class Heap(list):
    def __init__(self, heap=None):
        if heap is None:
            heap = []
        heapq.heapify(heap)
        super(Heap, self).__init__(heap)

    def __repr__(self):
        return 'Heap({})'.format(super(Heap, self).__repr__())

    def push(self, item):
        return heapq.heappush(self, item)

    def heappop(self):
        return heapq.heappop(self)

    def pushpop(self, item):
        return heapq.heappushpop(self, item)

    def replace(self, item):
        return heapq.heapreplace(self, item)

    def nlargest(self, n, *args, **kwargs):
        return heapq.nlargest(n, self, *args, **kwargs)

    def nsmallest(self, n, *args, **kwargs):
        return heapq.nsmallest(n, self, *args, **kwargs)


Variable creation and returning Boolean values

The code is sufficiently trivial that it's hard to see where improvements could be made. The only element that isn't already compatible with Python 3 is println (print is a function in 3.x), which seems useless anyway - why would you do:

pcl.println(pcl.var)

rather than

print pcl.var

If you're determined to keep it,

def println(stringint):
    print(stringint)

will work in 2.x and 3.x.

One step up would be to go for a class:

from operator import ne, ... # avoid 'from xyz import *'

class PCL(object):

    OPERATORS = {"!=": ne, ...}

    def __init__(self, vars=None): # provide initial variables (defaults to empty list)
        if vars is None:
            vars = []
        self.vars = vars

    def clear_vars(self): # create new list rather than deleting old one
        self.vars = []

    def create_var(self, value):
        self.vars.append(value)

    def return_bool(self, var1_index, op, var2_index):
        return self.OPERATORS[op](self.vars[var1_index],
                                  self.vars[var2_index])

This allows you to have multiple "sessions" alongside each other, with separate variable lists. It also removes the reliance on scoping for variable access, which will make testing easier as this grows in complexity.

I have also altered return_bool to take the indices and operator as arguments directly, simplifying the syntax:

>>> from pcl import PCL
>>> pcl1 = PCL()
>>> pcl1.create_var(1)
>>> pcl1.create_var(3)
>>> pcl1.return_bool(0, "!=", 1)
True

This may or may not be desirable.


Multiple longest common subsequence (another algorithm)

1. Analysis

This is a greedy algorithm: at each step it prefixes one letter to the result, choosing the letter than minimizes the change in the indexes into the strings.

The main loop of the algorithm adds one letter to the result, so can execute at most \$ N \$ times. Each iteration of the loop considers each letter in the alphabet \$ Σ \$, and each of the \$ M \$ strings, and searches (by bisection) the list of occurrences of that letter in that string, taking \$ O(\log N) \$. Thus the overall runtime is \$ O(\left|Σ\right|NM\log N) \$. (You missed a factor of \$ N \$.)

This is polynomial time, but the longest common subsequence problem is NP-hard, so the algorithm does not solve the problem in the general case.

Here's a simple case where mlcs returns the wrong result:

>>> mlcs(('ab', 'aba'))
'a'

2. Review

There's no docstring for mlcs. What does this function do? How do I call it? What does it return?
The case of no strings is not handled:

>>> mlcs(())
Traceback (most recent call last):
    ...
IndexError: list index out of range

This should probably be a ValueError, like max(()).
The case where all strings are empty is not handled:

>>> mlcs(('', ''))
Traceback (most recent call last):
    ....
AttributeError: 'NoneType' object has no attribute 'values'

This should return the empty string.
The code takes the union of the letters in the strings. But the only letters that can appear in the longest common subsequence are those letters that appear in all the strings, so the intersection is needed here here, not the union.
The code accumulates a list by repeated addition:

for i in range(len(x)):
    tx[x[i]] += [i]

This wastes space because Python might have to allocate a new list each time and copy the old list across. It's more efficient to accumulate a list using the append method.
Iteration over the indexes of a sequence can often be simplified using enumerate, for example the loop above can be written:

for i, letter in enumerate(x):
    tx[letter].append(i)

pos is a dictionary mapping input string to the current position in that string in the search. Since strings is a list of strings, it would make more sense for pos to be a list of positions, so that pos[i] was the current position in strings[i]. Then match simplifies to:

def match(pos):
    c = strings[0][pos[0]]
    return all(c == s[p] for s, p in zip(strings, pos))

The function match is not called, so could be omitted.
The initialization of pos:

pos = {}
for x in strings:
    pos[x] = len(x)

Could be written as a dictionary comprehension:

pos = {s: len(s) for s in strings}

or, if you follow my advice above about making pos into a list, a list comprehension:

pos = [len(s) for s in strings]

This loop:

for x in strings:
    if pos[x] < 0:
        loop = False
if not loop:
    break

always tests all elements of pos, so that even if the first one is negative, it will go on and uselessly test all the others. It would be better to fail as soon as possible:

if any(pos[s] < 0 for s in strings):
    break

or, if you follow my advice above about making pos into a list:

if any(p < 0 for p in pos):
    break

Note that the change discussed above gets rid of the only assignment to loop, so that we have:

loop = True
while loop:
    if any(p < 0 for p in pos):
        break

which simplifies to:

while all(p >= 0 for p in pos):

Instead of setting ind[x] and then setting it back to the default value based on a condition:

ind = defaultdict(int)
for x in strings:
    indxc = indexes[x][c]
    if indxc:
        i = find(indxc, pos[x] - 1)
        ind[x] = indxc[i]
        if ind[x] > pos[x] - 1:
            ind[x] = -128
    else:
        ind[x] = -128

initialize it to the default value and set it only if the condition does not apply:

ind = defaultdict(lambda:-128)
for x in strings:
    indxc = indexes[x][c]
    if indxc:
        i = find(indxc, pos[x] - 1)
        if indxc[i] <= pos[x] - 1:
            ind[x] = indxc[i]

Just as I recommended making pos into a list, I also recommend making ind into a list. If you did, then distance would become:

def distance(v, w):
    return sum((i - j)**2 for i, j in zip(v, w)):

and since this is only called from one place, you could easily inline it.
Similarly, indexes would be more conveniently organized so that indexes[letter][i] is a list of the indexes of the occurrences of letter in strings[i].
A magic number like this:

dr = 12777216

needs to be explained. It looks to me as though this needs to be some number larger than the biggest possible distance between pos and ind. But for very long strings (tens of thousands of letters), this won't be the case. It would be more reliable to start at infinity:

min_distance = float('inf')

But it would be better to reorganize the code to call the built-in min function, and catch the ValueError that is raised when there are no elements. See the revised code in §3 below for how this is done.
Similarly, the magic number -128 needs explanation. The idea seems to be that this is so far away from the index of any character in the string that the distance will be large and the candidate will be rejected. But is this really true? If the strings are longer than 128 characters then a candidate might be included erroneously. It would be better to reject candidates where bisect_right returns 0.
The handling of the case where bisect_right returns 0 seems incorrect to me. In this case find returns -1, and then this leads to the assignment ind[x] = indxc[-1] which succeeds (getting the last element in indxc) but this is wrong.

3. Revised code

from bisect import bisect

def mlcs(strings):
    """Return a long common subsequence of the strings.
    Uses a greedy algorithm, so the result is not necessarily the
    longest common subsequence.

    """
    if not strings:
        raise ValueError("mlcs() argument is an empty sequence")
    strings = list(set(strings)) # deduplicate
    alphabet = set.intersection(*(set(s) for s in strings))

    # indexes[letter][i] is list of indexes of letter in strings[i].
    indexes = {letter:[[] for _ in strings] for letter in alphabet}
    for i, s in enumerate(strings):
        for j, letter in enumerate(s):
            if letter in alphabet:
                indexes[letter][i].append(j)

    # pos[i] is current position of search in strings[i].
    pos = [len(s) for s in strings]

    # Generate candidate positions for next step in search.
    def candidates():
        for letter, letter_indexes in indexes.items():
            distance, candidate = 0, []
            for ind, p in zip(letter_indexes, pos):
                i = bisect.bisect_right(ind, p - 1) - 1
                q = ind[i]
                if i < 0 or q > p - 1:
                    break
                candidate.append(q)
                distance += (p - q)**2
            else:
                yield distance, letter, candidate

    result = []
    while True:
        try:
            # Choose the closest candidate position, if any.
            _, letter, pos = min(candidates())
        except ValueError:
            return ''.join(reversed(result))
        result.append(letter)


As noted in the comments:

I would make the factory retain ownership:

class LoggerFactory {

typedef std::map<std::string, std::unique_ptr<Logger>>  Container;
typedef Container::iterator                             iterator;
typedef Container::const_iterator                       const_iterator;
typedef Container::value_type                           value_type;

typedef std::list<std::reference_wrapper<LoggingSink>>  SinkHolder;

public:
    Logger& get(std::string const& loggerName = "default")
    {
        iterator find = cont.find(loggerName);
        if (find == cont.end())
        {

            std::unique_ptr<Logger> result = std::make_unique<Logger>();

            // Personally I would not do this.
            // I would pass the iterators to the constructor
            // of the Logger object.
            result->Sinks.assign(std::begin(standardAssignedSinks),
                                 std::end(standardAssignedSinks));

            auto insertR = cont.insert(value_type(loggerName, result));
            if (!insertR.second)
            {    throw std::runtime_error("Insertion Failed");
            }
            find = insertR.first;
        }
        return *(find->second);
    }

    void addStandardSink(LoggingSink& ls) {
        standardAssignedSinks.empace_back(ls);
    }

private:
    SinkHolder standardAssignedSinks;
    Container  cont;
};

Now you can have multiple loggers. But you can re-use loggers (as each logger has its own name. Most of the time people should be using the default logger.

Building a streamming logger is not that difficult it just requires an intermediate buffer object to accumulate the message. When it is destroyed it sends the message to the logger.

class Logger {
    public:
        template<typename T>
        LogStreamBuffer  operator<<(T const& data) // Member so left hand side  implied as Logger
        {
            // This is not perfect
            // This may cause a copy (and thus a destruction)
            // If there is a copy/destruction cycle an extra message will be
            // sent. You can code around this problem.
            // This is just to get you started.

            return LogStreamBuffer(*this) << data;
        }
    // OTHER STUFF
};
class LogStreamBuffer
{
    Logger&            parent;
    std::stringstream  buffer;

    public:
        LogStreamBuffer(Logger& parent)
           : parent()
        {}
        ~LogStreamBuffer()
        {
            // When the object is destroyed.
            // Log the accumulated message with the parent.
            parent.log(buffer.str());
        }
        template<typename T>
        LogStreamBuffer&  operator<<(T const& data)
        {
            // Anything you log is just appended to the message.
            buffer << data;
            return *this;   // return a reference to yourself.
                            // So you can chain messages.
        }
};

// Usage:
int main()
{
     LoggerFactory   factory;
     Logger          logger = factory.get("MyLogger");

     logger << "This is a test: " << 1 << " Got it";
       //   ^^^
       //   Creates a LogStreamBuffer
       //   As an invisable temporary object.
       //   The subsequent `operator<<` will accumulate
       //   data in the buffer. When the statement is
       //   finished (at the ;) all temporaies will be
       //   destroyed. This calls the LogStreamBuffer
       //   destructor and logs your data to the Logger
       //   object.

}


Sufficient implementation of subset sum for 45 min interview

Bug
I ran your program, replacing 100 with 6.  This should have found the subset {2,4} as a solution but it didn't.
Your program searches for contiguous subsets which sum to the given value.  I don't think that contiguousnous was specified by the problem in the link you provided.


I think I understand the problem, which if I am not mistaken means we want to pick a set of nodes from the tree such that no two taken nodes are connected in the tree. If you just think about it in a recursive manner, you either take a node and neither of its children, recursively trying to solve the same problem with the grandchildren. Or you do not take the node, and take the sum of the same problem solved for both children. An implementation could look like this (I left out underscore, using the index to check for the end of the tree):

static int max(final String tree) {
    return max(0, stream(tree.split(" ")).mapToInt(Integer::parseInt).toArray());
}

static int max(final int root, final int... nodes) {
    if (root >= nodes.length) {
        return 0;
    }

    final int maxWithRoot =
            nodes[root]
            + max(getLeftChildIndex (getLeftChildIndex(root)),  nodes)
            + max(getRightChildIndex(getLeftChildIndex(root)),  nodes)
            + max(getLeftChildIndex (getRightChildIndex(root)), nodes)
            + max(getRightChildIndex(getRightChildIndex(root)), nodes);

    final int maxWithoutRoot = max(getLeftChildIndex(root),  nodes) +
                               max(getRightChildIndex(root), nodes);

    return Integer.max(maxWithoutRoot, maxWithRoot);
}

You can now also see that the same calculation will be executed multiple times for the same node. But because the result of the max function only depends on the root index, you can cache the calculations, meaning you calculate the result for each node only once.

In this case, you could simply create an integer array as a cache, using the node index as the cache index.