Turning a comment into a review (I provide an alternative implementation, but the basic ideas can be applied to the OP implementation).
First, some general thoughts.
As I mention in the comments regarding the parseInt function, a linter can help spot any problems. A popular one is ESLint. But perhaps more to the point, the data seems to already be a number, so there shouldn't be any need to parse it.
It can help to clean up the code quite a bit by extracting the filters, reducers, mappers, sorters, etc. outside as a variable and give them a descriptive name, for example:
// filter
const arrivedOrRescued = ({rescueStatus}) => rescueStatus >= 3

// sorter
const byArrivalOrRescueTime = (a, b) =>
  Date.parse(a.ambulanceArrivalTime || a.rescueTime)
    - Date.parse(b.ambulanceArrivalTime || b.rescueTime)

// reducer
const byRescuers = (acc, {rescuerGroups}) => {
  rescuerGroups.forEach(({
    rescues
    , rescuer1Abbreviation: r1
    , rescuer2Abbreviation: r2
  }) => {
    let group = `${r1}-${r2}`
    acc.has(group) ? acc.get(group).push(...rescues) : acc.set(group, rescues)
  })

  return acc
}

so getting a Map (just an example) by rescuers out of the swimlanes could then become
let rescuers = cases.filter(arrivedOrRescued).reduce(byRescuer, new Map())

and sorting their rescues could become
rescuers.forEach((rescues, abbrevs) => rescues.sort(byArrivalOrRescueTime))

after which the latest rescue is the last element of the array now that they have all been collected into a single array and sorted.
One thing I would like to promote here when there can be somewhat complex nested objects in the data, is to use JSDoc comments to document the data shape.
For example:
/*
 * @typedef {Object} Swimlane
 * @property {Array.<RescuerGroup>} rescuerGroups
 * @property {Number} rescueStatus
 * @property {String} rescueStatusName
 *
 * @typedef {Object} RescuerGroup
 * @property {Array.<Rescue>} rescues
 * @property {?Number} rescuer1
 * @property {?Number} rescuer2
 * @property {?String} rescuer1Abbreviation
 * @property {?String} rescuer2Abbreviation
 *
 * @typedef {Object} Rescue
 * @property {?String} ambulanceArrivalTime
 * @property {?String} callDateTime
 * @property {?String} callerName
 * @property {String} callerNumber
 * @property {?Number} callOutcomeId
 * @property {Number} emergencyCaseId
 * @property {Number} emergencyCodeId
 * @property {Number} emergencyNumber
 * @property {Number} isLargeAnimal
 * @property {Number} latitude
 * @property {Number} longitude
 * @property {{lat: Number, lng: Number}} latLngLiteral
 * @property {String} location
 * @property {Array.<String>} patients
 * @property {Number} rescuer1
 * @property {Number} rescuer2
 * @property {?String} rescueTime
 * @property {Number} RescueStatus
 */

This makes it easier for others especially in data transformations.
Just a note that I haven't tested any of this, so take the above code with a grain of salt. Also, many will probably tell me to use more braces and semicolons.


Good job using const for values, as well as let for re-assignable values like counter and rejected.

Did you test this code? My presumption is that it didn't happen, because when I tried running it, I see the following error:

  error promise.then is not a function

This is because the promises are spread out:

function all (...promises) {

Without the spread operator it appears to run as I would expect, as long as each entry in promises is a promise.

I must admit I compared with another implementation of Promise.all(). In comparison with that function, yours tracks rejected, whereas the other one simply calls reject whenever a promise is rejected.

Another thing I noticed is that the variable name promise is reused - both for the outer promise to be returned by all() as well as the callback to promises.forEach(). It would be wise to use different names to improve readability. In fact there is little need to assign the outer promise - it can simply be returned without being assigned to a variable since it isn't modified after being instantiated.

Another aspect to consider is that Promise.all() can accept promises or non-promises - e.g. the MDN documentation gives an example like this:

const promise1 = Promise.resolve(3);
const promise2 = 42; // <- not really a promise
const promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
}).catch(error => {
   console.log('error: ', error.message);
});
// expected output: Array [3, 42, "foo"]

With your code, it throws the error promise.then is not a function so it might be wise to check if each item is a promise before calling .then() on it.


Based on functions like getId and toJSON, it seems like you would naturally want to have a base class for your models. As such, it would make sense to write your functions in a way that support prototypical inheritance e.g.

Base Model

function Entity(id) {
  this._id = id;
}

Entity.prototype = {
  function getId() {
    return this._id;
  }
  ...
}

module.exports = Entity;

Derived Model

var Entity = require('./entity');
var util = require('util');

function Purchase(customer, orders, ...) {
  Entity.call(this, PurchaseId.purchaseId());
  this._customer = customer;
  this._orders = orders;
  ...
}

util.inherits(Purchase, Entity);

Purchase.prototype.getCustomer = function() {
  return this._customer;
}
Purchase.prototype.getOrders = function() {
  return this._orders;
}
...
module.exports = Purchase;

Usage

var purchase = new Purchase(...);
console.log(purchase.getId()); // Purchase will inherit everything from Entity
console.log(purchase.getCustomer()); // and have it's own functions too

Note - notice in base we set the prototype directly but in the derived we modify it? This is deliberate because in the base class the prototype is currently empty so it's fine to completely overwrite. If we did the same thing on the derived class then we'd lose the base prototype therefore we simply append to the existing prototype.


Initializing values of a singly linked list with a constructor

Don't do this:
using namespace std;

Bringing everything from std into the global namespace causes more issues than it is worth. I know every book on the subject does it. But they do it because of size limitations in their medium. You should never do this in real code.
See: Why is “using namespace std” considered bad practice?
This should not be a public class:
template <typename E>
class SNode {
private:
    E elem;
    SNode<E> *next;
    friend class SLinkedList<E>;
};

Make it a private member class of SLinkedList. Then it gets smaller. You can make it struct, and you won't need the friend declaration or the <E> sprinkled everywhere.
That does not look correct:
SLinkedList(SNode<E>* v);   //What I need help with

Why would somebody want to create a linked list with a node? Why are you passing a pointer to the node? What is the ownership semantics of the pointer? So many unanswerable questions. Just get rid of this constructor.
I don't see any of the normal constructors I would expect for a container that is doing memory management (and you are doing memory management). Please look up the rule of three.
// I would expect to see
SLinkedList(SNode<E> const& copy);
SLinkedList& operator=(SLinkedList const& copy);

For bonus points add move semantics:
SLinkedList(SLinkedList&& move) noexcept;
SLinkedList& operator(SLinkedList&& move) noexcept;
void swap(SLinkedList& other) noexcept;

Yeahh. Stop using NULL; that's an old hangover for C (we don't like C here). C++ has a better identifier. Use nullptr; it has better type information associated with it (so it will not be converted to a integer type accidentally).
Sure you can throw.
template <typename E>
E& SLinkedList<E>::front()
{
    if (empty()) throw length_error("empty list");
    return head->elem;
}

But do you really want to?
I am an expert user and will always check that list is not empty before calling front(). But you are making me pay a penalty (the extra check (I just checked)) because there are idiots out there that don't check. Why are you penalizing me (the good guy) when the bad guys are the ones you should be penalizing?
Sure have a checking version. But the standard version should not check.
OK. This is obviously not working:
template<typename E>
void SLinkedList<E>::printList(SLinkedList<E> &list) //What I need help with
{
    for (int i = 0; i < list.size(); i++)
    {
        cout << list << " ";
    }
    cout << endl;
}

You want:
template<typename E>
void SLinkedList<E>::printList(SLinkedList<E> &list) //What I need help with
{
    for (auto item = head; item != nullptr; item = item->next)
    {
        cout << item->elem << " ";
    }
    cout << "\n";
}

Prefer '\n' to std::endl.
The only difference between the two is that std::endl forces a stream to flush. This is never the correct thing to do (unless you are an expert and understand stream flushing to byte level (or you are debugging - in which case you should be using an unbuffered stream like std::cerr)).
Incorrectly flushing the buffer is the MAIN cause of inefficiency in C++ I/O application. The standard streams are quite good at correctly flushing for efficiency; use the code somebody else has spent hours perfecting for your system.
This all looks fine:
SNode<E>* v = new SNode<E>;     // create new node
v->elem = e;                // store data
v->next = head;             // head now follows v
head = v;               // v is now the head
n++;

But would it not look a lot nicer if it was:
head = new SNode(e, head);
++n;

Also prefer to use prefix increment over postfix. The majority of the time it will make no difference. But with iterators (it can have a tiny impact). Since iterators are prevalent all over C++ code this could make a difference. There is no cost to prefix operations.
See: How to overload the operator++ in two different ways for postfix a++ and prefix ++a?
Additions

I have to create a constructor that allows a new linked list to be populated with ten consecutive values, starting at 0.

A special constructor for adding ten items is a bit strange. But we can do it. Let's create a marker enum:
enum Marker { MakeTenItems };
SLinkedList(Marker)
    : head(nullptr)
{
    for(int loop = 0; loop < 10; ++loop)
    {
        addFront(10 - 1 - loop);  // This will construct an E with an int
                                  // So E must have an appropriate constructor.
    }
}

Then to use it:
SLinkedList<int>  list(MakeTenItems);


Quick review.
This is a very basic review as I am not a react fan. Do not accept this post as an answer or you will likely dissuade others from adding a better one.
Your question

"I used a switch statement in getContent to avoid having an array of objects in memory all the time. Is it actually better performance-wise ?"

By "better performance-wise"  I assume you mean CPU cycles. The answer is, "No its not better."
Computation complexity
For 2 items the difference is tiny, but if you had a long list of items say n is number of items. To display the last item would require n comparisons so worst case is O(n), and best case display the first item is O(1). Picking random items the complexity is O((log n)c) with c just above 2 (AKA polylogarithmic)
What you had return this.state.content[this.state.cidx];, basicly a lookup table, is O(1) the best performance you can get.
Storage complexity
Many times there is a price to pay for using a lookup table and that is memory. But in this case that makes no difference as you are after already stored items rather than looking up a precomputed value.
As I understand it the react elements you defined as <Heroes/>, <Teams/> are store in an internal node tree, having them in an array means you have an extra item in the state object to reference the array and one reference per item. That would require storage O(2n + 1) rather than O(n). Where n in this case refers to a reference to the react elements, not the elements themselves.
O(2n+1) and O(n) are the same, and tiny compared to the elements actual needs.
Style
You could make a slight change
  updateContent(idx) {
    this.setState({cidx:idx});
  }

