This program is not bad, for a beginner.  You split the getRandomWord() routine into its own function, which is good.  You should do much more of that, though, as your main() is too long to follow at a glance.

The getRandomWord() function has a serious bug arising from your misuse of Random.nextInt(int n).  Possible outputs from that call are 0, 1, 2, 3, 4.  Therefore, it will never choose "awesome", and it may throw an IllegalStateException.  I don't recommend using a switch statement for that purpose, though, because the vocabulary list should be treated as data, not as code.  It would be better to pick a random element from an array of strings.

You also have a logic bug that lets the user "win" by guessing the same correct letter again and again.  For example, if the word is "fizz", and the user guesses 'z', then you record the fact that there are two blanks remaining.  If the user guesses 'z' again, you report a win.  (You really ought to handle duplicate guesses better, but at the least you should prevent such erroneous wins.)

A block of variable declarations at the top of your main() function is unfriendly — nobody likes reading those.  Instead, declare your variables as close to the point of use as possible.  In fact, within your block of declarations are two unused variables wordLength and solved that you yourself lost track of.

Pick variable names that make sense — not just to you but to any programmer who might come along.  Instead of k (short for "keyboard"?), pick input (and initialize it immediately).  Instead of temp (which isn't temporary, so it must mean "template"?), try wordDisplay.

Suggested implementation

This is mostly just a result of

refactoring your main() code into functions
renaming variables for clarity
writing some loops a bit more eloquently

import java.util.*;

public class HangMan {
    private static final String[] VOCABULARY = new String[] {
        "peace", "nuts", "dankmemes", "fizz", "awesome"
    };

    private static Scanner input = new Scanner(System.in);

    private static void intro() {
        System.out.println("Hey, what's your name?");
        String name = input.nextLine();
        System.out.println(name+ ", hey! This is a hangman game! (Some answers have two words, usually the longer ones)\n");
    }

    /**
     * Picks a word at random from the vocabulary.
     */
    public static String getRandomWord() {
        return VOCABULARY[new Random().nextInt(VOCABULARY.length)];
    }

    /**
     * Makes an array of placeholder characters the same length as the word.
     */
    private static char[] initWordDisplay(String word) {
        char[] wordDisplay = new char[word.length()];
        Arrays.fill(wordDisplay, '*');
        return wordDisplay;
    }

    /**
     * Prompts the user to enter a single-character guess (repeatedly
     * if necessary in case of errors).
     */
    private static char promptGuess() {
        do {
            System.out.print("Enter letter: ");
            String s = input.next();
            if (s.length() == 1)  {
                return s.charAt(0);
            }
            System.out.println("Please enter 1 character");
        } while (true);
    }

    /**
     * Fills wordDisplay with the guess, returning the
     * number of blanks correctly filled as a result.
     */
    private static int fillGuess(String word, char[] wordDisplay, char guess) {
        int foundCount = 0;
        for (int pos = 0; (pos = word.indexOf(guess, pos)) != -1; pos++) {
            if (wordDisplay[pos] != guess) {   // Prevent repeat guess
                wordDisplay[pos] = guess;
                foundCount++;
            }
        }
        return foundCount;
    }

    public static void main(String[] args) {
        intro();

        String word = getRandomWord();
        char[] wordDisplay = initWordDisplay(word);
        int blanksLeft = wordDisplay.length;

        System.out.print("\nWord to date: " + blanksLeft + " letters.");

        for (int attemptsLeft = 10; blanksLeft > 0 && attemptsLeft > 0; attemptsLeft--) {
            System.out.println("\nAttempts left: " + attemptsLeft);
            char guess = promptGuess();
            int foundCount = fillGuess(word, wordDisplay, guess);
            blanksLeft -= foundCount;

            if (foundCount == 0) {
                System.out.println("Sorry, didn't find any matches for " + guess);
            } else {
                System.out.println("Found " + foundCount + " matches for " + guess);
            }
            System.out.println(new String(wordDisplay));
        }

        if (blanksLeft == 0) {
            System.out.println("\n---------------------------");
            System.out.println("You did iiiiiiit!");
        } else {
            System.out.println("\n---------------------------");
            System.out.println("Better luck next time, you didn't get the word!");
            System.out.println("It was \"" + word + "\"");
        }
    }
}


Speed up CSV reading code (vector of doubles)

As per Bobby's comment, Vector is your problem, but not for the reason he says...

Vector is a synchronized class. Each call to any method on Vector will lock the thread, flush all cache lines, and generally waste a lot of time (in a situation where it's usage is in a single thread only).

The fact that you use Vector indicates that you are running some really old code, or you have not properly read the JavaDoc for it.

A secondary performance problem is that each value is being converted to a Double Object. In cases where you have large amounts of data, and where there is a primitive available for you to use, it is always faster to use the primitive (in this case, double instead of Double).

You should also be using the Java7 try-with-resources mechanism for your stream.

My recommendation is to change the signature of your method to return a List... actually, no, my recommendation is to return an array of primitive double[].... if you are interested in speed, this will be a significant improvement:

private static double[] readTXTFileSingle(String csvFileName) throws IOException {
    double[] csvData = new double[4096]; // arbitrary starting size.
    int dcnt = 0;

    try (BufferedReader stream = new BufferedReader(new FileReader(csvFileName))) {
        String line = null;
        while ((line = stream.readLine()) != null) {
            String[] splitted = line.split(",");
            if( ! NumberUtils.isNumber(splitted[0])) {

                continue;
            }

            double dataLine = Double.parseDouble(splitted[0]);
            if (dcnt >= csvData.length) {
                // add 50% to array size.
                csvData = Arrays.copyOf(csvData, dcnt + (dcnt / 2));
            }
            csvData[dcnt++] = dataLine;

        }
    }
    return Arrays.copyOf(csvData, dcnt);
}

Edit:

One other thing, if you want another tweak in performance, use:

String[] splitted = line.split(",", 2);

since you never access more than the first field in the record, you do not need to look for comma's beyond the first comma


Buggy as.
Unusable I made a single change and then could not get it to work (turned out I added an extra space)
Bugs
Any spaces in the wrong spot, and deviations from the simplified equation, any fractions and more will cause the code to throw a variety of errors.
Expectation
When you create a function people that use it have idiomatic expectations. You must attempt to conform at least to common variations on these expectations, and or ensure that your code does not throw errors if the input is not as expected.
One would expect a equation solver to be robust and handle all the standard input variations, like be

invariant to white spaces,
invariant to equation layout (1 * x ^ 2 + 1 * x ^ 2) === ( 2 * x ^ 2)
invariant to form of power (x * x) === (x ^ 2)
invariant to implied constants (x + 0) === (x), (1*x) === (x) and (2*x^2+0*x) === (2*x^2)
invariant to equation form (x + 1) ^ 2 === ((x + 1) * (x + 1)) === (x ^ 2 + 2 * x + 1)
I invariant to implied multiplier (2x === 2 * x) Note the number (or variable) if before x and has no operator, the multiplication * is always implied.

Other problems.
Not all quadratics have solutions.

A quadratic can have zero solutions as it is above of below the x axis. Eg x ^ 2 + 1
A quadratic can have one solution if it just touches the x axis eg x ^ 2
A quadratic can have two solution eg x ^ 2 - 1 * x

Quadratics can also include fractions  1/2 or 0.5. You should also be able to add the equations strings together, two or more 2nd order polynomials added together (joined with a "+" or "-") should equate into a valid quadratic.
Naming
The function naming is rather bad. To name a few examples

getValues maybe parseEquation
getXList mabe solveQuadratic
list maybe coefficients

Constants
You should use const for constants. Some examples...
const [a, b, c] = getValues(equation);

const list = [];

const cSign = equation.split(' * x ')[1].charAt(0);

And most likely more problems but as the code is so hard to use I have not looked any deeper into your algorithm.
Conclusion.
I would say "Try again." as it is not at all what I would expect from a function that solves quadratics.


Concurrent programming with a simple server

If you really are planning on creating a thread for each incoming request just use and Executors.newCachedThreadPool().  As long as the incoming requests arent very often, this ExecutorService will create a new thread when you submit to it, but if a thread is idle and not being used, the service will reuse the thread instead of creating a new one.

Edit: Here is the example using your code.

public class MyServer{

    private static int port = 1234;

    public static void main(String args[]){
        try{
            final ExecutorService service = Executors.newCachedThreadPool();
            ServerSocket serversock=new ServerSocket(port);
            while(true){
                Socket  socket=serversock.accept();
                service.submit(new MyClass(socket));
            }
        }catch(IOException e){}
        }
    }

    class MyClass implements Runnable{

        Socket socket;

        public MyClass(Socket s){socket = s;}

        public void run(){
            try{
                DataInputStream in = new DataInputStream(socket.getInputStream());
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                int x = in.readInt();
                out.write(2*x);
                socket.close();
            }
            catch(IOException e){}
    }
}

With this you have the possibility of thread reuse.


there is no right in wrong in this situation it's a question of what's best for your particular situation if you are going to build many Rest API endpoints it's best to separate them in separate files under routes like this so your code can be more maintainable :

│   ├── routes/
|   |         |___index.js
              |___auth.js
              |___gizmo.js
                          -


You should use with..as to open a file to make sure it is closed again, even if your program is interrupted:

with open('cpdf.pdf', 'rb') as pdfFileObj:
    ...

If your mode was only r, it could be omitted, as it is the default, however since the file is binary, we need 'rb' here.

Building your command can be greatly simplified using format, leaving out the slow string additions:

command = "java -jar pdfbox-app-2.0.2.jar ExtractText cpdf.pdf {0} -startPage {1} -endPage {1}".format(ffi, i)

Pull the command variable out of the loop and make it a constant.

Get rid of the intermediate variable ffi (which is also a very bad variable name).

Choose better variable names, like page, instead of i.

Follow PEP8 for variable names, use lower_case, not camelCase.

Make the file name a variable (allows passing it in via sys.argv or similar at some point).

Use format's awesome features of replacing named place-holders and locals() to get a dictionary of locally defined variables. Use dictionary unpacking (**dict) to connect the two.

If you are using python 2.x (which does not seem to be the case, judging from your print()), use xrange instead of range to avoid building a list with 1000 elements before iterating and build a generator instead.

Final code:

import sys
import PyPDF2
import subprocess

COMMAND = "java -jar pdfbox-app-2.0.2.jar ExtractText {file_name} out\\{page}-extracted.txt -startPage {page} -endPage {page}"

file_name = sys.argv[1] if len(sys.argv) == 2 else "cpdf.pdf"
with open(file_name, "rb") as pdf_file:
    pages = PyPDF2.PdfFileReader(pdf_file).numPages

for page in range(1, pages + 1):
    subprocess.check_output(COMMAND.format(**locals()), shell=True)
    print('Completed {}'.format(page))

Alternatively, saving the pdf_reader.numPage calls to locals():

subprocess.check_output(COMMAND.format(page=page, file_name=file_name), shell=True)

If the code were longer I would put it into a function. In that case COMMAND should be defined inside that function, because local variable lookup is faster than global variable lookup.

With functions:

import sys
import PyPDF2
import subprocess

def run(file_name, page):
    command = "java -jar pdfbox-app-2.0.2.jar ExtractText {file_name} out\\{page}-extracted.txt -startPage {page} -endPage {page}"
    return subprocess.check_output(command.format(page=page, file_name=file_name), shell=True)

def number_of_pages(file_name):
    with open(file_name, "rb") as pdf_file:
        return PyPDF2.PdfFileReader(pdf_file).numPages

if __name__ == "__main__":
    file_name = sys.argv[1] if len(sys.argv) == 2 else "cpdf.pdf"
    pages = number_of_pages(file_name)

    for page in range(1, pages + 1):
        run(file_name, page)
        print('Completed {}'.format(page))

Regarding your timing: It is probably slow because you are repeatedly starting the java program, accumulating initialization times. Maybe you can split the text obtained from the combined command somehow?


Making prime (sieve) code faster and able to run on big numbers

using namespace std;

It won't matter much with this program, but this can be a bad habit to start.  See Why is using namespace std bad practice?

Sieve of Eratosthenes

bool f[100000001];
void siv()

You're asking for a code review, so you want to encourage people to read your code.  You could make it easier on us by picking self-commenting names.  For example, I think these would be more recognizable as

const int MAXIMUM_VALUE = 100000001;
bool is_not_prime[MAXIMUM_VALUE];
void sieve_of_erastothenes()

Now I can easily see what the upper bound is, what is_not_prime holds, and know what the function does.  I can also reuse MAXIMUM_VALUE and if I type it incorrectly, I'll get a compiler error.  If I miscount the zeroes in 100000001, it will just silently do the wrong thing.

for (long long i = 2; i * i <= 100000001; ++i)
{
    if (!f[i])
        for (long long j = i * i; j <= 100000001; j += i)

You do i * i twice.  You could save it the first time and avoid that.

for ( long long i = 2, j = i * i; j < MAXIMUM_VALUE; ++i, j = i * i )
{
    if ( ! f[i] )
    {
        for ( ; j < MAXIMUM_VALUE; j += i )
        {

Not much of an improvement but some.  Although the compiler might do this for you already.

Note that I also changed j <= to j <.  This prevents us from writing past the end of the array.  The array is 0-indexed, so its maximum index is one less than its size.

Even better might be

int *prime_factor_counts = NULL;
void sieve_of_erastothenes(const size_t maximum_value) {
    prime_factor_counts = calloc(maximum_value+1, sizeof(int));

    if ( NULL == prime_factor_counts )
    {
        std::cerr << "Failed to allocate array." << std::endl;
        exit(EXIT_FAILURE):
    }

    prime_factor_counts[1] = 1;
    for ( size_t i = 2; i*i <= maximum_value; ++i )
    {
        if ( ! prime_factor_counts[i] )
        {
            for ( size_t j = i; j <= maximum_value; j += i )
            {
                ++prime_factor_counts[j];
            }
        }
    }
}

Switching from prime_factor_counts[j] = 1 to ++prime_factor_counts[j]; is about the same work but saves additional information.  Now we have a record of the count of the prime factors of each number.  Note that we are doing more work now (since j starts at i rather than i * i), but it's work that we probably needed to do anyway.

I dropped long long in favor of size_t.  The reason is that we can't create an array with more than size_t elements.  So there's no point in creating an index variable of any other type.

In C++, elements are undefined unless you specifically set them.  That was a bug in your original program.  It's fixed here by using calloc which explicitly zero-initializes the memory it allocates.

main

I'm going to simplify main a bit.

int main()
{
    int input_row_count;
    std::cin >> input_row_count;
    std::cout << process_input(input_row_count, 1, 2);
}

This gets most of the logic outside main.  We only get the number of rows of inputs directly.  Everything else comes through the process_input function.

Technically speaking, we should probably check for an input error.  However, if you're willing to live with the consequences of not checking, then I'm not going to insist.

process_input

std::string process_input(int input_remaining_count, int iteration_count, size_t maximum_value)
{
    if ( 0 >= input_remaining_count )
    {
        sieve_of_eratosthenes(maximum_value);
        return;
    }

    size_t start, end, desired_factor_count;
    std::cin << start << end << desired_factor_count;

    if ( maximum_value < end )
    {
        maximum_value = end;
    }

    std::string output = process_input(input_remaining_count - 1, iteration_count + 1, maximum_value);

    size_t count = count_matching_numbers(start, end, desired_factor_count);

    std::ostringstream out;
    out << "Case #" << iteration_count << ": " << count << '\n' << output;

    return out.str();
}

The big point to this is to find the maximum value for which we need a factor count before running the sieve_of_eratosthenes.  This way we don't have to always calculate a large number.

The second point is that this allows us to only calculate factor counts once across the entire input.  The other way, we had to recalculate the factor counts once for each range.  This puts the calculation work entirely in the sieve_of_eratosthenes function which had to do most of it anyway.

The original algorithm was probably better for short ranges with high start and end values.  It also used less space, since it just saved whether or not a number was prime and the prime factors of a particular number.  I don't know if the space increase matters or not given your usage.

count_prime_factors

size_t count_matching_numbers(size_t start, size_t end, size_t desired_factor_count)
{
    size_t count = 0;
    for ( size_t i = start; i < end; i++ )
    {
        if ( prime_factor_counts[i] == desired_factor_count )
        {
            ++count;
        }
    }

    return count;
}

Other issues with original

vector<long long>V;

It's pretty common to use ALL_CAPS to mean a constant.  This is not a constant, so it might be better named prime_factors.

        for(long long q = 1; q <= i; ++q)
        {

But later you say

        if (V[0] == 1)
            V.erase(V.begin());

It would be easier to replace both statements with just

        for ( size_t j = 2; j <= i; ++j )
        {

Now there's no chance of adding 1 to the vector, so you'll never need to remove it.

I'm also unclear on why the variable is named q.  The more common inner loop index variable would be j.

            if(i % q == 0)
            {
                if (!f[q])
                    V.push_back(q);
            }

It may be better if you did the checks in the reverse order.

            if (!f[q])
            {
                if(i % q == 0)
                    V.push_back(q);
            }

Checking if a value is zero should be simpler than checking if the remainder from a division is zero.  Of course, the pointer arithmetic may mess that up.  It may be worth timing both ways.

vector<long long>V;
        V.clear();
                    V.push_back(q);
        if (V.size() == c)
        {
            ++count;
        }

Since you only ever check the size of the vector, you don't actually need it.  You could replace it with just a counter variable:

size_t prime_factor_count;
        prime_factor_count = 0;
                    ++prime_factor_count;
        if ( prime_factor_count == c )
        {
            ++count;
        }

OOP

I didn't try to change things, but instead of making prime_factor_counts a global variable, you could have made it an object variable.  Then both count_matching_numbers and sieve_of_eratosthenes could have been object methods.  You could even make prime_factor_counts and sieve_of_eratosthenes static so as to share them across multiple objects.  As it is, this code is rather procedural.  Why use C++ to write C?


Maximum depth or height of a Binary tree

(I won't comment on the prescribed BinaryTreeNode definition)

API

Both GetMaxTreeDepth and GetMaxHelper can, and arguably should, be static, as they have no logical dependencies. GetMaxTreeDepth should of course be in some way public (i.e. expose an API), and GetMaxHelper should remain private/internal as an implementation detail.

There is little documentation here, and inline documentation (///) of public APIs is invaluable for discoverability and usability. In particular, I'd expect the throw-on-null documented, and a precise statement of the return value (e.g. I might expect that null would return 0, and a tree with only one node and no children return 1, but I'd be wrong). If I was feeling helpful, I might add note clarifying that it is a tree search, and that passing a graph with cycles is not supported (it will eventually crash with a stack-overflow); it is stated that you are processing a binary tree, but the definition you are given is clearly not going to prevent anyone building a graph.

I don't know if it was clarified in the question statement, but throwing on null is a design decision, and isn't something you can assume as an implementer (certainly not without documentation to go with the assumption). This is also not the most helpful exception ever:

throw new ArgumentNullException();

Which argument? Granted there is only one, but this could have bubbled up from an internal method which takes some parameter which is a function of root. Everyone will be happier if you tell them exactly how it was they violated your API's contract:

throw new ArgumentNullException(nameof(root), "Ideally a helpful message here, unless it's just going to state the obvious and create confusion");

Recursion

Recursion is always dodgy*: you don't know where you might end up, and it could well be a stack overflow. As a 'quick and easy' implementation this looks fine (and is easy to understand), but for production code I would consider an iterative solution using an explicit stack, as this can be considerably more space efficient and cope with much deeper trees. A reasonable iterative solution will almost certainly also be faster for larger trees.

GetMaxHelper

I'd break that last line of GetMaxHelper out a bit, making it clearer and easy to read in a narrow window. I'd be inclined to change root to node or something less important sounding also, since root sounds like it should be at depth 0 (or 1?), and these guys are not necessarily so.

int leftDepth = GetMaxHelper(node.Left, depth + 1);
int rightDepth = GetMaxHelper(node.Right, depth + 1);
return Math.Max(leftDepth, rightDepth);

We could probably argue all day about where the depth++ bit should go, so I won't.

Tests

It's good that you are testing boundary conditions, but you really need more comprehensive tests than this (I guess this is where the 15min time-limit shows up). An implementation where you 'forgot' to look down the right-hand branches, or made a C&P error (like I did when writing the above snippet) to the same effect would pass your tests.

Sorry, just noticed that you do use a right-hand branch; it's just that your diagram for GetMaxTreeDepthTest is misleading, only showing left-hand branches (which is obviously not ideal). There is value, however, in having tests which explicitly test different bits of logic (e.g. if you have one which only worries about left-branches, and another which only worried about right-branches, you can single out some class of problems more quickly).

Boring Stuff

The int depth = 0 is clearly redundant, and though that wouldn't bother me, you might consider a named argument or default (= 0) parameter to avoid leaving a variable floating around or to avoid misusing the method by accident. (That said, I seem to spend most of my life regretting using default parameters, so I wouldn't be tempted)

This spacing is inconsistent:

 return Math.Max( GetMaxHelper(root.Right, depth+1),  GetMaxHelper(root.Left, depth+1));

As is this:

Assert.AreEqual(3,result);

* unless it's a tail-call in an explicitly tail-call optimising language, of course


I haven't used PHP recently, just a few, mostly minor notes:

// Encrypt password
$member->Password = sha1($member->Password);

You might want to use a salt here to make your hashing stronger.

$this->getWriteDb()->insert('members', $data);
$id = $this->getWriteDb()->lastInsertId();

If that's possible, insert could return the ID. It would eliminate temporal coupling (users can't call the methods in the wrong order).

(Clean Code by Robert C. Martin, G31: Hidden Temporal Couplings, p302)

'Status' => 0,

0 is a magic number here. What could it mean? A named constants would express the intent.
These comments are rather redundant, the code is clear and says the same:

// Check if username is taken
if ($this->checkIfExists('UserName', $member->UserName)) {
    throw new App_Exception_UserNameExists('This username is already taken.');
}

// Check if email address already registered
if ($this->checkIfExists('EmailAddress', $member->EmailAddress)) {
    throw new App_Exception_EmailAddressExists('This email is already registered.');
}

...

// Get the member from the event
$member = $event->getTarget();

(Clean Code by Robert C. Martin, Redundant Comments, p60)
Btw, are you sure that you need two different type of exceptions here? Wouldn't be the same exception type with different messages enough?
Use private instead of protected if possible:

protected $_data = array(

Should I always use the private access modifier for class fields?; Item 13 of Effective Java 2nd Edition: Minimize the accessibility of classes and members.

class Model_Member extends App_Model_Model

The class name is weird a little bit. Model of a model? App also too generic, something more descriptive would be better.

$member->CreatedOn = date('Y-m-d H:i:s');

Wouldn't be better using DateTime objects here?


Better way to write 'bulky' function in jQuery

It's difficult to really clean it up, since a lot of it is "manual" translation from one piece of markup to another. Different elements, different attributes etc.

However, there's the low-hanging fruit (and golden rule): Don't repeat yourself.

So don't call $(this) over and over. It's just inefficient. Do something like

var source = $(this),
    target = $(".profileDetail");

and then chain off of those, like source.find('h4.name')...

However, a nicer way to do this might be to use a data-source/data-target attributes on the "big" profile elements. For instance

  ...

So in each element data-source is a comma-separated list of the selector to run in the source element, the (optional, defaults to html()) method to call on the result, and the (optional) arguments. Meanwhile, data-target is can be an attribute name, but it's optional and defaults to html()

Then, in the JS, do something like this:

$('ul.teamProfiles li').click(function (event) {
  var selection = $(this),
      destination = $(".profileDetail:first");

  // find and loop through elements with a data-source attribute
  destination.find("[data-source]").each(function () {
    var target = $(this),             // an element in the "big" profile container
        data = (target.data('source') || "").split(/\s*,\s*/), // parse the data-source attribute
        selector = data[0],           // get the selector
        method = data[1] || 'html',   // get the method (defaults to html)
        args = data.slice(2),         // slice off the arguments
        attr = target.data('target'), // get the destination attribute (if any)
        source, content;

    if(!selector) return; // nothing to do
    source = selection.find(selector); // find the source element in the small profile
    content = source[method].apply(source.get(0), args); // call the method with the args
    if(attr) {
      target.attr(attr, content); // set the target's attribute, if that's what's needed
    } else {
      target.html(content); // otherwise, default to inserting the content as html
    }
  });
});

That function is pretty generic (though it won't work for more complex stuff like setting a bunch of css).

The point is, that the mapping of small profile to large profile can be declared entirely in the HTML; the JS doesn't need to change if you add/remove elements.

Haven't tested it, but it should work


It looks fine. A few notes:

1, Use max instead of

$length = count($old) > count($new) ? count($old) : count($new);

2, Consider testing with newlines, tabs and maybe other whitespace characters.

3, http://en.wikipedia.org/wiki/Longest_common_subsequence could be useful if you want a better algorithm.

4, For removing HTML out of the function create a class which does it and delegate the calls to it. For example:

public interface Decorator {

    public function delete($input);

    public function insert($input);

    public function removeUnnecessaryMarkers($input);
}

public class HtmlDecorator {
    public function delete($input) {
        return "{$input}";
    }
    public function insert($input) {
        return "{$input}";
    }
    public function removeUnnecessaryMarkers($input) {
        return str_replace(array(" ", " "), " ", $input);
    }
}

...
if(!isset($new[$i])) {
    $result .= $decorator->delete($old[$i]);
    continue;
}
...

(I haven't tested that this is a valid PHP syntax or not. Feel free to fix it.)


While this is not a thorough code review, here are some things you could improve or should pay attention to:

median2 is dangerous for containers which offer RandomAccessIterators, but aren't contiguous. In particular, ssize_t i1 = &item - &*begin1; invokes undefined behavior if item and begin1 do not belong to the same memory area, which they might if the underlying container is not contiguous (also, sometimes operator& is overwritten, which can cause a lot of problems on its own). To prepare against this, I would advise you to rename RandomAccessIterator[12] to ContiguousRandomAccessIterator[12] or something in that line of wording.
You are probably aware of this already, but your code is not really portable. For one, there is __builtin_unreachable, which is a gcc builtin. Also, ssize_t is a type from unistd.h, which is a posix header and might not be available on non-posix-conformant operating systems (also, you do currently not include this header, which is a bug). ssize_t is easily replaceable by std::ptrdiff_t in most cases, but if you care for that much of correctness, you could also write something like using difference_t = typename std::iterator_traits<RandomAccessIterator1>::difference_type; and use that instead. For __builtin_unreachable(), if the optimization value you get by using it is really that important for you, you should wrap it in some compiler identifying macro. If it is not important (which is probably the case), you could do a variety of things, for example replace it with a throw expression or just return a default value.
Rng[12] is a very confusing template parameter name, at least to me. I would expect it to stand for "random number generator", which is not fitting here. Choosing a different name would likely be beneficial here.
You should consider passing std::pairs instead of separate iterators. This makes clear that one begin- and one end-iterator always belong together, and helps cleaning up the parameters of your functions.
std::vector<float>{1, 2, 3, 4}. Please don't. This code is just ugly. The reason is that 1) you are relying on implicit conversion for all your values (why not write std::vector<float>{1.0f, 2.0f, 3.0f, 4.0f} instead?) and 2) there is no reason here to use float at all. Stick to integer types unless you do something that actually requires floating point features.


The input elements are all siblings of each other, so you can use $.next() to select the next one that appears after the event target.  There is no need to name each input individually.

$(':input').keypress(function() {
    $(this).next(':input').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="1">
<input placeholder="2">
<input placeholder="3">
<input placeholder="4">
<input placeholder="5">


Transparent wrapper class for data structure in Python

Correctness?

I copied your code, and added the following testcase.

if __name__ == "__main__":
    k = ResizableDeque(maxlen=10)
    k.append(12)
    print(k)
    k.maxlen = 10
    k.append(13)
    k += [14]
    print(k)

Expected result:

deque([12], maxlen=10)
deque([12, 13, 14], maxlen=10)

But I got

deque([12], maxlen=10)
deque([12, 14], maxlen=10)

The reason is that you copy over a bunch of items in __init__, but not in the maxlen.setter.

Whitelisting vs blacklisting

In __init__ you copy several items over using a skip_list. Why not explicitly define the items you want to copy over instead?

Actually, why copy at all? Performance would be a proper reason, but then I'd suggest copying just the items that have proven to be necessary to copy (after profiling).


The index is not used at all, therefore you do not need enumerate():

for point in self.points { ... }

(You mentioned in a comment that the index is used somewhere else,
but we can review only the code that is shown in your question.)

let pointButton = UIButton()
pointButton.frame = point.bounds

can be simplified to

let pointButton = UIButton(frame: point.bounds)

and then you could get rid of the intermediate variable:

for point in self.points {
    self.view.addSubview(UIButton(frame: point.bounds))
}

and this looks like the best solution in your case to me.

You could use map() for that purpose:

self.points.map {
    self.view.addSubview(UIButton(frame: $0.bounds))
}

But using map() for its side effects is frowned-upon, see for example
Higher order function: “Cannot invoke 'map' with an argument list of type '((_) -> _)'”,
where an explicit foreach method is offered as an alternative:

extension Array {
    func foreach(function: T -> ()) {
        for elem in self {
            function(elem)
        }
    }
}

which can be used as

self.points.foreach {
    self.view.addSubview(UIButton(frame: $0.bounds))
}


Python implementation of Quicksort using list comprehensions

IMHO you can't really compare in-place quicksort to not-in-place quicksort. While the basic algorithm is the same, the implementation is vastly different, one being in-place (d'uh) and the other being much, much simpler.

Having said that, you could make your code a bit faster and (IMHO) cleaner by a) using wildcard-unpacking to separate the pivot from the rest (no need to slice the list twice), and b) return the list itself if it contains zero or one elements (no need to partition a one-elemented list).

def quicksort(lst):
    if len(lst) <= 1:
        return lst
    else:
        p, *rest = lst
        low  = [x for x in rest if x <= p]
        high = [x for x in rest if x >  p]
        return quicksort(low) + [p] + quicksort(high)

The else is kind of redundant here, but IMHO it's cleaner that way.

However, using the first element of the list as pivot can be problematic if the list is already (partially) sorted, which is not uncommon. In this case, the performance will be much better/more predictable using a randomly chosen pivot (or any other method). This means that we have to partition the list into three parts, though, low, med, and high, otherwise we risk getting infinite recursion in case the list contains two or more copies of the pivot.

def quicksort(lst):
    if len(lst) <= 1:
        return lst
    else:
        p = random.choice(lst)
        low  = [x for x in lst if x <  p]
        med  = [x for x in lst if x == p]
        high = [x for x in lst if x >  p]
        return quicksort(low) + med + quicksort(high)


Is this an efficient/correct way to get largest Prime factor?

Let's consider a few possible ways to speed this up.
Only look for prime factors
First of all, we know that even numbers (other than 2) are all composites, not primes. So, once we check for 2 as a factor, we can ignore all the other even numbers.
if (number % 2 == 0)
    factors.push(2);

for (int i=3; i<limit; i+=2) {
    if (number % i == 0)
        factors.push(i);
}

This will normally approximately double speed in return for minimal effort.
Limit the search for factors
Note that in the loop above, I've specified the upper limit on the loop as limit rather than number. There's a reason for that. If two numbers multiply to give a third number, at least one of the factors must be less than or equal to the square root of the result. If it's a perfect square, then both of those can be the square root of the number. Otherwise, one is smaller than the square root, and the other is larger than the square root.
But we don't have to conduct a long search for the second number--once we know the factor that's smaller than the square root, simple division tells us the other factor.
So, we can search only for factors less than or equal to the square root, and using them, we can directly find the factors that are larger than the square root.
Also note one other point: there can only be (at most) one prime factor larger than the square root.
Consider using a sieve
Taking the two preceding points together, we can see another possibility. In particular, we can start by searching for primes less than or equal to the input number. Then we can test whether the number is divisible by them (and not any composites).
There's a really fast algorithm for finding all the primes up to some limit called the Sieve of Eratosthenes. It doesn't involve doing an division (which is a slow operation for computers). Instead, consider starting with a table of all the numbers up to the limit you care about. Starting from 2, add 2 to your list of primes numbers, then cross off all the multiples of 2. The look for the next number that isn't crossed off (3 in this case). Add it to the list of primes, then cross off all the multiples of 3. Then repeat--look for the next number that isn't crossed off (5), add it to the list of primes, and cross off all of its multiples.
When you've gone through the whole table that way, you have a list of all the prime numbers up to the limit you care about. Then in your original loop turns into something like:
for (int i=0; i<numberOfPrimes; i++)
    if (number % primes[i] == 0)
        factors.push(primes[i]);

Although it's written in C++ rather than JavaScript, I posted some code to implement this algorithm on SO some years ago. Most of the code isn't very specific to C++ though, so converting to JavaScript should be fairly easy.
This may fall within what you're referring to as a "nested algorithm" though--I'm not entirely sure what you mean by that.


C++ split function (equivalent to python string.split())

I would use a const reference here:

static constexpr auto npos = std::string::npos;

// I would do this.
static constexpr auto const& npos = std::string::npos;

No point in duplicating storage.
Also declaring global variables is a frowned upon. Especially if they are in the global namespace. At a minimum these should be inside your own namespace, but preferably they should be inside the function.

Dyslexia strikes.
I read the next part to have std::string not std::string_view.
Prefer to pass parameters (especially those that are not mutated) by const reference. This prevents a copy.

std::vector<std::string> split(std::string_view const& str, std::string_view const& sep = "", std::size_t maxsplit = std::numeric_limits<std::size_t>::max())

                                               ^^^^^^^^                     ^^^^^^^^

I don't like this:

if (auto end = str.find_first_of(whitespace, start); end != npos && splits < maxsplit)

I did find that this is a C++17 extension. But it puts way too much information on one line. Personally I would split this across two lines.

auto end = str.find_first_of(whitespace, start);
if (end != npos && splits < maxsplit)

As a side note splitting the line by white space can be written more simply as:

 std::stringstream  stream(str);
 return std::vector<std::string>(std::istream_iterator<std::string>(stream),
                                 std::istream_iterator<std::string>());


while (currentNode.previous != null) {
                currentNode = currentNode.previous;
            }

            currentNode.previous = nodeToInsert;

You can avoid this iteration if you track the location of the tail element.

            tail.previous = nodeToInsert;
            tail = tail.previous;

Of course, you have to maintain the tail in other places as well.

    private Node<T> tail;

    public void enqueue(T data) {
        Node<T> nodeToInsert = new Node<>(data, null);

        if (isEmpty()) {
            head = nodeToInsert;
        } else {
            tail.previous = nodeToInsert;
        }

        tail = nodeToInsert;
    }

But you no longer have to iterate this way.

Since both branches update tail, I moved that out of the if/else.

I notice that you use this. to specify object fields.  That actually isn't necessary unless there is a conflict with a parameter or local variable.  Of course, if you simply prefer it that way to make it obvious which variables are object fields, you can.

You can also update the tail when you dequeue to an empty queue, but you don't need to do so for functionality.  It does allow the garbage collector to collect the node though.


Assert LinkedHashMap element in jUnit test

One cannot say anything against

assertEquals(failedEvents.size(), 1);
assertEquals(failedEvents.get(0).get("eventId"), "EVENT3");

It is even shorter and more clear.

However your argument of an invariant on the entire collection is valid, though
you should have said so. Better would be to make a reusable assertion:

assertEquals(failedEvents.size(), 1);
assertTrue(failedEventsHaveId(failedEvents, "EVENT3"));

/**
 * Invariant on the failedEvent: the eventId remaining one.
 */
private static boolean failedEventsHaveId(..., String eventId) {
    return ...;
}

If not reusable, then the code is unnecessarily "nice."


Your approach is completely wrong.

There is a difference between escaping and validation

Validation is the act of making sure a piece of input conforms to certain rules (be it logical, or business rules). It should not be used for security. You can't catch all possible edge cases with a blacklist, don't try.

Escaping (or Sanitization) is the act of escaping characters with special meaning and replacing them with another character or a string that will have the meaning of the literal character in the target context (for example, replacing < with &lt; in HTML). Escaping can and should be used for making sure nothing with special meaning enters the target context (HTML, MySQL query, JavaScript, etc).

In your case, the context is a MySQL query, you're trying to prevent SQL injection. The solution to SQL injection is not validation. It's prepared statements. So:

$pdo = //Instantiate PDO connection.
$stmt = $pdo->prepare("INSERT INTO fonts(id) VALUES (:id)");
$stmt->bindValue(":id", "1; DROP TABLE fonts -- "); //Unsafe input
$stmt->execute(); //Will not drop the table. No results will be returned.

With an insert, the entire string 1; DROP TABLE fonts -- will be inserted.

Sometime in the future (when you try to fetch the font from the database), and before you output it into CSS, you'll want to escape the string for this new context. CSS escaping is something that hasn't a native PHP API, but there are probably libraries around.


Repetitive then/catch method on Javascript

As I am not sure on how your Promises work, this is what I can come up with.

To reduce your catch nesting you could make each promise return another promise. This would force you to have a general .then and a general .catch after your updateUser method.

I stubbed a bit of code here:

var updateUser = new Promise(function(resolve, reject) {
  resolve("Promise one");
});

var updateOrCreateAddresses = new Promise(function(resolve, reject) {
  reject("Promise two"); // e.g. replace reject with resolve to see it "pass"
});

var updateOrCreateBalances = new Promise(function(resolve, reject) {
  resolve("Promise three");
});

var success = () => {
    alert("Success");
}

updateUser.then( x => {
    return updateOrCreateAddresses.then(y => {
        return updateOrCreateBalances.then(z => {
            return success;
        })
    })
})
.then(a => a())
.catch(err => alert(err));

What happens there? Each promise is returning another promise. If one promise fails, the promise will return the "error" to it's parent, where on updateUser the promise get's finally caught.


Macro that does some kind of duplicate check

Lowest-Hanging VBA Performance Fruit

You have

With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With

But you only have it in force for part of your Sub. If you move this

With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With

To the very end of your Sub, you should instantly see a big improvement.

In addition, you should set Application.Calculate to xlCalculationManual at the start, and set it back to xlCalculationAutomatic at the end. That's the other big performance drain.

Always Reset anything you disable

Whenever you change an Application.Thing setting, that change will persist as long as Excel remains open. This:

Application.DisplayAlerts = False

is never set back to True. Once your Sub ends, if your user accidentally clicks the close button, Excel will close without prompting them to save their work first. Because alerts are disabled.


Don't use Egyptian style bracing, that is the style more widely accepted by Java, use the more widely accepted C# bracing style.

Your current structure for the if/else statements is not good.  If you have to use braces in the else/elseif statements then you should use bracing everywhere, even on a single operation inside the if statement

like this

BigInteger Pow(BigInteger x,int n)
{
    if(n == 0)
    {
        return 1;
    }
    else if(n % 2 == 0)
    {
        var val = Pow(x,n/2);
        return val * val;
    }
    else
    {
        return x * Pow(x,n-1);
    }
}

Use if statements like this without the else if

BigInteger Pow(BigInteger x,int n)
{
    if(n == 0) return 1;
    if(n % 2 == 0)
    {
        var val = Pow(x,n/2);
        return val * val;
    }
    return x * Pow(x,n-1);
}

You return inside the if statements so there is no need to else anything just if through because if the first one is true then none of the other if statements will be executed.

I needed to change BigInteger to long. BigInteger it still an INT and so is long, for some reason I could not use BigInteger, so in my equations I will use long

Your naming should definitely be better I went with numBase and numPower I don't normally like hungarian style notation like this, but base is kind of reserved and all.

this is what mine looks like

public static long Pow(long numBase, long numPower)
{
    if (numPower == 0)
    {
        return 1;
    }
    if (numPower % 2 == 0)
    {
        var val = Pow(numBase, numPower / 2);
        return val * val;
    }
    return numBase * Pow(numBase, numPower - 1);
}

also I went with a static method inside of a static class so I could just call it willy-nilly whenever I felt like it.  Like this:

Class1.Pow(numBase,numPower);

the only thing with this is that it looks like you are overloading the already created Math.Pow method, you should probably at the least Comment to that effect, and/or create an actual overload for Math.Pow


This method is public but you don't do any validation about the passed in parameters which is a bad idea because your code is giving implementationdetails to a user of that method which he/she doesn't need to know. Assume folderToMove == null  then PathCombine() will throw an ArgumentNullException which is the correct exception, but this is telling a user that you are using System.Path.Combine() which he/she doesn't need to know.

You should better do the validation yourself and throw the expected exception.

Instead of Path.GetFileName() you should use a DirectoryInfo object and read its Name property which you could extract to a separate method to construct the destination foldername like so

    public void MoveFolder(string folderToMove, string destination)
    {
        if (folderToMove == null)
        {
            throw new ArgumentNullException("folderToMove");
        }
        if (destination == null)
        {
            throw new ArgumentNullException("destination");
        }
        if (string.IsNullOrEmpty(folderToMove))
        {
            throw new ArgumentException("The parameter may not be empty", "folderToMove");
        }
        if (string.IsNullOrEmpty(destination))
        {
            throw new ArgumentException("The parameter may not be empty", "destination");
        }

        String destinationFolder = CreateDestinationFolderName(folderToMove, destination);
        Directory.Move(folderToMove, destinationFolder);
    }
    private string CreateDestinationFolderName(string folderToMove, string destination)
    {
        var directoryInfo = new DirectoryInfo(folderToMove);

        return Path.Combine(destination, directoryInfo.Name);
    }


I think you should use aggregation.

It's either:

class Mesh<T> : ITransformable<T>
{
    public Mesh(IGrid<T> grid, ....)
    {
        Grid = grid;
        ......
    }

    public IGrid<T> Grid { get; private set; }
    .....
}

or:

class Transformer<T> : ITransformer<T>
{
    public T Slice(IGrid<T>, int x, int y, int width, int height)
    {
        ...
    }
    ....
}

It's hard to tell which is better without good understanding of your design (which I don't have). But generally I would prefer the second option.

Also, your IGrid implementation looks really weird. You are saying that you want to implement 2D array using 1D array, yet you use T[][] _values; in your implementation. So, what's the point? There is also a System.Windows.Size class, so I don't understand why would you want to use a Point.


Finding the smallest cube for which exactly five permutations of its digits are cube

Change this code:

boolean[] checked = new boolean[999];
Arrays.fill(checked, false);
for (int i = 1; i < 999; i++) {
    if (!checked[i]) {

To this:

boolean[] checked = new boolean[999];
for (int i = 1; i < checked.length; i++) {
    if (!checked[i]) {

The benefits:

boolean[] has all false values by default, no need to fill
Instead of iterating until some number, iterate until the something with a name that is required for the loop to work correctly, in this case checked.length

Other minor things:

The convention for naming variables is camelCase instead of snake_case
Refer to types by interfaces. Instead of ArrayList<int[]> perms =, use List<int[]> perms =
The getPermutations method returns List<int[]>, but you never actually use the int[] values, you immediately convert them to an int using arrayToInt. It seems it would be better if the method returned List<Integer> where the value are already converted into a form that you actually need.


You can eta-reduce blowupCreditCardNumber:

blowupCreditCardNumber = zip [1..]

Using composition, you can also make isCreditCardNumber pointfree:

isCreditCardNumber = (==0) . creditCardReminder . creditCardDouble . blowupCreditCardNumber . reverse

You don't need to optimize numberDoubleToList by special-casing the one-digit case.

numberDoubleToList = map digitToInt . show

The explicit recursion in creditCardDouble can be averted by using library functions that specialize in particular recursive patterns:

creditCardDouble = concatMap foo where
  foo (index, digit) | even index = numberDoubleToList $ (*2) $ digitToInt digit
                     | otherwise = [digitToInt digit]

foo's name makes foo look like a crutch, and that is good, because it is one.

I would inline definitions that are only used once and do not deserve to be in a library:

isCreditCardNumber = (==0) . (`mod` 10) . sum . concatMap foo . zip [1..] . reverse where
  foo (index, digit) | even index = map digitToInt $ show $ (*2) $ digitToInt digit
                     | otherwise = [digitToInt digit]

digitToInt digit is used in both cases of foo, and so can be factored out:

isCreditCardNumber = (==0) . (`mod` 10) . sum . concatMap foo . zip [1..] . reverse where
  foo (index, digit) = bar index $ digitToInt digit
  bar index | even index = map digitToInt . show  . (*2)
            | otherwise = pure

In fact, we don't need to generate the index and pass it to foo if all we do with it is put it into bar later:

isCreditCardNumber = (==0) . (`mod` 10) . sum . concatMap foo . zip (cycle [pure, map digitToInt . show . (*2)]) . reverse where
  foo (doubler, digit) = doubler $ digitToInt digit

foo is almost trivial, lets get rid of it entirely:

isCreditCardNumber = (==0) . (`mod` 10) . sum . concat . zipWith ($) (cycle [pure, map digitToInt . show . (*2)]) . map digitToInt . reverse

map digitToInt . show is pure on single digits, so we can factor it out of that list and then even factor out the (*):

isCreditCardNumber = (==0) . (`mod` 10) . sum . concatMap (map digitToInt . show) . zipWith (*) (cycle [1, 2]) . map digitToInt . reverse

Note that if you know the parity of the length of the credit card number, you can get rid of the reverse.


Clearer Naming Needed

In general, I think your variable naming could be better. I would rename less_token to be called path or something to make it clearer what you're doing here. new_str should be called current_path or curr_path. Moreover, I'd make the function name something more like find_less_program.

C Style

If you're going to be changing the ret parameter, it's idiomatic in C to pass in a pointer to ret and modify that. Either that or remove ret as a parameter and just return an int as an error code. Moreover, whenever I see a break in a while loop, I get a small frown on my face as that's usually a sign of bad control flow. See below for (IMO) a better control flow.

Moreover, it's been over a decade since C99 came out and introduced us to the bool type definitions. Prefer using them over the standard int way of signaling true or false. You'll need to include stdbool.h to use bool.

I would also create a small constant buffer containing the name of the program we're looking for (in this case "/less".) This prevents you from having to write "/less" all over the place and instead just use a variable name. There's no need to assign the first character of the allocated buffer to NULL in this case. Just call strcpy to copy the string name into the buffer instead of relying on strcat. This also makes your intent clearer as you're first copying an existing string into a buffer and then appending to it.

Here's a possible implementation taking together all of the above suggestions:

bool find_less_program(char *path) {

    bool found = false;
    char *curr_path;
    const char program[] = "/less";

    while (path && !found) {
        if ((curr_path = malloc(strlen(path) + sizeof(program))) != NULL) {

            strcpy(curr_path, path);
            strcat(curr_path, program);
            if (file_exist(curr_path)) {
                found = true; // we found the program
            }
            free(curr_path);
            path = strtok(NULL, ":");
        } else {
            fprintf(stderr, "malloc failed!\n");
            return false;
        }
    }
    return found;
}


Coordinating camera stage movement and data readout

Since what matters here is the ordering of the operations, not what the operations mean, I'm going to use these abbreviations:

A - MoveStageAsync
B - WaitForMotionEnd
C - ExposeTile
D - WaitForReadout

(I'm trying to explain how I got my version using these abbreviations, if you find them confusing, skip to the code.)

So with 3 iterations, your code is doing this: ABCADBCADBCD, and the naive, slow version you optimized from did this: ABCDABCDABCD.  If we wrap parentheses around the part that is in the loop body, we can abbreviate what your code is doing as A(BCAD)BCD and the unoptimized version as (ABCD).  Assuming that we have to keep the same order as what your code is currently doing, we can shift what's in the body of the loop slightly to get AB(CADB)CD and ABC(ADBC)D.  There isn't a way to shift the loop all the way to the beginning or end and do things in the same order you're currently doing them in.

If we try to find an ordering that lets us just toss the whole thing in a loop (like (ABCD), only efficient), we have to move to the first location first (nothing else makes sense), we have to wait for the motion to end next (nothing else makes sense, again), then we have to expose before we can wait for the exposure.  So the only way to do it with everything in the loop was the original, slow version.

So we have 3 possibilities: A(BCAD)BCD, AB(CADB)CD, and ABC(ADBC)D.  If we look at what those 3 would mean, I think AB(CADB)CD is the most readable.

Here it is as code:

MoveStageAsync(firstTile.X, firstTile.Y, firstTile.Z);
WaitForMotionEnd();

foreach(var nextTile in tiles.Skip(1))
{
    ExposeTile();

    MoveStageAsync(nextTile.X, nextTile.Y, nextTile.Z);

    WaitForReadout();
    WaitForMotionEnd();
}

ExposeTile();
WaitForReadout();

There are a few nice things about it: the setup and teardown around the loop both make sense as standalone actions, the waits in the loop body are both next to each other, and the loop body as a whole makes sense as a standalone action.  Although the loop index is a tile, it's really a loop over the transitions from one tile to another.


First of all I recommend you to setup a local webserver to test your php code, if you have not done so jet (I assume you haven't tried your code, since your asking if it's going to work).

Secondly you should abandon mysqli for PDO. Read PHP Database Access: Are You Doing It Correctly?

Also, why are you calling the parent's constructor when the user class has no parent (eg. the class does not extend another class)?


You've got way too much code.  You are not using the built-in tools Python provides to solve this problem, making your job much, much harder.

In your check(value) function, you are checking:

if value % 2 == 0:
    # ...
elif value % 2 != 0:
    # ...

If value % 2 == 0 is False, then value % 2 != 0 is guaranteed to be True.  There is no need for the elif ...:; you could simply use an else: clause.

In both cases, you assign amount = int( ... / 2).  Python has built-in integer division operator, //, so these statements could become simply amount = ... // 2.  In the second case, because value is odd, you divide value - 1 by two.  This "subtract 1" is unnecessary.  Using integer division (or dividing and then casting to an integer) will truncate the result to an integer.

Afterwards, in the first case, when value % 2 is zero, you assign value = 0, where as in the second case, when value % 2 is one, you assign value = 1.  You could simply assign value = value % 2.

def check(value):
    amount = value // 2
    value = value % 2
    return value, amount

Or slightly shorter:

def check(value):
    return value % 2, value // 2

Or even better, use the built-in function divmod(a,b) which does the same thing.  But you will have to swap the variables you assign to, because divmod(a,b) returns the result of the division first, and the modulo remainder second:

amount, value = divmod(value, 2)

In your binary_sum(*args) function, you are given a variable number of lists, and you want to take one element from each list, then take the next element from each list, and then take the next element from each list, and so on.  In Python, this is the zip() function.  (Note: "zip" is short for "zipper", not zip-compression.)

for addends in zip(*args):
    # ...

Except we have a wrench in the works; you want to start from the end and work towards the front.  That is hard.  It is easier if each list is reversed(), so starting from the start is starting from what was the end.  We can then zip() those reversed() lists together:

for addends in zip(*map(reversed, args)):
    # ...

Except we have another wrench in the works; the lists aren't all the same length, and zip stops when any of the lists runs out of items.  You need to add 0's at the start, so they are the same length.  Except we've reversed the lists, so we need to add 0's to the end.  That's easy.  We just need itertools.zip_longest(*args, fillvalue=0) to provide the extra 0's.

from itertools import zip_longest

for addends in zip_longest(*map(reversed, args), fillvalue=0):
    # ...

Now addends is first the 1's column digits, then the 2's column digits, then the 4's column digits, and so on.  We can just sum the addends together, along with any carry from the previous column:

digits = []
carry = 0
for addends in zip_longest(*map(reversed, args), fillvalue=0):
    total = sum(addends) + carry
    carry, digit = divmod(total, 2)
    digits.append(digit)

And then, add the carry bits to end once you've run out of columns:

while carry > 0:
    carry, digit = divmod(carry, 2)
    digits.append(digit)

Finally, since we've generated the result in the wrong order, you'll have to reverse it again, so the most significant digit is first.

from itertools import zip_longest

def binary_sum(*args):
    digits = []

    carry = 0
    for addends in zip_longest(*map(reversed, args), fillvalue=0):
        total = sum(addends) + carry
        carry, digit = divmod(total, 2)
        digits.append(digit)

    while carry > 0:
        carry, digit = divmod(carry, 2)
        digits.append(digit)

    return digits[::-1]

A few tests:

>>> binary_sum([1,1,1,0])
[1, 1, 1, 0]
>>> binary_sum([1,1,1,0], [1,0])
[1, 0, 0, 0, 0]
>>> binary_sum([1,1,1,1], [1])
[1, 0, 0, 0, 0]
>>> binary_sum([1,1,1,1], [0,0,0,1])
[1, 0, 0, 0, 0]
>>> binary_sum([1,1,1,1], [1,0,0,0])
[1, 0, 1, 1, 1]
>>> binary_sum([1], [1], [1], [1], [1])
[1, 0, 1]


Android "ServiceListener" class for listening web services

You may consider abstracting the idea of an HttpService that provides capabilities to make remote endpoint invocations via http.

interface HtppService {
   <T> T get(URI endpoint, Class<T> responseType);
   <T> T put(URI endpoint, Object body, Class<T> responseType);
   <T> T post(URI endpoint, Object body, Class<T> responseType);
   ///...
}

The advantages are:

You encapsulate the reusable logic of making http remote calls, since many of your services will want to do this over and over.
Your remote services no longer need to worry about how to make remote calls, they will be provided with your own HttpService implementation for that matter. Then you can focus on the important business data.
Your implementations can vary, and today you can have one using OkHttp but tomorrow you might just as well use something like, e.g. Spring RestTemplate.
Also you totally encapsulate and control your dependencies of third-party libraries. In this case, your dependency with OkHttp won't be all over the place, but only in the implementation of this interface.

Wit this interface defined you could first work in the implementation of its methods, expecting that all your remote services would use them.

class OkHttpService implements HttpService {

   private final HttpClient httpClient;

   public(HttpClient httClient) {
      this.httpClient = client;
   }

   public <T> get(URI uri, Class<T> respType) {
     //TODO: implement generic get call
   }

  <T> T put(URI endpoint, Object body, Class<T> responseType) {
     //TODO: implement generic put call
   }

   //etc, etc

}

Then you could finally build your remote service. I would start by defining its interface:

interface AirportService {
  Airport[] getAirportsByCity(String city);
}

Then you can provide an implementation of this service that will make remote calls through your HttpService:

class DefaultAirportService implements AirportService {

   private final String host;
   private final HttpService httpService;

   public DefaultAirportService(String host, HttpService httpService) {
      this.host = host;
      this.httpService = httpService;
   }

   public Airport[] getAirportsByCity(String city) {
      URI endpoint = URI.create(String.format("%s/airports?city=%s", host, city));
      try {
          return httpService.get(endpoint, Airport[].class);
      }
      catch(Exception e) {
        throw AirportServiceException("Failed to get airports for " + city, e);
      }
   }
}

There are few advantages here:

First, by passing an HttpService instance as an argument to the constructor you can easily mock that service and test your AirportService implementation in isolation.
Also, the fact that we accept the host name as one of the arguments will help you configure different instances of your service for different environments. For example, in integrations servers you may want the endpoint to point to a test server.
Finally, you can concentrate on your business logic here, and avoid having to worry about Http calls and how to deal with them.

Once you have reached that point, if you want to encapsulate your service in a runnable object, that is going to be quite simple to do:

AirportService airportService = new DefaultAirpotService("http://localhost:8080", myHttpService);

Runnable runService = new Runnable() {
   public void run() {
      aiportService.getAirportsByCity("Miami");
   }
}
new Thread(runService).start();


Regular Expression for parsing PHP annotations containing multiple lines and markup

If you're using it in a PHP code, you are not restricted to using / as the pattern delimiter. Using any other character, such as ~ or % frees you of using \/ everywhere, thereby shortening it.
I don't know what \R is meant to do there, but I think it was supposed to be \r. If so, you do not need it at all.
For the annotation name parameter match, you can just specify that it start with a \w character, followed by a lazy match on [\w\\] character set. Even using [\w\\]+ as the name parameter would not be wrong.
When inside a character set, you absolutely do not need to escape any characters other than the closing square bracket (]) and the exponent (^) if it is the first character. You can move the hyphen (-) to either the beginning or the end. So, the whole value group reduces to

(?P<value>(?:[-/\w\s"<>_#=.'{}:;,*()[\]]*[^*\s/)]))?

PS: You might need to escape at most one of ' or " depending on how you are using the pattern in your code.
In the above, it appears you want to match everything except the next @ character, so; [^@]* would be my next suggestion.
Towards the end of you pattern, you have: (?:\s | $|\)) which could become: (?:\s+|$|\)) or simply (?:\s+|\)) since you would not be needing the anchor at all.
You are not counting on a string like:

@name    (something)

where, you receive name and \s\s\s(something as resulting value (\s is space literal). This can be kept under check by setting \s*\(? instead of (?:\s|\(). This might also not be the intended behaviour from the user, which is why I kept this suggestion at the end.

[*\s]* # multiple space or asterisk characters
@ # followed by the @ sign which
(?P<name>[\w\\]+) # has a string of \w or \ characters following it
\s*\(? # separated by spaces and maybe opening parenthesis
  (?P<value> # store the value attached to the named annotation
    (?:
      [^@]* # value is made of enlisted characters
      [^*\s/)] # but does not end with
    )
  )? # the value is optional parameter
(?:\s|$|\)) # succeded by one of these


JavaScript code to add buttons and slowly remove them

Naming.
Use a consistent and idiomatic naming style. Most important is consistency within the code base.
JS
For JS use cammelCase for all names appart from object that are instanciated with the new token, in that case use PascalCase. For constants you can use UPPER_CASE_SNAKE but as objects and arrays are often declared as constants you can end up with a lot of UPPER_CASE_SNAKE in the code, which does not read well.
There seams to be no general agreement as to what style to use. I personally only use UPPER_CASE_SNAKE for constants that are basic types (Number, Bool, String, etc..) and for object properties that are not writable.
CSS
Currently your CSS naming is inconsistent. This will make it harder to write good code as you will be spending mental energy remembering what style you used for what name, eg you have the two classes named button_slow_remove and slow-fade you remember the name not the hyphen or underscore, later you come back to the project and you will forever be checking "Was that name underscore or hyphen"
For CSS you can use Block Element Modifier (BEM) naming convention. The link provided a good introduction with plenty of resources to get you started.
Note BEM is but one of many and there is nothing wrong with defining your own, as long as you are consistent.
Plurals
Names give hints to a variables content. We pluralize arrays, lists, sets, etc (sometimes even strings if we are using them as an array of characters), and use the singular for single items.
You are using let add_btns = document.querySelector('.button_add'); and someone, even you coming back later will automatically think buttons (an array / array like), its a buton, use the singular const addBtn = document.querySelector('.button_add');
Also it is ok to use common abbreviations, btn is just as good a name as button
Always BE CONSISTENT!

Code Style

NEVER start a line with a ( unless it is part of a multi line statement or expression. You have (function () { If someone adds a line above this and is one of those crazzy people that say they don't need to terminate lines

Eg
var a = 0
var b = a  // << this line is exterminated

 (function() {  // << will parse as var b = a(function() { and throw an error

So play it safe and add the ; for those that don't.
var a = 0
var b = a  // << this line is un-terminated

;(function() {  // the ; terminates any multi line statement or expressions

// while at you can use the shorter form

;(()=>{
    ...code
})()

Use arrow functions to reduce code noise. Code noise is any code that is not needed.

Always declare variables as const, only use var or let if the variable needs to change. The following variables are all incorrectly defined as let yet don't change buttons, add_btns, btn, id, clear_btns, slow_remove_btns

Take care with the indenting.

Reduce code noise. A measure code quality can be defect density, this value is linked to the coder and their experience level. Your defect density will remain consistent (though time will reduce the value), it means more code, more bugs. The easiest way to reduce the number of bugs in your code is to reduce the code size. You have many unneeded lines of code, many due to style.

You have
btn.addEventListener("click", function () {
    let id = this.id;
    alert("my id is: " + id);
});

// less noise
btn.addEventListener("click", (e) => alert("My id is: " + e.target.id));

// or to keep `this`
btn.addEventListener("click", function() { alert("My id is: " + this.id) });

API use

Don't use setAtribute if its not needed. The general rule is setAtribute is only needed for properties that are not part of the DOM's API and needs to be reflected in the markup.

When setting text for an element use the textContent property, ONLY use innerHTML if you are adding HTML

Use an element's id to select it rather than the class name. Using class name forces you to create CSS rules for elements with the same style.

Rather than add the buttons directly to the DOM, which will force a re-flow and slow things down, use a documentFragment, or create an off page container to work with, then when complete add them to the page in one call / one re-flow.

Bugs
You have some bugs in the code.

Your code comments say 40 buttons yet the code generates 41 buttons.

The code at fault is
const BUTTON_NUM = 40;

// ... some code removed

     let i = 0;
    while (i <= BUTTON_NUM) { // from 0 to 40 are 41 steps

    // Should be
    while (i < BUTTON_NUM) {

You are adding id's too often. Inside the while loop you do a for in loop over the buttons you have already created. This means the first button is assigned the same values 41 times.

Testing
You don't write your code for testing, you test code. You have not presented any testing code so there is nothing to review.

Some other points

Keep things simple. You are storing an array of buttons, you are adding events to each fade button. There is no need. Add a single event to the button container, use the event.target argument to get the element clicked on. Don't store elements if you don't need them

Magic numbers and strings are bad. You code has many strings referring to class names all over the place. If you need to make changes, it requires you to make changes in many places, which is a pain and potencial defect.
You started well with const CLS = ["thin", "button"] and  const BUTTON_NUM = 40 but then started mixing in string as needed. Keep all magic values (constants that are subject to design change) in one place, that need only one change to the source.

From the Comments

Try to make it class – zb

NO Don't! JS does not have classes, only objects. class is a syntax used to create objects.
You don't need to create an object, you have correctly encapsulated your code with a singleton, it needs no exposed API (object with properties and functions), and works as a static single instance (It does not need many copies).
OO coding is a complex subject, and most low level coders do not have a good grasp of when and how to use it effectively. Making it a class does not mean it makes it better code.
Rewrite
From the ground up and using an object btns to hold button related consts, and functionality.
To improve portability, or really just make it more flexible I have create functions to cover the common tasks you code was doing. Eg query, addEvent, clickEvent...
I have also deliberately referenced element buttonContainer to show that it is a legitimate way to access elements. But do note that that name is global and not isolated to the singleton.
The layout and CSS have been improvised as you only provided CSS and that had unrelated content.
The code adds 3 events for each of the main ui buttons. The add button adds the buttons to a fragment and then to the page (clearing the previous content beforehand)
Then a final event is added to the button container to manage the alert showing button id.
It is designed to simplify the adding of Remove FX. You need only change 3 lines of JS and that is only data to add a new fade FX. (of course you need to add the HTML and CSS)

;(() => {
    const btns = {
        count : 13,
        className : "buttons buttons--style-default buttons--action-fader",
        text : "Button #", // the # is replaced with the ID
        id : "button#",    // the # is replaced with the ID
        actions : {add : "#addBtn", slowFade : "#slowFadeBtn",clear : "#clearBtn" },
        anim : { slowFade : "buttons--anim-fade", clear : "buttons--anim-clear" },
        animNames : ["slowFade", "clear"],
        reset() {
           btnContainer.innerHTML = "";
           for (const name of btns.animNames) { btnContainer.classList.remove(btns.anim[name]) }
        },
        remove(method) { btnContainer.classList.add(method) },
    };

    const query = query => document.querySelector(query);
    const addEvent = (el, func, type = "click") => el.addEventListener(type, func);
    const clickEvent = event => alert("My id is : " + event.target.id);
    const actionEvent = name => addEvent(query(btns.actions[name]), () => btns.remove(btns.anim[name]));
    const frag = document.createDocumentFragment();

    addEvent(query(btns.actions.add), () => {
        btns.reset();
        for (let i = 0; i < btns.count; i ++) {
            frag.appendChild( Object.assign( document.createElement("button"), {
                    id : btns.text.replace("#", i),
                    className : btns.className,
                    textContent : btns.text.replace("#", i),
                })
            );
        }
        btnContainer.appendChild(frag);
    });
    addEvent(btnContainer, clickEvent);
    btns.animNames.forEach(actionEvent);
}) ();
.buttons {
    background: transparent;
    align-self: center;
}
.buttons--style-default {
    padding: 0.5rem 0.5rem;
    transition: all .5s ease;
    outline: none;
    color: #41403E;
    cursor: pointer;
    font-size: 1rem;
    box-shadow: 20px 38px 34px -26px rgba(0, 0, 0, 0.2);
    border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
}
.buttons--action-ui {
    align-self: center;
    margin: 0 0.2rem;
}
.buttons--action-fader {
    display: inline-flex;
    margin:  .2rem 0.2rem;
    border: solid 2px #41403E;
}
.buttons--style-default:hover {
    box-shadow: 2px 8px 4px -6px rgba(0, 0, 0, 0.3);
}
/* Animations or animation like rules for buttons */
.buttons--anim-clear {
    display: none!important;
}
.buttons--anim-fade {
    opacity: 0;
    transition: opacity 4s linear;
}

    <button id="addBtn" class="buttons buttons--style-default buttons--action-ui" >Add buttons</button>
    <button id="clearBtn" class="buttons buttons--style-default buttons--action-ui" >Remove buttons</button>
    <button id="slowFadeBtn" class="buttons buttons--style-default buttons--action-ui" >Remove with fade</button>


Part 2: Create or update record via HTTP request

You haven't used this:
IGNORE_RULES

in your call to setValue.
Also, you have a double call to close; delete the first one.
resp does not benefit from being pre-initialized to an empty string; you can delete that line.
The only other thing I see is that this:
params = [
    param for param in request.getQueryParams()
    if param.startswith('f_')
]
paramdict = {
    p[2:]: request.getQueryParam(p)
    for p in params
}

can be condensed to only the dictionary comprehension:
paramdict = {
    p[2:]: request.getQueryParam(p)
    for p in request.getQueryParams()
    if p.startswith('f_')
}


This is a giant mess! Here's what you should do to start cleaning it up.

Code organization

Everything you are doing is quite repetitive with minimal variations. Start by constructing an array of each section number you need to inspect for title and each section number you need to inspect by guid. You can then iterate through these systematically without writing everything out.
Turn these two strings into constants you define at the top of your file '%3Flang%3Dnl&HndJk7Sd'  and '&HndJk7Sd'. SImilarly does $movie->title() return the same value each time you call it? If so, move this value into a constant too.
I would then do a loop of a kind like this (pseudocode):

for each filename in possible files{
 video = simplexml_load_file(filename)
 if(video->Video && video->Video!='') {
     echo 'Exists'
     gracefully exit script?
}
//If script has not exited file doesn't exist
echo 'New';

Note that this general organization means you stop as soon as you find a file. The way you have set up your code now, you load all directories but you might have actually found the video in the very first place you checked.

PHP language features

Any reason the standard function file_exists() isn't applicable in some way? Not sure why you seem to have all these special functions just to check if a file exists?


What constitutes an effect and what constitutes a side-effect may be a matter of framing expectations.  The real problem, I think, is that the function name fails to convey what it actually does.  A more appropriate name might be something like pinProductsInBackgroundWithCoordinates(), because:

"check if objects have coordinates" only vaguely describes what this function is doing.  What if it does have coordinates — then what?  And if it doesn't, then what?
If the query succeeds, then wouldn't all of the objects end up having coordinates?
It looks like .pinInBackground() is going to be called for all of the objects.

If you take my naming suggestion, then pinning products is the effect, and ensuring that they all have coordinates is the side-effect.  That's much better than checkIfObjectsHaveCoordinates(), in which case both actions would be considered side-effects.

I'm not quite comfortable with the error handling.  I think that rearranging it would clarify both branches of the conditional.

if error != nil {
    print(error)
} else if objects != nil {
    for object in objects! {
        …
    }
}


Chess programming algorithm minimax to Alpha Beta

A couple of things on top of what @tim already covered.

Use Random.nextInt instead of Math.random

Instead of this:

position = (int)((multiple.size() - 1) * Math.random() + 1);

you can write much simpler like this:

position = 1 + random.nextInt(multiple.size() - 1);

where random is an instance of Random, created for example in the constructor. Simpler isn't it?

Use interface types instead of implementations

Instead of:

    ArrayList<int[]> values = new ArrayList<int[]>();

This would be better:

    List<int[]> values = new ArrayList<int[]>();

(but not quite good enough, see the next item)

Define Abstract Data Types for your problem domain

An Abstract Data Type (ADT) is essentially a collection of data and  operations on that data.
In object oriented languages an ADT is usually modeled with a class,
where data is represented by member fields and the operations are represented by methods.

When I look at that ArrayList<int[]> in the previous point,
I've no idea what it stands for,
what kind of logical object it represents,
and what the numbers in new int[]{-2000, 0, 0, 0, 0} and the other array initializations scattered in the code mean.

If you have defined an ADT for this,
the code would become all the more readable.
Instead of new ArrayList<int[]>,
there might be new MinimaxValueSet().
Instead of values.add(new int[]{-2000, 0, 0, 0, 0}),
there might be valueSet.addNewSetWithScore(-2000),
where this helper method would fill in the repetitive zeros.

Don't print to the console

I suppose the println here was added for debugging:

public int getDepth() {
        System.out.println(depth);
        return depth;

It doesn't belong there and should be removed.
(I suggest to remove debugging code before pasting for code review,
it's just noise for reviewers.)


Code for calculating number of variations

Similar to the other question, I would suggest to utilize a std::map changing your loadTestCases accordingly

std::map<int, int>loadTestCases(int N){
    std::map<int, int> testCases;
    int TestCase;
    for (int i = 0; i < N; i++)
    {
        std::cin >> TestCase;
        auto inserted = testCases.emplace(TestCase, 1);
        if(!inserted.second) {
            testCases.at(TestCase)++;
        }
    }
    return testCases;
}

The advantage of this approach is, that you only have to traverse the keys of the std::map once and can multiply the values if there is a match.

Also given that your container is sorted you can actually skip the std::abs call, as a_i - a_j > 0 is guaranteed by that sort, if you traverse the container from the back. Also more importantly, once you find a_i - a_l > k, you automatically know, that any following pair is also valid, as by construction for an a_m < a_l we get a_i - a_m = a_i - a_l - (a_m - a_l), with (a_m - a_l) < 0.


Javascript to show folder and files by calling Web Api

Prefer modern syntax You're using a few ES2015+ features already, including async/await. If you're going to write a script containing modern syntax (which you should - it can make code much easier to read and write), best to use it everywhere. In particular:

Use const (or let when you need to reassign) instead of var. var has too many problems to be worth using nowadays, such as an unintuitive function scope (instead of block scope), hoisting, and implicitly creating properties on the global object when on the top level. (Use the no-var linting rule.)

In ES2015+, iterators are available. Utilizing these can make code significantly more concise. For example:
const myfolder = document.getElementsByClassName("folder");
[...myfolder].forEach(function(element) {

can be
for (const element of document.querySelectorAll('.folder')) {

jQuery or not? You're using a bit of jQuery, and a lot of vanilla JS DOM manipulation. This is odd, stylistically. One would usually expect, if jQuery is used, for it to be used everywhere that it can be, at least regarding the DOM. But jQuery doesn't really provide anything that can't be done just as easily in vanilla JS, so you could remove jQuery as a dependency entirely too, if you wished. (That's what I'd choose, but it's up to you.)
Attributes 2 things:

When you want to assign to a data- attribute, consider using dataset instead of the more verbose setAttribute:
li.setAttribute('data-id', data.filePathId);

can be
li.dataset.id =  data.filePathId;

Classes can be also be set with dot notation, with className:
li.setAttribute('class', "folder");

can be
li.className = 'folder';

Avoid direct insertion of HTML markup You have:
$("div.message").text(message);

That's a good way to do things - assign text to the text content of an element. But elsewhere, you have
li.innerHTML = data.folderName

That can result in arbitrary code execution. It can also result in formatting problems relating to HTML entities. It sounds very likely that you're expecting folderName to only contain a plain non-HTML string, in which case you should set only the text of the <li>:
li.textContent = data.folderName;

Even though the folder name from the API response is almost certainly trustworthy, using textContent instead of innerHTML is a good habit to get into.
Semicolons Sometimes you're using semicolons when they're needed, and sometimes you aren't. To be stylistically consistent, best to choose one style - either use them wherever appropriate, or don't use them at all. Note that if you don't use them at all, unless you're an expert, you may well eventually run into problems due to Automatic Semicolon Insertion. (I'd recommend using semicolons.) To enforce a particular style on your code, use a linter.
fetchFolder and fetchFiles errors If either the fetchFolder or fetchFiles request fails, there are 2 problems:

You don't return or throw if the response is not OK. As a result, the await response.json(); will throw. The control flow is odd.
You show the spinner at the beginning of the request, but if there's an error, the code will never get to the end of the function where the spinner is hidden again.

The two functions also do very similar things - they show the spinner, do a fetch, and on error, show an error element to the user. Make things more DRY by creating a wrapper function around them.
Or, you could also consider using Promise.all - wait for both requests to complete before updating the UI, to make things look more natural to the user.
const fetchPath = (path) => {
    const response = await fetch(`https://localhost:44371/api/${path}`);
    if (!response.ok) {
        throw new Error(response.status);
    }
    return response.json();
};
const fetchFolderAndFiles = (id) => {
    const spinner = document.getElementById('spinner');
    spinner.style.display = 'block';
    divFolder.textContent = '';
    await Promise.all([
        fetchPath(`files/${id}`),
        fetchPath(`folder/${id}`),
    ])
        .then(([files, folders]) => {
            showFiles(files);
            showFolders(folders);
        })
        .catch((error) => {
            const message = `An error has occured: ${error.message}`;
            const messageElm = document.querySelector('div.message');
            messageElm.textContent = message;
            messageElm.className = 'message alert alert-warning';
        })
        .finally(() => {
            spinner.style.display = 'block';
        });
};

Don't check array length before iterating There's no need for
if (folders.length > 0) {
    folders.forEach((data) => {

If the array is empty, no iterations will occur anyway. Surrounding the forEach in another if statement increases indentation unnecessarily and makes more unnecessary cognitive overhead.
Duplicate listener bug Every time fetchFolder is called, you also call createFolderEventListener, which does:
const myfolder = document.getElementsByClassName("folder");
[...myfolder].forEach(function (element) {
    element.addEventListener("click", function () {

So every time a folder is clicked, you're adding additional listeners to every folder element on the page. This will result in many unnecessary requests, and possibly more strange behavior.
Only add a listener to a folder if the folder doesn't already have a listener. Or, even better, add only a single listener, to a parent element, and utilize event delegation:
document.addEventListener('click', (e) => {
    if (!e.target.matches('.folder')) {
        return;
    }
    const { id } = e.target.dataset;
    fetchFolder(
        fetchFiles(id);
    );
});

Run that once, on pageload, and then you can remove createFolderEventListener.
Do the same thing for createFileEventListener, which has the same problem.
Precise variable names You have:
var divFiles = document.getElementById("files");

and
function createFileEventListener() {
  const myfolder = document.getElementsByClassName("file");

(createFileEventListener should probably be removed entirely, but if it isn't, make sure to change myfolder to myfile)
Precise variable names make code easier to read and helps prevent bugs. A variable name should probably only be plural if it refers to a collection. Otherwise, it should be singular. Similarly, a collection should have a plural variable name. Maybe call it filesContainer instead of divFiles, and fileDivs instead of myfolder.


Anatomy of a string-reversal program with less coupling

When you're passing a buffer around, you should always pass the size of the buffer (or the desired size of the buffer) as well. Your get_buffer() function that creates a buffer should return both the buffer and the buffer's size (either in a struct or as separate parameters), so that the caller of the function knows how much data is safe to put in it. (Yes, you've got that global constant, but what if you move to a paradigm where the allocator can allocate different-sized buffers?)
When you're using a buffer to hold a variable-length string,, you should pass the string length around as well, so you don't have to repeatedly call strlen(). Again you'll need to create a new struct or use separate parameters. fgets() returns the size of the string. Since fgets() doesn't return the length of the string, you do have to do a single strlen() (and you should, to make sure that you got the whole string ending with the newline).
I don't understand why you have a function that creates a buffer, but no function that destroy a buffer. Symmetric structure is good. The current setup locks you in to using malloc() and free(). If you wanted to switch to another memory allocation method, there's no simple way to do it.


Find all subsets of an int array whose sums equal a given target

There are three reasonable responses here:

yes, your recursion code can be improved for performance.
yes, part of that improvement can come from sorting the data.
yes, there's a way to refactor the code to not use recursion, and it may even be faster.

Bearing that in mind, this answer becomes 'complicated'.

Basic performance improvements for current code:

if (sumInStack == TARGET_SUM) {
    print(stack);
}

can easily be:

if (sumInStack >= TARGET_SUM) {
    if (sumInStack == TARGET_SUM) {
        print(stack);
    }
    // there is no need to continue when we have an answer
    // because nothing we add from here on in will make it
    // add to anything less than what we have...
    return;
}

I dislike any recursive function which rely on external (outside-the-method) values. In your case, the sumInStack is external. This makes the target hard to 'see'.

Additionally, if we do sort the data, there are some benefits we can have, and a way to restructure the recursion to make it do less work (since we can guarantee that all values after a point have certain properties...):

consider the method (assuming sorted data):

public void populateSubset(final int[] data, int fromIndex,
                           final int[] stack, final int stacklen,
                           final int target) {
    if (target == 0) {
        // exact match of our target. Success!
        printResult(Arrays.copyOf(stack, stacklen));
        return;
    }

    while (fromIndex < data.length && data[fromIndex] > target) {
        // take advantage of sorted data.
        // we can skip all values that are too large.
        fromIndex++;
    }

    while (fromIndex < data.length && data[fromIndex] <= target) {
        // stop looping when we run out of data, or when we overflow our target.
        stack[stacklen] = data[fromIndex];
        populateSubset(data, fromIndex + 1, stack, stacklen + 1, target - data[fromIndex]);
        fromIndex++;
    }
}

You would call this function with:

Arrays.sort(data);
populateSubSet(data, 0, new int[data.length], 0, 15);

So, that is 'can the code be improved?' and 'will sorting help'

As for the 'unrolled' (no recursion) version of the system, it can be done. It would require three int[] arrays:

int[] data = {....}
int[] sum = new int[data.length];
int[] indices = new int[data.length];
int depth = 0;
int lastindex = -1;

The sum gives and indices act like a stack, and the depth is how deep the stack is (again, assume sorted data):

Arrays.sort(data);
while (depth >= 0) {
    lastindex++;
    if (lastindex == data.length) {
        // we have run out of data.
        do {
            // walk up the stack till we find some data.
            depth--;
        while (depth >= 0 && (lastindex = indices[depth] + 1) < data.length);
    }
    if (depth >= 0) {
         .....
         you then add your code in here to check the target,
         keep it updated in your 'stack'.
         go down a level and move on....
    }

}


Regarding your questions:

No idea :-)
Yes, you should be more specific. The easiest way to find out what exception it could raise is to run it without the guard and give it an address you know does not exist (I'm pretty sure the address "abdjdiehdbdocoegrvdkdoc" does not exist, for example). Note that you can catch multiple exceptions at once with except (Exception1, Exception2): (the parentheses are required) or with multiple except blocks (if you need to do different things, depending on the exception type).
Yes, your current if lat == 0 and lon == 0 approach does not scale to additional lookup services. It is also currently slightly broken, since you always use Google (you use the function before the check). You could iterate through a list of lookup functions until you find one that returns valid coordinates:

LOOKUP_FUNCS = get_lat_lon, google_lat_lon

def find_coordinates(address, lookup_funcs=LOOKUP_FUNCS):
    for function in lookup_funcs:
        lat, lon = function(address)
        if (lat, lon) != (None, None):
            return lat, lon
    return None, None

Note that I assume here that the functions return None, None, instead of 0, 0, which is arguably a better value for something non-existing. Theoretically, some address could actually be at 0, 0. Note also that csv.writer translates None to "", when writing to a file (see the documentation).

A main that does as much as yours is fine, IMO, if this is the only thing this script does. But you might still want to rename it to add_lat_lon(in_file, out_file) or something like this, to be able to import the actual functionality in some other script.In your new main block (or directly under the if __name__ == '__main__': guard), you could then call that function.
It is perfectly fine to return tuples.

Some additional notes:

You should add docstrings to your functions to document what they do.
csv.writer has a writerows method that allows you to directly pass a list of rows. So you can just do writer.writerows(info).
Instead of print(addr[:len(addr)-1]) you can just do print(addr[:-1])


You can use the Dobinski formula for calculating Bell numbers more efficiently.

Dobinski's formula is basically something like this line, although the actual implementation is a bit more complicated (this function neither returns precise value nor is efficient, see this blogpost for more on this):

import math
ITERATIONS = 1000
def bell_number(N):
    return (1/math.e) * sum([(k**N)/(math.factorial(k)) for k in range(ITERATIONS)])

E.g. you can use the mpmath package to calculate the nth Bell number using this formula:

from mpmath import *
mp.dps = 30
print bell(100)

You can check the implementation here