to
  updateContent(cidx) {
    this.setState({cidx});
  }

But really I only say so as filler as your code looks good, like its almost a cut and paste from the best of react, a good thing (I am not implying you cut and pasted anything )
I do have a long list of style points in regard to your code, but as that list directly contradicts the react style guide it would be rather bad advice.
Merry Xmas


Simple game to learn common port numbers for Sec+ exam

Naming things is hard

Two of your variables have terrible names. To see what I mean, try to guess what the following variables contain, by only looking at their name, but not at your code:

numbers
random_gen

All the other variables are named really good. They name exactly their purpose or accurately describe their content, like incorrect or answer.

Source code layout

In the first section you list the quiz questions. Each of these questions should be on its own line of the code, to clearly show to the reader how the code is structured. That way, all quiz questions are listed nicely below each other, and it's easily possible to count the questions by checking their line numbers in the editor.

It's also easy to see that the 443 question is missing the protocol (TCP), which is difficult to see in the current layout.

The 443 question uses a single string as answer, while the 22 question uses a tuple of the application protocols. Which one is correct, or are they both? I doubt so.

What is the difference between AND and and in the questions? If there is none, choose one spelling and stick to it.

Redundancy

Instead of repeating the question names in random_gen, you can just use the expression numbers.keys().

Instead of writing the number 20 everywhere, better describe what you really mean by that number, which is len(questions). (By now you should have renamed the numbers variable to the more appropriate questions).

Typos

Imap is spelled IMAP
VPN443 is spelled VPN
incorrectis is spelled incorrect is

Bug

The program does not guarantee that you get each question once. Instead of using random_choice for each of the questions you should rather shuffle the questions and then just iterate over them.

Code improvements

Instead of (1==1), better write True.
Instead of var == first or var == second, better write var in (first, second).
There is no need to enclose each condition of an if or while in parentheses. That's only necessary in C and related languages. In Python and Go, it is considered bad style.

The function Sec_port_game should simply be named quiz since that is more specific than game, and at the same time makes the code independent from the Sec+ exam.

The function quiz should take the questions as a parameter, so that you can call it like this:

quiz(secplus_questions)
quiz(popular_rock_bands_questions)

It could be implemented like this:

import random
from typing import Dict

def quiz(questions: Dict[str, str]):

    shuffled_keys = random.shuffle(list(questions.keys()))
    for key in shuffled_keys:
        question = questions[key]

        # TODO: ask the question, compare the answer


Maintainability
Maintainability is a measure of how long it takes to modify some code.
Some things that help improve maintainability.

Use a consistent style throughout the code base. If the code is a group effort then that style must be established before the start of the project.

For naming adopt the language standardized or informal style (Informal for JS as it does not have a standard style). In JavaScript we use camelCase variable names, PascalCase for instantiate-able objects via the new operator.
For constants UPPERCASE_SNAKE with the general rule that we uppercase read-only properties of objects. Though many will also use them for all constants. There is no real consensus regarding the naming of constants but it is not good to be inconsistent in the use of UPPERCASE_SNAKE.
Arrays, lists, and array like objects should use the plural name to indicate that it is more than one entity.
Be consistent in naming items. Do not call the same abstract different names in different locations. EG you called the list of requests lists and group. You called a request insert and putGroup. (see example)

Magic numbers and strings should be in one place so that they don't need to be hunted down to make changes. As they are separated from the code it pays to always comment these constants, include type, limits, and what they are used for. (see example)
To ensure constants are not modified use object.freeze to make them read only. This instills trust in the state of the constants so the coder modifying the code does not have to hunt down each usage of the value to ensure it has not been modified if there are problems.

Reduce the complexity by reducing operator and token counts. Eg if (!foo.length) { a = b } else { b = a } is better as if (foo.length) { b = a } else { a = b }
Reduce the number of return points and keep it DRY. Eg in two places you create a new group and return it. With a little rearranging of the logic the two can be one. (see example)

Readability
This comes hand in hand with maintainability. Low readability also means low maintainability.
Example
not quite how I would have written it (I would use a while loop and have the param requests AKA lists as a safe to mutate copy). Also would have used default params for the constants. However the example is consistent with your original.
I also prefer 4 space indent as I find it much more readable with my old eyes.

const grouping = Object.freeze({ // Request grouping constants for buildGroupRequests
    MAX_SIZE: 50,     // Max length of string per group. Last item may be longer.
    DELIMITER: " + ", // String used to separate groups. Len < MAX_SIZE
    PREFIX: "PUT ",   // String used to prefix groups. Len < MAX_SIZE
});

function buildGroupRequests(requests) {
    return requests.reduce((groupedReqs, request) => {
        if (groupedReqs.length) {
            const lastReq = groupedReqs[groupedReqs.length - 1];
            const putGroup = lastReq.put + grouping.DELIMITER + request.put;
            if (putGroup.length <= grouping.MAX_SIZE) {
                lastReq.put = putGroup;
                return groupedReqs;
            }
        }
        groupedReqs.push({put: grouping.PREFIX + request.put});
        return groupedReqs;
    }, []);
}

console.log(
    buildGroupRequests([
        { put: "/firstName=Danny" },
        { put: "/lastName=Williams" },
        { put: "/email=danny.w@domain.com" },
        { put: "/address=1984 Some St, Very long named place. Woop Woop 6162" }
    ])
);

Update
As requested in comment. Using a while loop and more along the lines as I would write it to be consistent with internal standards. Please note this is not as maintainable if used in a general JS work environment.

const grouping = Object.freeze({
    maxSize: 50,
    delimiter: " + ",
    prefix: "PUT ",
    requests(reqs, {maxSize: max, delimiter: del, prefix: pre} = grouping) {
        var prev = {put: pre + reqs.shift().put};
        const grouped = [prev];
        while (reqs.length) {
            const next = reqs.shift().put;
            const putGroup = prev.put + del + next;
            if (putGroup.length <= max) { prev.put = putGroup }
            else { grouped.push(prev = {put: pre + next}) }
        }
        return grouped;
    },
});

const requests = [
    { put: "/firstName=Danny" },
    { put: "/lastName=Williams" },
    { put: "/email=danny.w@domain.com" },
    { put: "/address=1984 Some St, Very long named place. Woop Woop 6162" }
];

console.log( grouping.requests([...requests]));


Convert data frame to list of lists by row

without any external packages:

feat3 <- function(coords, height = 20, vjust = 75,  fill = "blue"){
  xx <- apply(coords, 1, function(x) {
    list(type = "rect",
         x = as.numeric(x[1]),
         y = vjust,
         width = as.numeric(x[2] - x[1]),
         height = height,
         fill = fill)
    }
  )
  return(xx)
}

all.equal(feat3(coords), result)
# [1] TRUE

Benchmarks:

microbenchmark::microbenchmark(
  feat3(coords),
  feat2(coords), unit = "relative"
)
# Unit: relative
# expr      min       lq     mean   median       uq      max neval cld
# feat3(coords)   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   100  a
# feat2(coords) 315.8261 297.2919 254.5025 258.7822 248.2652 286.9575   100   b


It would be nice if you provide some information about the libraries used in your code. For example, if I want to read about JSONArray and JSONObject, which json library do I need to search for?

The same observation goes for the java classes HttpGet, HttpResponse, HttpClient and DefaultHttpClient. Showing the imports of those classes would also be helpful.

Having said that I only have one suggestion to your code. It seems like you don't need to create the array of Objects from the queue of strings (Object[] q = queue.toArray();), you could just iterate over the elements in the queue and then process each element.

Instead of adding elements to the jArray object this way

        while ((aux = reader.readLine()) != null) {
            queue.add(aux);
        }
        q = queue.toArray();

        for (int i = 0; i < q.length; i++) {
            String[] row = q[i].toString().split(",");
            JSONObject json = new JSONObject();
            json.put("col0", row[0]);
            json.put("col1", row[1]);
            json.put("col2", row[2]);
            json.put("col3", row[3]);
            json.put("col4", row[4]);
            json.put("col5", row[5]);
            jArray.put(json);
        }

I would add the elements in this other way

        while ((aux = reader.readLine()) != null) {
            queue.add(aux);
        }

        for (String row : queue){
            String[] csvValues = row.toString().split(",");
            JSONObject json = new JSONObject();
            json.put("col0", csvValues[0]);
            json.put("col1", csvValues[1]);
            json.put("col2", csvValues[2]);
            json.put("col3", csvValues[3]);
            json.put("col4", csvValues[4]);
            json.put("col5", csvValues[5]);
            jArray.put(json);
        }


SICP 1.3 Sum of Squares of two largest numbers

In my opinion this is too much code for such a simple task.

Assuming that you do not have a max function, you can define it in this way:

 (define (max x y)
   (if (>= x y) x y))

or, if you cannot use if:

(define (max x y)
  (cond ((>= x y) x)
        (#t y)))

Then, the function sosl could be defined as:

(define (sosl a b c)
  (if (> a b)
      (+ (square a) (square (max b c)))
      (+ (square b) (square (max a c)))))

or, again, if you need to use cond, as

(define (sosl a b c)
  (cond ((> a b) (+ (square a) (square (max b c))))
        (#t (+ (square b) (square (max a c))))))


if (HasHeaderRow)
        {

It seems strange, that you know in advance, if the file has headers or not? If that is right, why then call the method in the first place if HasHeaderRow is false - when you do nothing in that case?

  public List<(string IPN, string FPTech)> GetIPNFPTechFromCSV(string filePath)

I would return IEnumerable<..> instead and then use yield return to return each data pair (see below).
I would define a struct or class instead of using a named tuple. IMO named tuples are only useful very locally, because they can be harder to maintain, if their definition changes and you distribute them across the application (see below).

  var IPNFPTechPair = (IPN: line.Split(Delimiter)[IPNPos], FPTech: line.Split(Delimiter)[FPPos]);

Here you split the same string twice. It would be better to do:

string[] cells = line.Split(Delimiter);
var IPNFPTechPair = (IPN: cells[IPNPos], FPTech: cells[FPPos]);

You should handle all the heading stuff in a separate method in order to make the design and responsibility more clear.

All in all I would do something like:

public IEnumerable<IpnItem> Read(string filePath)
{
  using (StreamReader reader = new StreamReader(filePath))
  {
    (int ipnColumn, int fptechColumn) = ReadHeaders(reader);

    string line;
    while ((line = reader.ReadLine()) != null)
    {
      string[] cells = line.Split(Delimiter);
      yield return new IpnItem(cells[ipnColumn], cells[fptechColumn]);
    }
  }
}

private (int ipnColumn, int fptechColumn) ReadHeaders(StreamReader reader)
{
  string[] headers = reader.ReadLine().Split(Delimiter);
  if (headers.Length != 2) throw new Exception("Number of column headers should be 2");
  (int ipnColumn, int fptechColumn) columnIndices = (Array.IndexOf(headers, "PartNumber"), Array.IndexOf(headers, "FPTech"));
  if (columnIndices.ipnColumn == -1 || columnIndices.fptechColumn == -1) throw new Exception("Invalid or missing column names");
  return columnIndices;
}

Where IpnItem is declared as:

  public class IpnItem
  {
    public IpnItem(string ipn, string fpTech)
    {
      IPN = ipn;
      FPTech = fpTech;
    }

    public string IPN { get; private set; }
    public string FPTech { get; private set; }
  }


In your example, you have two passes over the list - std::distance works in linear time unless it operates on random access iterators.

A naive way to fix this is to calculate the number of elements inside your for loop and check it afterwards. But this way you'll pessimize performance for random access iterators.

To avoid this pessimization you can examine the iterator_tag of you Iter at compile time and decide whether you're going to call std::distance or count your elements in a loop.

The simplest way to do this is in C++14 is by tag dispatching. Here is an example:

template<typename RandomAccessIter>
double sd(RandomAccessIter begin, RandomAccessIter end, std::random_access_iterator_tag)
{
    // calling std::distance
}

template<typename ForwardIter>
double sd(ForwardIter begin, ForwardIter end, std::forward_iterator_tag)
{
    // counting elements in a loop
}

template<typename Iter>
double sd(Iter begin, Iter end)
{
    // dispatching
    return sd(begin, end, typename std::iterator_traits<Iter>::iterator_category());
}

This code will corretly handle bidirectional iterators as well since std::bidirectional_iterator_tag inherits from std::forward_iterator_tag. And code duplication can be avoided by incaplusating common logic in separate functions.

Viola! Now you have only one pass.


Python algorithm for identification of low-level jets (meteorology)

Naming the variables

wspd_matrix would be much easier to read if it were called wind_speed_matrix
jetspd would be much easier to read if it were called jet_speed
jethgt would be much easier to read if it were called jet_height

Remove the numeric values in the code

0.8 and 2.5 appear quite often in your code. It is hard for someone without a domain knowledge to know what they stand for. And if you have to change them for some reason, this is error-prone. Why not just naming them (max_multiplier = 0.8 per example) at the beginning of the function ?

Redundant condition

if x<0.8*maxspd and x<maxspd-2.5

appears twice in your code. It represents a clear mathematical function :

if x<min(0.8*maxspd , maxspd-2.5)

which is much easier to read (and picture mentally)

Redundant code

Something needs to be done about this three prints :

print 'Maximum found at time',t,'and level',i,'with speed',x,'m/s'
print 'Minimum found at time',t,'and level',i,'with speed',x,'m/s'
print 'Minimum found at time',t,'and level',i,'with speed',x,'m/s'

Maybe a

print_local_optimum_found(type_optimum, at_time, at_level, at_speed)

Check the input

if maxflg and not minflg:
    print 'probably something wrong with NaNs'

Why waiting until the end of the program to realize something wrong happened ? If you know NAs cause trouble, just check the presence of NAs before

The algorithm itself

It is hard to suggest improvements now with every piece of code in the same function. If you fix all this, such improvements will become much more readable!


Reading a file chunk by chunk in QT 4.3.3

As you're storing the whole result into memory anyway for display in a text editor (so you're not expecting to load hundreds of MB of text), why not just use what Qt provides to read the entire file into a string in one call?

It's probably more than enough optimized for general purpose usage. Displaying the entire result in the editor might also be faster than constantly appending parts.

I also see that you're using the C API for opening the file (which is never closed) and then passing it to Qt. Qt has QFile for this, as shown in the link mentioned above.


Finding the frequency of an element in a sorted list of integers

Reinventing the wheel

There is already a binary search available in JDK.

Bug

On the array {2,3,4,25,99,99,99,99,19000} your implementation returns 0. Removing the lines

else if (lo !=mid)
    high = mid;

from elementExists seems to fix the issue.

Printing from an algorithm

System.out.println("Mid is: " + mid);

It is not a good idea to print to stdout from an algorithm; at least not in the production code. Think about what happens if your friend uses your code: he gets overwhelmed with all the output + I/O is usually computationally expensive.

Summa summarum

All in all, I had this in mind:

import java.util.Arrays;

public class FrequencyElement {

    public static void main(String args[]) {
        int input_array[] = {2, 3, 4, 25, 99, 99, 19000};
        int element = 99;
        System.out.println(getElementFrequency(input_array, element));
    }

    static int getElementFrequency(final int array[], final int queryElement) {
        final int index = getElementIndex(array, queryElement);

        // If there is more than one query elements. Arrays.binarySearch does
        // not guarantee that the index returned will point to the left most
        // occurrence.
        if (index < 0) {
            return 0;
        }

        int count = 1; // Count array[index].
        int offset = 1;

        while (index - offset >= 0 && queryElement == array[index - offset]) {
            ++offset;
            ++count;
        }

        offset = 1;

        while (index + offset < array.length
                && queryElement == array[index + offset]) {
            ++offset;
            ++count;
        }

        return count;
    }

    private static int getElementIndex(final int[] array,
                                       final int queryElement) {
        return Arrays.binarySearch(array, queryElement);
    }
}

Hope that helps.


In python your spell_check function could, and should be written like this:

def spell_check(word, english):
    return word if word in english else None

Dict and sets has there differences, one being that membership testing is faster with sets, they also consume less memory, which will be important for the efficiency of your program.

So a pythonic way of defining "english" would be something inline with:

with open("wordlist", "r") as f:
    english = {word.strip() for word in f}

you could still define the set above for readability.

Now that you have a set that you could use for membership testing, I think it's remove the function spell check, since it adds a line of code and somewhat obscures the program. If it did something more then checked for membership, sure, bur right now, no.

In that case, you could remove the third for loop and create a generator to let the program deal with only one word at the time and further reduce memory usage.

with open("check", "r") as f:
    with open("output", "w") as output:
        wrong = (x.strip() for x in f if x.strip() not in english)
        for key, word in enumerate(wrong):
            output.write("{}: {}\n".format(key, word))

what happens here is that the two files are open at the same time, and since wrong is a generator, it will read one line, in this case word, at the time. If the currently written word is in english it yield it and write it to the file.

Pythons enumerate builtins purpose is for these kinda situations, where you want to iterate over something while still keeping track of the rounds.

You should also make it a habit to protect your main function by,

if __name__ == '__main__':
     main()

to avoid executing self written programs when importing them.

Putting it all together:

def main():

    with open("wordlist", "r") as f:
        english = {word.strip() for word in f}

    with open("check", "r") as f:
        with open("output", "w") as output:
            wrong = (x.strip() for x in f if x.strip() not in english)
            for key, word in enumerate(wrong):
                output.write("{}: {}\n".format(key, word))

if __name__ == '__main__':
    main()


Finding a perfect square smaller than an input number (Swift)

Also using a playground (if that helps)

Well, that is the main reason for the slow execution. A playground is an interactive environment, and the code is not optimized. For all computations in the main playground file, intermediate results are displayed in the side bar (such as the values of the variables, or how often a loop has executed). This makes longer computations really slow.

For code that consists of many computation steps you better

either move it to a function in a separate playground source file,
or use a compiled Xcode project instead of a playground.

I often prefer a compiled project over a playground because

you can debug your code (single-step, inspect variables, ...),
you can enable optimizations (compile with the “Release” configuration) for performance critical tasks.

But your code can also be simplified and optimized. This loop

var index = 0
var smlSqr = [Int]()
repeat {
    smlSqr.append(index * index)
    index += 1
} while(index < findLimit)

appends one array element in each loop iteration, so that it can be written as a map operation:

let smlSqr = (0..<findLimit).map { k in k * k }

(You may also think about better variable names: what does smlSqr stand for?)

And this

var maxSqr = 0 // Final result
var candidate = 0
while candidate < smlSqr.count {
    if smlSqr[candidate] > maxSqr {
        maxSqr = smlSqr[candidate]
    }
    candidate += 1
}

determines the largest array element. The is a dedicated method for that purpose:

let maxSqr = smlSqr.max()!

(We can force-unwrap here if we know that the array is not empty.) But the array elements are sorted in increasing order, so that the largest element is actually the last element:

let maxSqr = smlSqr.last!

So what we have so far is

let target = 758865
let findLimit = Int(Double(target).squareRoot().rounded(.up))
let smlSqr = (0..<findLimit).map { k in k * k }
let maxSqr = smlSqr.last!

and now we can see that this can be simplified even further: The last element appended to the array is (findLimit - 1) * (findLimit - 1), so that we only need

let target = 758865
let findLimit = Int(Double(target).squareRoot().rounded(.up))
let maxSqr = (findLimit - 1) * (findLimit - 1)

(And this is so short and fast that you can execute it in in a playground directly, without any of the optimization tricks mentioned above.)

To make the code reusable, you should define it as a function:

func largestSquareRoot(lessThan n: Int) -> Int {
    let root = Int(Double(n).squareRoot().rounded(.up)) - 1
    return root * root
}

Note that this gives a nonsensical result for \$ n = 0 \$ and crashes for \$ n < 0 \$. You'll have to define what result you want in those cases.


Haskell marking procedure for non-unique lists

Found a deceptively simple solution.

selections (left,right) = nub [(delete o left,right ++ [o]) | o <- left]

List comprehensions are great.


Basics
In Java, since version 7, there is no need to specify the generic type of a generic class on the right-hand side of the initializer. Instead, you can use the "diamond operator". The following:

    ArrayList<Integer> chairs = new ArrayList<Integer>();

should be:
    ArrayList<Integer> chairs = new ArrayList<>();

Additionally, unless you have a specific need, you should use the highest level of abstraction that's useful for your variables. There is no need to declare chairs as an ArrayList, when a List would be fine:
    List<Integer> chairs = new ArrayList<>();

Data Types
Here you have used an ArrayList, but this is a bad choice. Performance in ArrayLists is poor when you add or remove items from the middle of the list. A LinkedList is generally better for that type of operation.
Alternate solution
A linked list is a great option for this problem, because it can be made to behave like a circle. What we do, is start with a populated list, and then "walk the list". We remove the first member, then take the next member, and move them to the end of the list. Then we remove the third member, and the 4th and 5th survive and go to the end. Note that the first, second, and third survivors (chair 2, 4, and 5) are now next to each other at the end.... (after chair 100).
Note that for every member we remove from the list, we add a bunch of survivors  to the end. By doing some modulo arithmetic, the amount we shift to the end can be controlled to the size of the remaining members.
We repeat the process until the list is size() == 1
private static int getSurvivorsLL(final int numChairs) {
    Deque<Integer> chairs = new LinkedList<>();
    while (chairs.size() < numChairs) {
        chairs.add(chairs.size() + 1);
    }
    int skip = 0;
    while (chairs.size() > 1) {
        System.out.println("Eliminated " + chairs.removeFirst());
        skip++;
        int shift = skip % chairs.size();
        for (int i = 0; i < shift; i++) {
            chairs.addLast(chairs.removeFirst());
        }
    }
    return chairs.removeFirst().intValue();
}

Note that, because I need the removeFirst() method, I use the Deque personality for the LinkedList.
Update - Neat, Custom, or Fast
This question got me thinking, for both good, and bad reasons. I initially misread the question, and gave a broken answer. Then I "improved" my alternative suggestion to be a more natural language fit than an ArrayList (which does not have O(1) "remove" time).
Unfortunately, for me, I then ran a benchmark against my code, and the OP's code. My code lost, even though the LinkedList is a more natural fit for this problem. It just makes sense that the LinkedList should be faster... all we are doing is shuffling items one-at-a-time to the end of the list. and there's only one item moved each turn. So, why was it slow? To put things in perspective, here are the times of the OP's code:
Task Chairs -> OP: (Unit: MICROSECONDS)
  Count    :   1000000      Average  :    2.3310
  Fastest  :    1.9730      Slowest  : 1878.1240
  95Pctile :    2.7630      99Pctile :    3.9480
  TimeBlock : 2.506 2.323 2.245 2.479 2.268 2.262 2.265 2.262 2.386 2.319
  Histogram : 981012 14462  4176   229    97    13     5     3     1     2

It computes the solution for 100 chairs in under 2 microseconds. But the time for the LinkedList solution I propose is:
Task Chairs -> LL: (Unit: MICROSECONDS)
  Count    :    182906      Average  :   16.4010
  Fastest  :   13.8150      Slowest  : 2252.3280
  95Pctile :   23.6840      99Pctile :   30.7890
  TimeBlock : 20.028 16.870 18.086 16.485 15.615 15.323 15.411 15.385 15.399 15.417
  Histogram : 179027  3537   253    52    15     2    16     4

where the fastest time is in about 14 mircoseconds - 7 times slower than the OP code, even though it in theory does less work!.
Right, so, what would make the code faster? First up, I designed a custom node class that would be simpler than a full Linked List. Here is the code:
private static final class Chair {
    private final int id;
    private Chair next = null;

    public Chair(int id) {
        this.id = id;
    }

}

private static int getSurvivorsCL(final int numChairs) {
    Chair previous = buildCircle(numChairs);
    int size = numChairs;
    while (size > 1) {
        Chair togo = previous.next;
        previous.next = togo.next;
        togo.next = null;
        size--;
        int shift = (numChairs - size) % size;
        while (shift-- > 0) {
            previous = previous.next;
        }
    }
    return previous.id;
}

private static Chair buildCircle(int numChairs) {
    final Chair last = new Chair(numChairs);
    Chair tmp = last;
    while (--numChairs > 0) {
        Chair c = new Chair(numChairs);
        c.next = tmp;
        tmp = c;
    }
    last.next = tmp;
    return last;
}

The above code is a 'clean' version of what I would expect the circular chair arrangement to accomplish. What is the time for that?
Task Chairs -> CL: (Unit: MICROSECONDS)
  Count    :     943355      Average  :     3.1800
  Fastest  :     2.3680      Slowest  : 34884.2530
  95Pctile :     3.5520      99Pctile :     3.9480
  TimeBlock : 3.243 3.098 3.068 3.160 3.478 3.202 3.241 3.047 3.127 3.137
  Histogram : 936200  2336  4519   169    84    29     3     1     2     4     4     2     1     1

This is 4 times faster than the LinkedList, but, it is still 50% slower than the OP's code? The 4-times faster than LinkedList is impressive, but there's still something that does not make sense to me.... it should be faster than ArrayList.
So, to experiment, I used an even simpler approach of a static array, where none of the data is moved at all. The only thing updated is a "pointer" to the next chair. In other words, the index in the array is essentially the chair number, and the value in the array is the "next" chair. This way we can create a logical circle, and just change a pointer each time a chair is removed. Here is the code:
private static int getSurvivorsAN(final int numChairs) {
    int[] chairs = new int[numChairs];
    for (int i = 1; i <= numChairs; i++) {
        chairs[i - 1] = i % numChairs;
    }
    int current = numChairs - 1;
    int skip = 0;
    int size = numChairs;
    while (current != chairs[current]) {
        int remove = chairs[current];
        chairs[current] = chairs[remove];
        size--;
        skip++;
        int loopskip = skip % size;
        while (--loopskip >= 0) {
            current = chairs[current];
        }
    }
    // chairs are 0-based, we need to return 1-based, so add 1.
    return current + 1;
}

How fast was that?
Task Chairs -> AN: (Unit: MICROSECONDS)
  Count    :     939602      Average  :     3.1920
  Fastest  :     2.7620      Slowest  : 18780.0630
  95Pctile :     3.5530      99Pctile :     3.9470
  TimeBlock : 3.271 3.145 3.127 3.181 3.195 3.141 3.140 3.152 3.175 3.401
  Histogram : 934304   761  4360   114    47     9     3     2     0     1     0     0     1

About the same as the Chair node version above... but, still slower than the OP.
So, how to beat the OP? Well, it must boil down to the fact that a System.arrayCopy() of all the "remaining" chairs in the circle (what should be an O(n) operation, where n is the size of the List, is more efficient than looping over each value in the skip. So, for example, on the first iteration, we remove chair 1, it must mean that copying every other chair "back one spot" is faster than just moving 1 chair to the end. To test this, I made an efficient version of ArrayList (i.e. using primitives, not Integer). Here's the code:
private static int getSurvivorsAS(final int numChairs) {
    int[] chairs = new int[numChairs];
    for (int i = 0; i < numChairs; i++) {
        chairs[i] = i + 1;
    }

    int remove = 0;
    int skip = 0;
    int size = numChairs;
    while (size > 1) {
        size--;
        System.arraycopy(chairs, remove + 1, chairs, remove, size - remove);
        chairs[size] = 0;
        skip++;
        remove = (remove + skip) % size;
    }
    return chairs[0];
}

How does this compare?
Task Chairs -> AS: (Unit: MICROSECONDS)
  Count    :   1000000      Average  :    1.6140
  Fastest  :    1.1840      Slowest  : 1699.3120
  95Pctile :    1.9740      99Pctile :    2.3690
  TimeBlock : 1.653 1.614 1.573 1.689 1.593 1.591 1.592 1.583 1.650 1.606
  Histogram : 970982 26003   384  2495    78    35    17     4     1     0     1

So, what does this all mean?
Well, it means that System.arraycopy() is fast. How do things scale, though?
Here are the scaling charts for three of the code blocks, the OP code, the best Circular List code (with the Chair node), and the ArrayShift code.
All three have a O(n^2) type complexity, so it all washes out, essentially. Note that the array-shift code is fastest for all tested scales (all the way up to more than 100,000 chairs.
Conclusion
The OP's code is better than I expected in terms of performance. The LinkedList code is worse than I expected. The best code from a readability perspective is, I think, the LinkedList code. It best represents the actual problem.
The best code from a performance perspective is a primitive array-of-int which you shift using System.arrayCopy() in order to remove chairs.


Generally, RegExps are a bad choice to deal with HTML code. You're better of with DOM parser: parse the tree and then use XPath to find desired elements, i.e. the ones containing the torrent name and the magnet link. I'm not posting any code because I've never done it in PHP though, but as a pointer...

Anyway, if you just wanted a simple script that just works, you're good, and if you wanted to do some self-education, you can try parsing the DOM.

The first search result from Google gives me this: http://simplehtmldom.sourceforge.net/

And some points on the code style:

You have some weird (IMO) indentation in the if statement. Usually the closing bracket is on the same level as if is, i.e.:

if (mail($to, $subject, print_r($matches, 1), 'From: BlackBeard@piratemail.com')) {
    echo("
Message successfully sent!
");
} else {
    echo("
Message delivery failed...
");
}

And you have inconsistent spaces-after-arguments:

preg_match_all($selected,$data,$matches, PREG_OFFSET_CAPTURE);
....
mail($to, $subject, print_r($matches, 1), 'From: BlackBeard@piratemail.com')

Second one (with spaces after commas) is usually a preferred one.


Checking for a win along the top row of a Tic Tac Toe board

You're checking if each section of your board is enabled as part of your check, this check makes your test look more complicated than it needs to be.  Part of this is because your board is tightly integrated into its graphic representation.  Generally speaking you want to try to avoid this, it makes both layers easier to change.

Rather than having a signature of Connected() consider writing something more like this (pseudo code):

bool CheckWin(string currentPlayer) {
    foreach row in rows
        return true if CheckWinningRow(row, currentPlayer)
    // Check Columns
    // Check Diagonals
}

bool CheckWinningRow(int row, string currentPlayer) {
    return true if (board[row*3] == currentPlayer &&
                    board[row*3+1] == currentPlayer &&
                    board[row*3+2] == currentPlayer);
}

Checking each row is going to be the same action, it's just going to be a different starting location in your array.

You only need to check if the last player (currentPlayer, either X or O) has won.  If you work by checking the current player, you don't need to know if the button is enabled (has already been played) it's not going to have the current player's value in it if it hasn't been played on yet.


Simple Example of an Iterable and an Iterator in Java

Variables

I understand why you have the Range.this.end and Range.this.start to avoid confusion about where those variables come from... If you need the Range.this as part of the teaching exercise, then sure. Otherwise, I would recommend three things....

add range as a prefix, even though it is slightly redundant
Make them final...
one variable per line... (it makes revision-control diffs/patches easier to read)

The code would look like:

private final int rangeStart;
private final int rangeEnd;

Then, all the Range.this.start would be just rangeStart, etc.

Nested classes

Your iterator class is a non-static class, so it can reference the outer class's range start/end.

In this case, the nested class can be changed to a static class very easily. This has the potential of simplifying memory management because the iterator does not need a reference to the enclosing Range.

Consider a private-static Iterator instance:

// Inner class example
private static final class RangeIterator implements
                Iterator<Integer> {
    private int cursor;
    private final int end;

    public RangeIterator(int start, int end) {
        this.cursor = start;
        this.end = end;
    }

    public boolean hasNext() {
        return this.cursor < end;
    }

    public Integer next() {
        if(this.hasNext()) {
            int current = cursor;
            cursor ++;
            return current;
        }
        throw new NoSuchElementException();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

This static class removes the need for the back-references to Range.this entirely....

The new iterator is called simply with:

public Iterator<Integer> iterator() {
    return new RangeIterator(start, end);
}

Pre-Validate

It is better to pre-validate state, than to fall-through to an error... This code:

    public Integer next() {
        if(this.hasNext()) {
            int current = cursor;
            cursor ++;
            return current;
        }
        throw new NoSuchElementException();
    }

would be better as:

    public Integer next() {
        if(!this.hasNext()) {
            throw new NoSuchElementException();
        }
        int current = cursor;
        cursor ++;
        return current;
    }

Post-Increment

This block can be simplified:

        int current = cursor;
        cursor ++;
        return current;

to just:

return cursor++;

although I imagine this is done as an education ploy.

Integer as the example

Because of the int auto-bocxing I worry that Integer may not be the right choice for data type. You may want to consider a non-primitive as the data.

Autoboxing is the sort of thing that will confuse.

Conclusion

Otherwise, I don't see much in the way of problems.


Designing a binary tree structure from scratch in C

Here are some things that may help you improve your code.

Don't leak memory

The main routine begins with these two curious lines of code:

root = (bin_tree *) malloc (sizeof(bin_tree));
root = NULL;

That's a guaranteed memory leak because we no longer have any way to refer to the memory allocated by malloc.  Since your create_tree function will automatically allocate space for the root node, I'd change that to this, combining declaration and initialization:

bin_tree *root = NULL;

Check return values and handle errors

The code calls malloc but never checks for error return values.  This is a serious problem that must be addressed.  Also, scanf can return EOF if there was an error, but that condition is neither checked nor handled.

To be more precise, the way that the underlying operating system lets a program know that it cannot allocated the requested memory is by returning NULL from a call to malloc.  Robust programs should always check for that condition before using the returned value as a pointer or they will risk a crash by dereferencing a NULL pointer.

Similarly, scanf returns the number of arguments successfully scanned.  In your case it should be 1 because each call is scanning one integer value.  If it's anything other than 1, it's an indication of a problem that should probably be handled gracefully by the program, perhaps by emitting a message to the user that only integer values are allowed and asking again.

Use "in-order" tree traversal

The binary tree you've constructed maintains the order of entries, so to take advantage of this, we should use in-order.  It's as simply as changing the order of two lines of code so the print_tree code looks like this:

void print_tree(bin_tree *root) {
    if (root != NULL) {
        print_tree(root->left_child);
        printf("%d ", root->value);
        print_tree(root->right_child);
    }
}

So for example, when I feed the program this input:

  10 5 33 2 18 17 15 20 22 1 8

The program then constructs this tree:

And an in-order traversal produces this output:

  1 2 5 8 10 15 17 18 20 22 33

Put each statement on a single line

It detrimental to the readability of your code to put multiple things one the same line. So instead of this:

else if(val < (*root)->value){ create_tree(val, &(*root)->left_child);}

I would recommend writing this:

else if (val < (*root)->value) {
    create_tree(val, &(*root)->left_child);
}

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Security is hard. The recommended approach to implementing anything crypto related is let someone else do it! When I first thought, before reading the code, that you were actually trying to implement AES from scratch by hand in VB, I was just going to say don't. You aren't doing that, but there are still a lot of fiddly details to worry about for a secure system.

Dim initVector As String = "Bla3212EWMND12es"

The purpose of an initialisation vector is to randomise the subsequent stream. The way that AES under CBC (or one of its successors) works is that you encrypt the first block with the key, the second block with the key and the first block, the the third block with the key and the second block, and so on. This means that even if two blocks contain the same data, they won't be the same once they're encrypted.

However, this does mean that if two messages are the same, they'll encrypt to the same thing. Even if two messages are different but the first 100 blocks are the same, the first hundred blocks will encyrpt to the same thing. This might not sound like much, but it gives valuable information to an attacker.

Solution: we use initialisation vectors. If you start your message off with one block of random junk, even two identical messages will (assuming an ideal cipher) have no more in common than with the equivalent amount of random noise. For this to work, initialisation vectors must be different each time. (The initialisation vector is not secret: you can happily stick it onto the front of your encrypted file in plaintext so the decrypt side knows how to start off. But generate it with your favourite cryptographically secure random number generator.)

symmetricKey.Mode = CipherMode.CBC

I've briefly described the idea behind CBC above. Of the available ciphermodes, it is not a bad one for encrypting static files although there have been some quite famous attacks on it when used to encrypt network traffic. (Basically, you should use anything but ECB!)

ByVal EncryptionKey As String

Darting right back to the top, be careful with security data. From the context I'm infering that this is a password of some description, presumably user-supplied. Whereever it comes from, crypto libraries do all sorts of magic to make sure that secret data (especially passwords and keys) get wiped out of RAM once used and don't get accidentally written to the page file or something. I am not familar enough with VB.net to say how you'd do that, but you should consider your chain of custody here.

Dim symmetricKey As New RijndaelManaged()

Per MSDN:

  The Rijndael algorithm is the predecessor of Aes. You should use the Aes class instead of RijndaelManaged. For more information, see the entry The Differences Between Rijndael and AES in the .NET Security blog.

plain.CopyTo(cs)

It's worth thinking about what you want to happen to your plaintext file. I very much would not expect anything about it to change in an EncryptFile function, and very often you do just want it to just stay there and do nothing. However, I'll at least mention it in case you don't want a copy of the original: in that case you want to securely delete it. There's nothing quite so satisfying for an attacker as ignoring all your fancy encryption and reading the unencrypted original straight from disk!


Python script to execute a command using Paramiko SSH

All your imports should be below eachother like this:

import sys
import paramiko
import getpass

I think using classes is a bit too much for this, but you should create a few functions to diverse functionality

A Main
A function for the shell commands
A function for connecting

This should be enough for now, you can always add more. Secondly when using comments they should be like this

# A comment
print('do something')

instead of this:

print('do something') # A comment

I do think you have too many comments because the names kind of speak for themselves

def ssh_command(ssh):
    command = input("Command:")
    ssh.invoke_shell()
    stdin, stdout, stderr = ssh.exec_command(command)
    print(stdout.read())

def ssh_connect(host, user, key):
    try:
        ssh = paramiko.SSHClient()
        print('Calling paramiko')
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=host, username=user, key_filename=key)

        ssh_command(ssh)
    except Exception as e:
        print('Connection Failed')
        print(e)

if __name__=='__main__':
    user = input("Username:")
    key = input("Public key full path:")
    host = input("Target Hostname:")
    ssh_connect(host, user, key)

I think your program is ok, but could use some improvement, be sure to check out the Paramiko demo's these contain many usefull pointers for working with parmiko


Whenever you find you have a situation where you are tring to match values to numbers, especically sequential numbers, the trick is to use an array. This makes the whole thing simpler, and centralizes the logic in one place, and the data in another.

Before we go there, though, some other things are:

Java class names should be Pascal case (upper-case word-starters), so it should be called Apple, and not apple.
There is no need to "pre-declare" variables. int selection; is unnecessary, just make the setting line: int selection = input.nextInt();

For example, your code could easily be:

import java.util.Scanner;

public class Apple {

    private static String[] DRINKS = { "Coffee", "Tea", "Juice", "Fizzy Drink" };

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 4; i++) {
            System.out.println("Please enter the selection you would like");

            for (int d = 0; d < DRINKS.length; d++) {
                System.out.printf("Enter %d for %s\n", d + 1, DRINKS[d]);
            }
            int selection = input.nextInt() - 1;
            if (selection >= 0 && selection < DRINKS.length) {
                System.out.println("You have chosen " + DRINKS[selection]);
            } else {
                System.out.println("You have made a wrong selection, please re-select");
            }
        }
    }
}

Note how I have reused the DRINKS array when both printing the prompt, and selecting the Drink. Also note that you can add drinks just by changing the array.

Finally, I find that using printf(...) is convenient when formatting data.


Sending a file over a socket with AES encryption

try-with-resources

        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance(HASH_ALG);
            fis = new FileInputStream(this.filePath);
            byte[] byteArray = new byte[1024];
            int bytesCount = 0;
            while ((bytesCount = fis.read(byteArray)) >= 0)
                md.update(byteArray, 0, bytesCount);
            byte[] hash = md.digest();
            fis.close();
            return String.format("%032x",new BigInteger(1, hash));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error in checksum");
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException("Error in checksum. Provided file can't be closed.");
            }
        }

In a normal run, you try to close the stream twice.  You do not need to call close() before the return.  The finally block will take care of it.

There is also an issue.  If there is an exception in the getInstance call, you will attempt to dereference a null pointer in the finally block.

You can rewrite this

        try (FileInputStream fis = new FileInputStream(this.filePath)) {
            MessageDigest md = MessageDigest.getInstance(HASH_ALG);

            byte[] bytes = new byte[1024];
            for (int bytesCount = fis.read(bytes); bytesCount >= 0; bytesCount = fis.read(bytes)) {
                md.update(byteArray, 0, bytesCount);
            }

            return String.format("%032x", new BigInteger(1, md.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error in checksum");
        }

This uses a try-with-resources so that you don't have to manually close the resource.

I prefer names like bytes to byteArray as being simpler and more focused on what the data means logically than how it is stored physically.  You can read more about this in discussions of Hungarian notation.  This is somewhat controversial.  I mostly mention it because the code was scrolling when it was named the Hungarian notation way.

Using the for loop to replace the while reduces the scope of the bytesCount variable.  Other than that, both do the the same thing.

I added some vertical whitespace to break things up.

It's not necessary to assign the result of md.digest() to a variable.  We can pass it directly to the BigInteger constructor.  Either way works though.


Java 2d array Hourglass Sums challenge from Hackerrank

Avoid magic number

6 and 16 should be replace with properly named constants... 16 is also dependant of the first number ; if I'm not mistaken the number of possible hourglasses is (6 - 2)²

public static final int GRID_SIZE = 6;
public static final int NUMBER_OF_POSSIBLE_HOURGLASSES = Math.pow(GRID_SIZE - 2, 2);

Better naming

Most of your variable have good name, however it's not useful to name indices arr_i and arr_j, name them simply i and j.

The class name is not that good IMO, HourGlassSolver or HourGlassFinder would be better.

findmax should be cased like this findMax

Parameters for calculateHourGlassSum have unclear name (pos2 ??)

Simplify your function

Your function do their jobs well but can be made shorter thanks to the new Java 8 Stream API.

For example, your findmax :

public static int findMax(final int arr[]) {
    return Arrays.stream(arr).max().get();
}

Extract part of your code into a function

for (int i = 0; i < 4; i++) {
   for (int j = 0; j < 4; j++) {
       hourGlassSum[pos] = calculateHourGlassSum(arr, i, i + 2, j, j + 2);
       pos++;
   }
}

This should probably be made into a distinct function that returns an int array or a List<Integer>.


Aliases
Table aliases are handy, sure. But single-letter aliases are not good. It's OK to want to save having to type more characters than needed, but you have to keep in mind that things like aliases and variables get really confusing if the name you give it does not say anything about what it means. c, o, p, ot... Why not instead cust, ord, prod, ordItems?
Table naming
orders-items is not a good table name. Why? Well, because you will have to use back ticks each time you reference it, as opposed to your other tables. In SQL, avoid using reserved characters in table/column names to negate this problem. If possible, rename to orders_items or OrderItems or something along those lines.
To rename the table:
RENAME TABLE `orders-items` TO orders_items;

Consistency
Your SQL queries, though both are valid, look completely different. Compare this:
    $order_data = $connection->prepare("SELECT c.first_name, c.last_name, c.email_adress, c.customer_info, o.order_info, o.total_price, o.location, o.created FROM customers AS c LEFT JOIN orders AS o ON c.id = o.customer_id WHERE o.id = :order_id LIMIT 1");

And this:
    $query = "SELECT `products`.`name`, `orders-items`.`quantity` FROM `orders-items`" . "INNER JOIN `products` ON `orders-items`.`products_id` = `products`.`id`" . "WHERE order_id = :ordero_id LIMIT 1";

One of them you use table aliases, the other you use full table names. The latter you use back ticks, but not the former. The latter you also have periods splitting your query code. Stick to one style to make your code easier to maintain.
Your question
Your first query is selecting one specific order along with the customer associated with it. Your second query is selecting one specific order along with the items associated with it. If you want to combine both, then assuredly you will get customer information multiple times in your result set. Your LIMIT 1 seems like it would not be very useful... Can an order be placed by multiple customers?
However, since orders is your primary table, I suggest to start from there, then JOIN your other tables with INNER JOIN so you don't return nulls (if that is the intent, and assuming an order has to have a customer, and has to have items).
All said, I think this should work for what you are trying to do:
SELECT
    ord.id,
    ord.order_info,
    ord.total_price,
    ord.location,
    ord.created,
    cust.id,
    cust.first_name,
    cust.last_name,
    cust.email_adress,
    cust.customer_info,
    ordItems.quantity,
    ordItems.products_id,
    prod.name,
    prod.price
FROM
    orders AS ord
        INNER JOIN
    customers AS cust ON ord.customer_id = cust.id
        INNER JOIN
    `orders-items` AS ordItems ON ord.id = ordItems.order_id
        INNER JOIN
    products AS prod ON ordItems.products_id = prod.id
WHERE
    ord.id = :order_id;


Splitting a string basing myself on categories

Relying on special values (namely '·') not to be present in the input is a bad idea.  Your problem is basically a variant of itertools.groupby(), so you should use that.

from itertools import groupby

def split_on_changes(string, cats):
    """
    docstring and doctest here

    """
    def category(char):
        """
        Return the index of the category to which char belongs
        (or None if it does not belong to any category).
        """
        return next((i for (i, cat) in enumerate(cats) if char in cat), None)
    return list(''.join(group) for _, group in groupby(string, category))

The category() helper function is based on this technique to find the first element of a list that satisfies a predicate.  It could also be written as

def category(char):
    for i, cat in enumerate(cats):
        if char in cat:
            return i

Depending on what you want to do with the results, you might want to consider not calling list() and string.join().


It's correct, but it's ineffiecent. It uses O(n^2) time in the worst case (for instance, if the input's ((((((..)))))))).

You can do better than that by iterating over the input string and keeping a stack of brackets, pushing opening brackets to it and popping when you encounter closign brackets, checking that it's not empty and that the top bracket matches the current one.


You have a lot of repeats

 if (ace == guess) {
      System.out.println("You nailed it! Fast Eddie reluctantly hands over your winnings, scowling.");
  }
  else  {
      System.out.println("Ha! Fast Eddie wins again! The ace was card number " +ace+".");
  }

  if (ace == 1) {
      System.out.println("AA  ##  ##");
      System.out.println("AA  ##  ##");
  }
  else if (ace == 2) {
      System.out.println("##  AA  ##");
      System.out.println("##  AA  ##");
  }
  else if (ace == 3) {
      System.out.println("##  ##  AA");
      System.out.println("##  ##  AA");
  }
  System.out.println("1   2   3");

Could put the ace position in an array and just reference it by index
I don't know java to write an array


Just a few suggestions:

Probably advisable to use Int.TryParse instead of CInt(txtCLock.Text) for parsing user input so you don't get an invalid type exception.

On general error handling you might at least put a try/catch around the logic in txtCLock_TextChanged to catch any errors at a lower layer and either log them or present to the user in a nice way if applicable.

If you're not actually referencing the first/last name backing fields you can use automatic properties so you don't have to write a get/set for every property.


Scroll with multiple, and going different directions

Ok, I got my code to work.

I kept my HTML the same but made a few changes to my jQuery.

    $(document).ready(function(){
$('html, body').animate({
    scrollTop: $(".ganesh").offset().top,
}, 5000).animate({
    scrollLeft: $(".bird1").offset().left,
}, 5000).animate({
    scrollLeft: $(".saar").offset().left,
}, 5000).animate({
     scrollLeft: $(".anna").offset().left,
}, 5000).animate({
     scrollLeft: $(".friends1").offset().left,
}, 5000).animate({
     scrollLeft: $(".quote").offset().left,
}, 5000);
});


Check if a string contains a set of characters

Using regex for this is overkill, but so is sorting both strings. I'd just do:

def find_chars(subject, characters)
  characters.chars.all? { |char| subject.include?(char) }
end

Just doing a very cursory benchmarking, but it's an order of magnitude faster, at least for small strings like your example.

Edit: I should point out that this implementation is different from the original in that it doesn't care about multiples of the same character.

The original code will return false if given, say, ruby and rr, since there's only one "r" in the string. The implementation above, however, just matches the first letter twice - or N times, if need be.

Whether this is correct for your use-case, I don't know.

Incidentally, you could consider uniqing the character set to avoid redundant matching, but it'll probably be much slower for all but the most extreme input.

Edit 2: Responding to comments. This isn't very pretty, but should get the job done:

def find_chars(subject, characters)
  letters = characters.chars
  subject.chars.each do |letter|
    i = letters.index(letter)
    next if i.nil?
    letters.delete_at(i)
    return true if letters.empty?
  end
  false
end

Unfortunately, something simple like (characters.chars - subject.chars).empty? won't work as it too deletes duplicates.

In the above, it doesn't actually matter if you loop through the subject and search the characters, or vice-versa. However, it might matter performance-wise. I'd suggest looping over the longer string, and searching the shorter one (which'll get shorter the more stuff gets matched and deleted):

def find_chars(subject, characters)
  letters, repertoire = [subject, characters].sort_by(&:length)
  repertoire.each do |letter|
    i = letters.index(letter)
    next if i.nil?
    letters.delete_at(i)
    return true if letters.empty?
  end
  false
end

Now, I don't know how this fares in terms of performance. You'll have to test it out.

You could also return to sorting the characters string, and do binary search; maybe quicker than index.

By the way, I'd consider monkey-patching this method into String. It'd be nicer to write "hello".covers?("lelo") or something. But whether stand-alone or monkey-patched, find_chars isn't a great name.

Edit 3: The above can also be written as so, though performance is likely similar:

def find_chars(subject, characters)
  letters, repertoire = [subject, characters].sort_by(&:length)
  repertoire.each_char do |letter|
    letters.sub!(letter, '')
    return true if letters.empty?
  end
  false
end

Just for the heck of it, here's another approach. But I doubt it'll be fast:

def find_chars(subject, characters)
  repertoire = subject.chars.group_by { |char| char } # use &:itself for Ruby 2.2+
  letters = characters.chars.group_by { |char| char }

  letters.all? do |char, list|
    repertoire[char] && repertoire[char].count >= list.count
  end
end

It's basically frequency analysis and comparison. Again, it might be worth to pick the shortest of the two strings as the one to loop.


This seems pretty straightforward, so I don't have a ton of critiques.

Naming

PEP8 conventions say your function should probably be named wifi (which is not a great name)

The names filepath1 and filepath2 aren't very helpful.

Input

You're repeating yourself unnecessarily while getting user input.  Furthermore, try to keep your functions pure and handle user input separately.

Magic numbers

It might be cleaner to make "1" and "2" constants.  Even cleaner is to use a dictionary, like I did.

Unused variables

You never use p, so I don't see a reason to assign to it.

Here is my full rewrite of your Python program.  I don't know enough about the batch scripting to comment there.

import subprocess as sub

room_to_batchfile = {
    "1": "Path/To/DeadSpots.bat.ink",
    "2": "Path/To/Regular.bat.ink"
}

def setup_wifi(room):
    sub.Popen(room_to_batchfile[room], shell=True, stdout=sub.PIPE)

if __name__ == '__main__':
    loc = ""
    while loc not in room_to_batchfile:
        loc = input("Please choose your location: 1-Rooms, 2-Rest \n")

    setup_wifi(loc)

Honestly, given the small nature of this it might not even make sense to make it a function.  If you plan on expanding this then it might be worthwhile to implement these changes.


There are some things, which can be improved.

For one, the weave method can be rewritten using itertools, see this SO post for examples.
The idea is to combine elements via iterators (with function similar to zip - see izip_longest), chain and filter out Nones, which were possibly added from missing counterparts.

Then, this pattern:

rows = []
for i in range(len(splits_bestand)):
    rows += [CoordinateRow(splits_bestand[i].split())]

can be replaced with more compact comprehension:

rows = [CoordinateRow(sb.split()) for sb in splits_bestand]

Also, Python list has extend method, which can be used directly in .extend method, like: self.row.extend(row). Similarly for append method. If you will need those at all after using itertools.

Code for previous raw can also be easily rewritten with itertools. Left as an exercise.


When reading

  An alternative (non-OOP) solution would do something like list_of_MOCS = [{'symbol_1':(bars_1,signals_1)},...,{'symbol_N':(bars_N,signals_N)}] so basically a list containing a map with the key being the ticker and value being a tuple of the two dataframes.

I thought, that a better alternative would be:

MOCS = {
    'symbol_1': (bars_1, signals_1),
    'symbol_2': (bars_2, signals_2),
    ...
    'symbol_N': (bars_N, signals_N),
}

Especially given the fact that pd.DataFrame(MOCS) would yield a valid structure.

However, reading at your usage in generate_positions and expected usage in backtest_portfolio; and especially the fact that you will need to explode the data-structure anyway, I would keep the class approach and use collections.namedtuple as largely suggested in the comments. It provides both the advantages of a class (attributes access) and a tuple (immutable + index access).

I would however change generate_positions to create a dictionnary that will hold the structure of the resulting dataframe before building said dataframe. And incorporate that method directly into the constructor as it does not provide much added value on its own:

from collections import namedtuple

MarketOnCloseSecurity = namedtuple('MarketOnCloseSecurity', 'symbol bars signals')

class MarketOnClosePortfolio(Portfolio):
    """Encapsulates the notion of a portfolio of positions based
    on a set of signals as provided by a Strategy.

    Requires:
    market_on_close_securities
    initial_capital - The amount in cash at the start of the portfolio."""

    def __init__(self, market_on_close_securities, initial_capital=100000.0):
        self.market_on_close_securities = market_on_close_securities
        self.initial_capital = float(initial_capital)

        #loop through each MOCS (market_on_close_security) to calculate positions
        securities = {
            security.symbol: 100 * security.signals['signal'] # This strategy buys 100 shares
            for security in market_on_close_securities
        }
        self.positions = pd.DataFrame(securities)

    def backtest_portfolio(self):
        ...

I would also extend the namedtuple to provide extra utilities methods:

class MarketOnCloseSecurity(namedtuple('MarketOnCloseSecurity', 'symbol bars signals')):
    def buy_shares(self, amount):
        return amount * self.signals['signal']

    def close_price(self):
        return self.bars['close_price'].astype(float)

So that you can have more meaningful actions in MarketOnClosePortfolio:

class MarketOnClosePortfolio(Portfolio):
    """Encapsulates the notion of a portfolio of positions based
    on a set of signals as provided by a Strategy.

    Requires:
    market_on_close_securities
    initial_capital - The amount in cash at the start of the portfolio."""

    def __init__(self, market_on_close_securities, initial_capital=100000.0):
        self.market_on_close_securities = market_on_close_securities
        self.initial_capital = float(initial_capital)

        securities = {
            security.symbol: security.buy_shares(100)
            for security in market_on_close_securities
        }
        self.positions = pd.DataFrame(securities)

    def backtest_portfolio(self):
        # use security.close_price() for any security in self.marke_on_close_securities if you need to
        ...


Recursively evaluate neighbors in a two dimensional grid

Avoid unnecessary calculations

It's a trivial performance improvement, but in

        //Check south
        if(y - 1 >= 0)
        {
            if(this.at(x, y - 1).getColor() == color)
                locateNeighbors(x, y - 1, color, matches);
        }

        //Check west
        if(x - 1 >= 0)
        {
            if(this.at(x - 1, y).getColor() == color)
                locateNeighbors(x - 1, y, color, matches);
        }

changing to

        //Check south
        if (y > 0)
        {
            if (this.at(x, y - 1).getColor() == color)
            {
                locateNeighbors(x, y - 1, color, matches);
            }
        }

        //Check west
        if (x > 0)
        {
            if (this.at(x - 1, y).getColor() == color)
            {
                locateNeighbors(x - 1, y, color, matches);
            }
        }

will be faster when the expression is false.  When it's true, it's unlikely to matter, as the compiler should optimize down to just one subtraction.  But when false, no subtractions are needed at all.  Of course, subtractions add a trivial amount of time in boards with just a few hundred squares.

Note:  I also added brackets around the single statement form if statements.  While the compiler is fine with the other syntax, it tends to lead to a coding error that can be hard to diagnose.  For that reason, many programmers always use the block form.

Recursion adds overhead

You could also try rewriting the recursive function iteratively.  Note that there is more state in a function call than you need to save.  The color doesn't change, and it always refers to the same matches Set.  Only the points change.

You don't provide all the code, so I can't test it.  But it would look something like.

        List<Point> candidates = new ArrayList<>();
        candidates.add(new Point(x, y));
        while (!candidates.isEmpty())
        {
            Point p = candidates.remove(candidates.size() - 1);
            if (matches.contains(p))
            {
                continue;
            }
            else
            {
                matches.add(p);
            }

            //Check north
            if (p.getY() + 1 < columns)
            {
                if(at(p.getX(), p.getY() + 1).getColor() == color)
                {
                    candidates.add(new Point (p.getX(), p.getY() + 1));
                }
            }

            //Check east
            if (p.getX() + 1 < rows)
            {
                if(at(p.getX() + 1, p.getY()).getColor() == color)
                {
                    candidates.add(new Point (p.getX() + 1, p.getY());
                }
            }

            //Check south
            if (p.getY() > 0)
            {
                if (at(p.getX(), p.getY() - 1).getColor() == color)
                {
                    candidates.add(new Point (p.getX(), p.getY() - 1);
                }
            }

            //Check west
            if (p.getX() > 0)
            {
                if (at(p.getX() - 1, p.getY()).getColor() == color)
                {
                    candidates.add(new Point (p.getX() - 1, p.getY());
                }
            }
        }

Note however that the compiler may optimize out the suboptimal portions of the original code.  In that case, this may not be faster.

You also should question whether this is the place in the program where optimizations are most helpful.  I would think that removing gems, adding new ones, and redrawing the board would take more time.  Shaving off a few milliseconds here won't help you if you're stuck with extra seconds elsewhere.  As a general rule, you want to finish the program and then find where optimizations would be most useful.

It's unnecessary to write this.at unless there is a conflict.  Simply saying at will almost always work.

Declare as the interface

You define matches as a HashSet.  In Java, it is more common to define objects as interfaces rather than implementations.  So

                HashSet<Point> matches = new HashSet<Point>();

would be written as

                Set<Point> matches = new HashSet<>();

instead.  This allows you to change the implementation quickly in one place without affecting the rest of the program.

Assuming that you are using Java 8, you don't have to write Point twice.  The compiler will figure out the appropriate type for you.


When the called API throws unknown exceptions I don't think that there is other way than catching all exceptions (sometimes Throwables too). +1 Jeroen Vannevel's comment too.

Anyway, a common interface might be able to improve the code a little bit:

public interface Command {

    run() throws Exception;

    String getName();

}

Then, you can have implementations, like WifiSwitcher, and call them one after the other:

final List<String> errors = new ArrayList<String>();
for (final Command command: commands) {
    try {
        command.run();
    } catch (final Exception e) {
        errors.add("Could not perform command: " + command.getName());
        if (BuildConfig.DEBUG) {
            Log.getStackTraceString(e);
        }
    }
}

if (errors.isEmpty()) {
    return true;
}
showErrorNotification(errors);
return false;

(I haven't tested nor compiled the code above.)


You can make the structure of your code a bit more intuitive and obvious by using something akin to a REPL.

Now back when Lisp was the new hot stuff, people would write interactive programs like so: (loop (print (eval (read (..))))), which is executed from inner to outer. We can adapt this structure for general interpreters, something like: print $ evalBF $ parseBF. Now since haskell doesn't like the side-effects that print entails when we're not in a Monad, we can even go so far as to abstract that away:

main :: IO ()
main = do
    -- making a bit of an assumption as to how things are passed in
    (program:arguments) <- getArgs
    let compiled = parse program
    print $ execute compiled $ asStacks arguments

This separates the responsibility of semantics from the responsibility of syntax, which enables us to theoretically define a different syntax for a BrainFlak equivalent language and choose the syntax through a command line switch or so.

So far, so clear.

At this point we want to grab a unified representation of a BF program, that doesn't rely on syntax. Now the esolangs wiki entry you linked specifies exactly these things are called: Monads and Nilads.

Now an OOP programmer would attempt to encapsulate the syntax and the behaviour of these into the same thing, but since we want to keep data and behaviour separate in haskell, it makes more sense to attack this from a different angle.

For that purpose I'd propose the following:

data BfProgram = OneNilad |
    HeightNilad |
    PopNilad |
    ToggleNilad |
    PushMonad BfProgram |
    EvalMonad BfProgram |
    LoopMonad BfProgram |
    ExecuteMonad BfProgram |
    Sequence [BfProgram]

thanks to Zeta for suggesting OneNilad and HeightNilad

This enables us to somewhat cleanly parse a string into a syntax tree like so:

parse :: String -> BfProgram
parse '(':')':cont = Sequence $ OneNilad : (flattenSeq $ parse cont)
parse '[':']':cont = Sequence $ HeightNilad : (flattenSeq $ parse cont)
parse '{':'}':cont = Sequence $ PopNilad : (flattenSeq $ parse cont)
parse '<':'>':cont = Sequence $ ToggleNilad : (flattenSeq $ parse cont)
-- order matters, previous patterns will be matched before these
parse '(':code = Sequence $ (PushMonad $ parse monad) : (flattenSeq $ parse cont)
    where (monad,cont) = divideMonad '(' ')' code
parse '[':code = Sequence $ (EvalMonad $ parse monad) : (flattenSeq $ parse cont)
    where (monad,cont) = divideMonad '[' ']' code
parse '{':code = Sequence $ (LoopMonad $ parse monad) : (flattenSeq $ parse cont)
    where (monad,cont) = divideMonad '{' '}' code
parse '<':code = Sequence $ (ExecuteMonad $ parse monad) : (flattenSeq $ parse cont)
    where (monad,cont) = divideMonad '<' '>' code
parse _ = Sequence []
-- another option would be to throw an error here

Note the similarity to your bf function?

Now this block parses a given syntactically valid BfProgram from a String into an actual Program. To not make it too easy for you, I'll only show you the type-signatures of the helper functions. The divideMonad is the more interesting here (tip, you already have something similar in your code):

divideMonad :: Char -> Char -> String -> (String, String)

and flattenSeq is the following:

flattenSeq :: BfProgram -> [BfProgram]

given this, we can now rewrite bf as execute like so:

execute :: BfProgram -> ([Integer], [Integer], [Integer]) -> ([Integer], [Integer], [Integer])
execute (Sequence []) stacks = stacks
execute (Sequence (x:xs)) stacks = execute (Sequence xs) $ execute x stacks
execute OneNilad (x,y,z) = (x, y, ((pop z+1):rest z))
execute ToggleNilad (x,y,z) = (y,x,z)
execute PopNilad (x,y,z) = ((rest x), y, (topadd z (pop x)))
execute HeightNilad (x,y,z) = (x,y,(topadd z (toInteger (length x))))
-- nilads done, always nice
execute (PushMonad p) (x,y,z) = apply $ execute p (x,y,(0:z))
    where apply (x,y,(h:z)) = ((h:x),y,(topadd z h))
execute (EvalMonad p) (x,y,z) = apply $ execute p (x,y,(0:z))
    where apply (x,y,(h:z)) = (x,y,(topadd z (-h)))
execute (ExecuteMonad p) (x,y,z) = apply $ execute p (x,y,(0:z))
    where apply (x,y,(_:z)) = (x,y,z)
execute (LoopMonad p) stacks = loop p stacks
    where loop p ([],y,z) = ([],y,z)
       loop p (x@(0:_),y,z) = (x,y,z)
       loop p stacks = loop p $ execute p stacks

Written like this we have eliminated the String from execute and thus successfuly separated semantics from syntax (as well as program data from program code)

Now if you compare this with the code you already have, you should notice some striking similarities, and some key differences.

One important difference is that I've opted to use much longer names.
Another one is the use of "local function declarations". That way I eliminate much of -- x is a helper function of y.

Last but not least, I'll recommend considering another step: pop, topadd, and rest are functions that are to be called on BF-stacks. You can clarify their usage by grouping them in a class.

The last thing that remains to say now is: I actually didn't check whether the code I provide here compiles. If you get some compiler errors, please do notify me :)


Haven't tested the code, but the code should be thread safe! All ExecCommandAsync methods are called from within asynchronous functions.


"Function Buffer" to avoid triggering an event handler too frequently

As mentioned in the comments, this is usually called "debouncing."

A simpler and easier-to-use approach would be something like this:

function debounce(fn, delay) {
    var timeout;

    return function () {
        var context = this,
            args = arguments;

        clearTimeout(timeout);
        timeout = setTimeout(function () {
            fn.apply(context, args);
        }, delay || 250);
    };
}

Use case:

$(window).resize(debounce(someFunction, 1000));

With that out of the way, let's review the code.

Broken features

The timeout is never cleared if the function is called multiple times within the delay period. Unless I'm missing something, all this is going to accomplish is delaying the function from running, but it will still run as many times as it is called. This doesn't seem to work "as advertised."

Missing features

Most functions take arguments. Many functions rely on a this binding. These buffered functions don't allow passing arguments or preserve the this binding. These are features you will probably need at some point. Incidentally, with this implementation it would be very difficult to make changes allowing arguments to your buffered functions, because FtnBuff does not have a...

Single responsibility

If you're going to debounce functions, there's no reason you can't debounce them one at a time. Your code incurs a lot of complexity from maintaining a list of functions to call (which also causes problems with passing arguments).

Let's take a step back. If you wanted to have one function handle an event, you'd do this:

addEventListener('resize', someFunction);

If you needed to have two functions handle an event (and didn't want to register them as separate listeners), you might do something like this:

addEventListener('resize', function () {
    someFunction.apply(this, arguments);
    anotherFunction.apply(this, arguments);
});

There's no reason why a debounce function should handle calling a series of functions; that's not its job. Its job is just to debounce. Calling a series of functions is already a core feature of the language; just write a function that calls the other functions and debounce that.

TLDR: Don't try to handle multiple functions, it's too limiting and not necessary.

Typechecking

You may be more familiar with strongly-typed languages; they have built-in type checking. So you think, "hmm, how can I ensure that things are the right type in this dynamically-typed language?" And you end up writing things like if (isFunction(fn)), or if (!isNaN(n)), or whatever.

This is not a road you want to go down. It's going to cause unnecessary code bloat, and it doesn't really solve anything. Imagine passing a non-function or a non-number to one of those functions. If you weren't doing these checks, things would likely fail in some way that would indicate what the problem was. Since you are doing these checks, things won't fail, but nothing useful will happen either. This is arguably worse -- I'd rather have something fail and be able to track down the problem then have nothing happen at all, and get stuck wondering why.

What you could do instead is throw errors when these checks fail. This would be better than what you have now, but again, not really necessary. It's up to you to document your API (think annotations) and it's up to the person using it to use it properly. If they're passing a string in for a delay parameter that's clearly documented as taking a number, that's user error.

TLDR: Don't write twice as much code to handle dumb user errors, document your API instead.


Is there any downside to define a function that use one dictionary as an argument instead of several (+10) arguments?

Well, the answer depends on the meaning of the variables. If they are related (and they should be, since the same functions uses them!), then it's a good idea to group them in a dictionary since it makes the code more readable.

However, even if it makes sense to group all variables into a dict, your env.update() solution is not satisfying because it is unlikely that x and y really belong to env. What have you gained here? Function definitions may be shortened, but you only moved the problem to make it less visible. The next developer will be very surprised to see that you simply replaced function arguments by a dict without thinking about readability. This does not respect the Principle of least astonishment and probably others too.

You should try to group variables that really belong together, make use of *args and **kwargs whenever it makes sense, and otherwise split/reorganize functions that take too much unrelated arguments: they probably break the Single responsibility principe anyway.

Now, be careful when refactoring such functions, make sure you really understand them, and write unit tests or integration tests before changing them to make sure you don't make the code worse than before.


all the ways to fit some pegs into given holes

I recommend against using single letter variable names, in particular your use of p and h.
I think the code is clearer if you use peg and hole.
Your code is going to break if you have multiple holes or pegs of the same size.
You'd be better off using tuples instead of frozensets. You don't appear to be using the set features.

In order to have better code/algorithm you need to look at the problem differently. Right now you are trying to find peg/hole combinations. Instead, you should try to figure out where each peg fits.

You have the pegs: 2, 4, 7

Your goal is to select three of the holes: 1, 3, 4, 6, 9 which fit the pegs.

itertools.permutations(holes, 3)

will produce an iterator over all possible choices of 3 holes from the list. Something like:

1 3 4
1 3 6
1 3 9
1 4 3
...

We interpret each value as an assignment of holes to pegs. So 1,3,4 means (2, 1), (4, 3), (7,4). Of course not all such assignments are valid. So we filter out the invalid ones (i.e. where the pegs don't fit).

As an added bonus, itertools.permutations generates its values in sorted order. Because we only filter the results, the resulting function will also produce its values in sorted order. This removes the neccesity of doing the sorting yourself.

Here is my implementation:

import itertools

def check_fits(pegs, holes):
    for peg, hole in zip(pegs, holes):
        if peg > hole:
            return False
    return True

def fit(pegs, holes):
    assert len(pegs) <= len(holes)
    for selected_holes in itertools.permutations(holes, len(pegs)):
        if check_fits(pegs, selected_holes):
            yield zip(pegs, selected_holes)

pegs = [2, 4, 7]
holes = [1, 3, 4, 6, 9]

for item in fit(pegs, holes):
    print item

itertools.permutations will generate many invalid assignment of pegs to holes. For example, in the example above, it will generate a significant number of assignment which attempt to fit a peg of size 2 into a hole of size 1. A simple recursive function could avoid spending time on so many bad assignments. However, itertools.permutation is written in C, and so probably still has a speed advantage over such a recursive algorithm.


Gathering IDs to find values from objects

If there are zero, one, two or possible more prerequirements, generalize their storage. Do not use multiple properties and nested if-else-statements, but an array and a loop.

The function should then look like this:

function checkPreReq(e) {
    var preReqs = skill[tab][e].preReqs;
    if (!preReqs)
        return true;
    for (var i=0; i<preReqs.length; i++) {
        var preReq = preReqs[i];
        if (skill[tab][preReq].base <= 0)
            // failed at least this preReq
            return false;
    }
    // passed all requirements
    return true;
}


Find maximum difference between values in an array

What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.

Nope.

Consider {5, 2, 1}. The pseudo code returns 5 - 1 = 4 which happens to be the difference between the smallest and the largest value.

Now consider {1, 2, 5}. The pseudo code computes 1 - 2, 1 - 5, 2 - 5 and never updates x because all these values are < 0; the pseudo code then returns x, which is still 0. The difference between the largest and the smallest value, however, is still 5 - 1 = 4.