This is a nice first project. Since you are a beginner in C++, I'm not going to worry about the using namespace std and a couple other details.

Naming

Your functions follow an inconsistent naming style and are not spelled correctly:

int pluss(int num1, int num2);

int Minus(int num1, int num2);

int devide(double num1, double num2);

int multiply(double num1, double num2);

These would be better named

int plus(int num1, int num2);

int minus(int num1, int num2);

int divide(double num1, double num2);

int multiply(double num1, double num2);

Consider using void functions

Your functions all return an int. It's not very clear what the return value would mean, so I was puzzled over that for a bit, but then I noticed that they all returned 0:

int pluss(int num1, int num2)
{
    ...
    return 0;
}

It seems that you are copying the idea of int main(), where main returns an error code if something went wrong, but there's no way for something to go wrong in these functions barring an exception, so just make these functions void:

void pluss(int num1, int num2)
{
    int answer = num1 + num2;
    cout << num1 << " + " << num2 << " = " << answer << endl;
    system("pause");
    system("CLS");
}

On the other hand, the names of your functions seem to suggest that they should return the result of the operation, in which case you might do this:

int plus(int num1, int num2)
{
    return num1 + num2;
}

But don't do this. This is simply re-inventing the + operator.

System dependency

Your code uses system() all over the place. system is not cross platform, and it is better to make the code as cross-platform as possible. You really don't need to use system("CLS") everywhere; people using a console don't expect their console to clear old messages. Furthermore, system("pause") isn't necessary; the console waits whenever your program needs to obtain input.

Switch

In your main function, you have this:

if (begin == 1) {
    ...
}
else if (begin == 2) {
    ...
}
else if (begin == 3) {
    ...
}
else if (begin == 4) {
    ...
}
else {
    ...
}

This is basically a switch statement; you could just code that like so:

switch (begin) {
case 1: ...
case 2: ...
case 3: ...
case 4: ...
default: ...
}

Why only add and subtract ints?

If you think it's a good idea to be able to divide and multiply doubles, why not have the same thing for add and subtract? That's definitely something I would expect if I were using your calculator.

Functions should only do "one" thing

Your functions do multiple things:

void multiply(double num1, double num2)
{
    double answer = num1 * num2;
    cout << num1 << " * " << num2 << " = " << answer << endl;
    system("pause");
    system("CLS");
}

Notice how this function is less of a mathematical function, and more of a "perform this task". The task you are having it perform is to "display the result of multiplication, then clear the screen afterwards". That's most definitely multiple things. It would be better to make the function this:

void showMultiply(double num1, double num2)
{
    double answer = num1 * num2;
    cout << num1 << " * " << num2 << " = " << answer << endl;
}

But if you were to do this with all your functions, suddenly they are all almost the same:

void showPlus(double num1, double num2)
{
    double answer = num1 + num2;
    cout << num1 << " + " << num2 << " = " << answer << endl;
}

void showMinus(double num1, double num2)
{
    double answer = num1 - num2;
    cout << num1 << " - " << num2 << " = " << answer << endl;
}

void showMultiply(double num1, double num2)
{
    double answer = num1 * num2;
    cout << num1 << " * " << num2 << " = " << answer << endl;
}

void showDivide(double num1, double num2)
{
    double answer = num1 / num2;
    cout << num1 << " / " << num2 << " = " << answer << endl;
}

We can collapse these down to result in less duplication:

void showCalculation(double num1, double num2, double answer, char operator)
{
    cout << num1 << ' ' << operator << ' ' << num2 << " = " << answer << endl;
}

Now when we use it, it would look like this:

double answer = num1 + num2;
showCalculation(num1, num2, answer, '+');
...

However, since this function is only one line of code, I personally wouldn't use the function.

Code duplication

Notice how each block in the if statements look almost identical:

if (begin == 1) {
    system("CLS");
    int x;
    int y;
    cout << "Give me a first number" << endl;
    cin >> x;
    system("CLS");
    cout << "Give me a second number" << endl;
    cin >> y;
    pluss(x, y);
    return main();
}
else if (begin == 2) {
    system("CLS");
    int x;
    int y;
    cout << "Give me a first number" << endl;
    cin >> x;
    system("CLS");
    cout << "Give me a second number" << endl;
    cin >> y;
    Minus(x, y);
    return main();
}
else if (begin == 3) {
    system("CLS");
    double x;
    double y;
    cout << "Give me a first number" << endl;
    cin >> x;
    system("CLS");
    cout << "Give me a second number" << endl;
    cin >> y;
    devide(x, y);
    return main();
}
else if (begin == 4) {
    system("CLS");
    double x;
    double y;
    cout << "Give me a first number" << endl;
    cin >> x;
    system("CLS");
    cout << "Give me a second number" << endl;
    cin >> y;
    multiply(x, y);
    return main();
}

This is a sign that you should write functions to break it up. This is what I'd do:

double promptForInput(const string &message)
{
    double result;
    cout << message << endl;
    cin >> result;
    return result;
}

...

if (begin == 1) {
    double num1 = promptForInput("Give me the first number");
    double num2 = promptForInput("Give me the second number");
    double result = num1 + num2;
    showCalculation(num1, num2, result, '+');
}
// and so on

Calling main() is undefined behaviour

It is not legal to call main() in your C++ code. You are using this to loop; you should instead learn how to use loops. This is one example of how to do so:

int main()
{
    do {
        int begin;
        cout << "----------------------------------------" << endl;
        cout << "-----Welcome to C++ Based Calculator!---" << endl;
        cout << "-1=Plus--2=Minus--3=devide--4=multiply--" << endl;
        cout << "----------------------------------------" << endl;
        cin >> begin;

        if (begin == 1) {
            ...
        }
        ...
        else {
            break;
        }
    } while (true);

    return 0;
}

Use constants

Since you are using numbers to represent what choice the user made, I strongly recommend you store them as constants:

constexpr int PLUS = 1;
constexpr int MINUS = 2;
constexpr int DIVIDE = 3;
constexpr int MULTIPLY = 4;

Final result

After apply all my recommendations, this is my final result:

#include <string>
#include <iostream>

using namespace std;

double promptForInput(const string &message)
{
    double result;
    cout << message << endl;
    cin >> result;
    return result;
}

constexpr int PLUS = 1;
constexpr int MINUS = 2;
constexpr int DIVIDE = 3;
constexpr int MULTIPLY = 4;

int main()
{
    do {
        int choice; // choice is a better name for this
        cout << "----------------------------------------" << endl;
        cout << "-----Welcome to C++ Based Calculator!---" << endl;
        cout << "-1=Plus--2=Minus--3=Divide--4=Multiply--" << endl;
        cout << "----------------------------------------" << endl;
        cin >> choice;

        double num1 = promptForInput("Give me the first number");
        double num2 = promptForInput("Give me the second number");

        double result;
        char operatorName;

        switch (choice) {
        case PLUS:
            result = num1 + num2;
            operatorName = '+';
            break;
        case MINUS:
            result = num1 - num2;
            operatorName = '-';
            break;
        case DIVIDE:
            result = num1 / num2;
            operatorName = '/';
            break;
        case MULTIPLY:
            result = num1 * num2;
            operatorName = '*';
            break;
        default:
            cout << "Some message thanking the user for using the calculator (optional). " << endl;
            return 0; // to exit main
        }

        cout << num1 << ' ' << operatorName << ' ' << num2 << " = " << result << endl;
    } while (true);
}

Going further

If you wanted to make this "even better", this is how I'd fully implement this:

#include <iostream>
#include <sstream>
#include <string>

void printOptions() {
    std::cout << "------------------------------------------" << std::endl;
    std::cout << "----- Welcome to C++ Based Calculator! ---" << std::endl;
    std::cout << "- Plus:     +                          ---" << std::endl;
    std::cout << "- Minus:    -                          ---" << std::endl;
    std::cout << "- Divide:   /                          ---" << std::endl;
    std::cout << "- Multiply: *                          ---" << std::endl;
    std::cout << "- Quit:     Enter                      ---" << std::endl;
    std::cout << "------------------------------------------" << std::endl;
}

constexpr char QUIT = '\0';

char menu() {
    printOptions();

    std::string input;
    std::getline(std::cin, input);

    if (input.size() != 1) {
        return QUIT;
    }
    return input[0];
}

double promptForInput(const std::string &message) {
    std::cout << message << std::endl;

    double result;
    std::istringstream input;
    do {
        std::string line;
        std::getline(std::cin, line);
        input.str(line);

        input >> result;

        if (!input) {
            std::cout << "Please input a valid number" << std::endl;
        }
    } while (!input);

    return result;
}

double performOperation(double num1, double num2, char choice) {
    switch (choice) {
    case '+': return num1 + num2;
    case '-': return num1 - num2;
    case '*': return num1 * num2;
    case '/': return num1 / num2;
    }
    std::cerr << "Internal Error" << std::endl;
    std::exit(1);
}

int main() {
    do {
        char choice = menu();
        if (choice == QUIT) return 0; // The user wants to quit

        double num1 = promptForInput("Give me the first number");
        double num2 = promptForInput("Give me the second number");

        double result = performOperation(num1, num2, choice);

        std::cout << num1 << ' ' << choice << ' ' << num2 << " = " << result << std::endl;
    } while (true);
}

Here's what I did differently:

I had the user input the actual character for the operation they want to use. This makes my life a little easier, as I can just pass that around. If I didn't want to do this, I'd actually translate the number into the character.
I didn't use the using namespace std;. That statement pollutes your namespace with all the symbols from the standard namespace; there's a reason why the standard namespace is only 3 characters long
I used std::getline to get the input. This makes it so that the user has to input everything on its own line. I liked this idea better.
I moved the switch into its own function; this makes the main function shorter, making it easier to understand.


Certainly, assign a class to each tech icon (I'm assuming they're divs), use a JQuery selector to select all DOM element with the assigned class and then use each() to step through each item.


I don't know the Arduino language but I've recently been learning, from what I can gather on the website unsigned ints will "roll-back" to zero if they reach their maximum (which will be reached in a huge "fifty days" so no need to worry about that.

You can clean up your syntax for your statements by putting the braces at the end  of the statement (on the same line), also remove the byte i from the function visibility into only the loop by declaring it in the for.

I also noticed that your function checkswitch is only used for boolean operations yet it's returning a byte - this can be fixed by returning the result of the comparison of the if you used directly.

Here is my suggestion:

byte key=0;
unsigned int st=millis(),ct=millis(); //st-starttime , ct-currenttime

void setup() {
  delay(5000);            //start prog after 5 sec
  pinMode(7, INPUT);
  pinMode(8, INPUT);
  pinMode(9, INPUT);
  for(byte i=7;i<=9;i++)
    digitalWrite(i, HIGH);    //7,8,9 pins HIGH  for internal pullup
  Serial.begin(9600);
}

void loop() {
  for(byte i=7;i<=9;i++)
    if(isHigh(i)) {      //check which switch was last pressed
      key=i;
      st=millis();
    }

  if(ct>st+200) {                 //triggers only if 200 ms passed to not fill the Serial input
    if(key!=0) {
      Serial.println(key);
      key=0;                       //clear saved key
    }
  }
}

boolean isHigh(byte n) {          //Check button pressed with internal pullup
    return digitalRead(n)==LOW;
}


Performing API calls from a mobile client, reauthorizing the session if necessary

I agree with Ibalazscs that StatePattern makes sense - using a switch to drive changes in behavior is a code smell.

Given that this state machine has only one end state, you could ditch the processConnect boolean, and just check for end state...

ConnectionState state = ConnectionState.checkAnswer;
while(! ConnectionState.endProcess.equals(state) {
  ...
}

You also might want to consider whether ConnectionState should implement an interface to make it extensible.  See Item #34 "Emulate extensible enums with interfaces", Effective Java Second Edition, by Joshua Bloch


In some sense, the question of whether or not to test private methods might be a better fit for Programmers.SE. I'll try to answer, but first a few notes on your code (since this is Code Review):

It seems the tree keeps growing and keeps adding oranges after its death, which doesn't seem quite right (though I'm sure the State of Florida would find it interesting!). A failing test for this could be:

it "stops growing once it's reached its lifespan" do
  age_by_years(15)

  expect {
    orange_tree.age!
  }.to_not change { orange_tree.height }
end

You should probably add a similar one to check that the number of oranges stops increasing too.
You might also ask, if you never pick any oranges, do they just stick around from year to year? I mean, there's ripe and then there's withered on the branch :)
Incidentally, the expect {...}.to change {...} test could be useful in a few places. If you want to check how much a value changed, you can add a by at the end, e.g.

it 'increases age by one when we call age!' do
  expect {
    orange_tree.age!
  }.to change { orange_tree.age }.by 1
end

I'm not a fan of monkey patching Array in this case. While it seems neat to call orange_tree.oranges.pick!, extending a core class to do so is going too far (especially as it's not even new functionality, just an alias). The semantics only make sense as longs as we're talking about an array of oranges, but an array is a generic object that can be used for anything.
You might have an array of OrangeTree objects - does it make sense that you can call orange_trees.pick!? Maybe, yeah, if you got a bunch of oranges back. But this is just a cutesy alias for pop.
I might just add a pick method to OrangeTree instead. Maybe give it an argument to say how many to pick.
The same way you have #dead? as a shortcut for calling #reached_age? with a certain value, I'd add a #fruit_bearing? method that works the same way. I don't know if I'd bother with the #reached_age?method, though, as it's so simple. It's actually shorter to write age >= ...
Your #increase_age_by_one_year, #increase_height_by_two_feet, and #add_three_oranges_to_tree methods are too specific in their naming. Sure, the names are accurate descriptions, but it's like having magic numbers in your method names. What if you decide that it should grow 3 feet per year? Or that the number of oranges to add is derived from the tree's age? Then the method names are no longer appropriate. I'd stick with just #increase_age, #increase_height, and #add_oranges.
As long as the increments are constant, though, it'd probably be good to use, well, constants, rather than hardcoded numbers.
The #add_three_oranges_to_tree method is also sort of redundantly named: What would it add oranges to, if not the tree?
Speaking of, while you can pick oranges, and thus decrease their number, the height can't decrease the same way. So there's no need to keep track of it in an instance variable. Instead, you could just do:

def height
  age * 2 # or, better yet, multiply by a named constant
end

Of course, there's still the question of what happens to the age and height, after the tree's death. You might say that a 100-year-old tree is indeed 100 years old in terms of age - it's just been dead for 85 years. But of course it shouldn't then be 200 feet tall.
Really minor thing, but if you intend for Orange to just be an empty class, you can make the extra clear by writing it in 1 line: class Orange; end
As for your tests: What is #assert_emptiness_when_young doing as a method? It's a test like all the others, not a helper. And you only use it in one place, so I don't see why it's separate. It's also potentially misleading: You create a tree, and call age! once. But what if the fruit-bearing age was 5? Ageing it once would no longer be a good test. I'd simply write:

it "has no oranges when it's young" do
  age_by_years(2)
  expect(orange_tree.oranges).to be_empty
end

Incidentally, it'd be nice to change that #age_by_years method. Age what by years? It'd be simpler to just have a method called tree_aged or tree_with_age that simply returns a tree with the given age.
That would let you simplify many of your tests, like the one above, to just:

  expect(tree_aged(2).oranges).to be_empty

Anyway, back to your questions:

Usually, no, I wouldn't test private methods. Tests are just code, and much like any other code that'll use your class, it shouldn't have to call private methods. That's why they're private. What's important is that the public interface works as expected. And if it does, that indicates that whatever the class is doing in private must work as expected too.

Same as how you don't need to poke around in a car's engine as long as it starts and gets you to your destination just fine.

However, if your tests of the public interface are failing, and you want to go debugging, you might add a test of a private method to help you fix it. Again, the car analogy: If the car doesn't work, your mechanic will want to look around in the engine.

Another case in which you might want to test private methods, is if your public interface is very simple but also very flexible and accepts all sorts of arguments (say, a great big hash of options). Checking every combination of arguments would take forever, and you still might miss some edge cases. But if the private methods each handle just one of those arguments, you can perhaps test those by themselves, and thus be reasonably satisfied that things will work with any combination of arguments. It's not a common situation though, since you'll generally want to avoid such complex "black box" constructions anyway.

So again, there isn't a great need to test private methods. You can mess around with the class' private methods, and re-run the public method tests, and it'll tell you if things work as expect. Because again, if the public interface (which is what other code will be using) works, who cares about how the private methods work? Even if you've used a private method test to help you fix a problem, the real payoff should still be that the public method tests now act as intended. So if anything, you should add a few more of those, and scrap the private one.

Take the proposed test above that verifies that the tree doesn't keep growing after its death. The test is still only using the public #height method/accessor. Since it's failing, you'll want to do something. You can add whatever logic you want to the public or private methods; when the tests pass, you know you've fixed that particular issue. No need to specifically test the private methods.

There's also just basic decoupling. Since private methods aren't meant for consumption, and should be able to change radically, as long as the public interface stays intact. For instance, since you're not testing private methods right now, you could rewrite the class as below, and your current tests would still pass just fine.

class OrangeTree
  LIFESPAN = 15
  FRUIT_BEARING_AGE = 3
  ORANGES_PER_YEAR = 3

  attr_reader :age, :height, :oranges

  def initialize
    @age = 0
    @oranges = []
  end

  def age!
    @age += 1
    add_oranges if fruit_bearing?
  end

  def dead?
    age >= LIFESPAN
  end

  def fruit_bearing?
    age >= FRUIT_BEARING_AGE
  end

  def height
    age * 2
  end

  private

  def add_oranges
    ORANGES_PER_YEAR.times { oranges << Orange.new }
  end
end

(note that this implementation still has the same issues as yours: It keeps growing and adding oranges even if it's dead.)


Speed up looping through slicers and .selected true if slicer item name matches input words

Invariants, variables which don't change in a loop, should be set before entering the loop. Additionally, if you want to store the value of a Boolean expression, just store the expression's return value:

Sub SearchSlicer()
    Dim oSc As SlicerCache
    Dim oSi As SlicerItem
    Dim searchword As Variant

    searchword = InputBox("Enter a searchword")
    searchword = "*" & UCase(searchword) & "*"
    Set oSc = ThisWorkbook.SlicerCaches("Slicer_SEARCH_WORDS")

    For Each oSi In oSc.SlicerItems
        oSi.Selected = oSi.Name Like searchword
    Next oSi
End Sub

But I doubt this will speed up the loop much. Most likely the 'like' operator is where most of the time is spent (and I don't see any alternative to it).


htmlentities is used to protect against XSS, and should be used when echoing data, not when inserting it into the database.

Your approach leads to bad data (for example, now you always have to use htmlentities when checking a password, as it will otherwise be wrong), and weak security (using htmlentities before inserting data leads to it not being used when echoing - because it's already been encoded - which leads to data being forgotten, because nobody can remember what was encoded and what was not).

Misc

Functions: I would extract code blocks to functions. It makes those blocks reusable and leads to more readable code. Possible functions are eg getUserByEmail and insertUser.
rename $com_code to $confirmationCode, so it's clear what it is without reading the comments.
always use camelCase or always use snake_case for variables, don't mix this.
uniqid and rand are not good at creating random values. Even though a confirmation token isn't that sensitive, I would still use something like openssl_random_pseudo_bytes instead.
be more consistent with your spacing (eg after ,).
your error handling could be more consistent. Eg sometimes you handle the else case of mysqli_prepare, and sometimes you don't; you never check the result of mysqli_stmt_execute.
It is possible that the user will get the following error message: Prepared statement error [...] Registration Successful.
your comments are mostly not necessary. And those that are - eg the one about confirmation - would not be with better variable names and code extracted to well named functions (which could then have proper PHPDoc type comments). Having too many comments that don't add any new information is not good, because after a while a reader will just ignore all your comments, even the important ones.


It's a good effort; the important thing is to keep practicing and keep learning.  I see a number of things that may help you improve your program.

Don't overspecify member functions

The declaration of the sort_address member function in the header file is currently this:

Person& Person::sort_addbook(Person add_book[10]);

However, the Person:: is neither needed nor wanted here.  Instead, it can and should be written like this:

Person& sort_addbook(Person add_book[10]);

That make it both easier to read and satisfies the compiler when you turn up the warning level.

Let the compiler generate code where it can

The Person constructor and destructor do nothing.  The compiler could generate that for you, so you should let it.  You can simply omit both the declaration and the implementations for both of those.

Eliminate "magic numbers"

This code includes "magic numbers," that is, unnamed constants such as 10.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "10" and then trying to determine if this particular 10 means the length of the array or some other constant that happens to have the same value.

Don't use #pragma once

Although it is supported by some compilers, code which is intended to be reused should avoid non-standard extensions.  By definition, all #pragma are non-standard.  For portable code, you should use the standard include guards.  Even if you are only ever using one compiler at the moment, you will want to know the portable way of accomplishing this.

Don't use system("pausse")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  One simple replacement for that might be

void pause() {
    std::string nothing;
    std::cin >> nothing;
}

Prefer resizeable containers to fixed size

Rather than using a fixed size of 10, it may be preferable to use something like a std::vector.

Think carefully about object responsibilities

A Person is not an address_book.  A Person is an individual, while an address_book represents a collection of Person objects.  For that reason, the sort_addbook shouldn't really be a member function of the Person object.  I'd recommend implementing an AddressBook object instead and having it include a sort method.

Use a stream operators where practical

As with the point above, I'd recommend that the Person object use the << and >> operators rather than read and print.  For example, they might be implemented like this:

friend std::istream& operator>>(std::istream& in, Person &p) {
    in >> p.name;
    std::getline(in, p.address);
    return in;
}
friend std::ostream& operator<<(std::ostream& out, const Person &p) {
    return out << "Name: " << p.name
        << "\nAdress: " << p.address << '\n';
}

Don't use std::endl if you don't really need it

The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.

Prefer standard algorithms

Instead of writing your own sort, you could use the std::sort instead.  To do that, you'll need to implement a comparison operator.  Here's one way to do that, as a member function of the Person class:

bool operator<(const Person& other) const {
    return name < other.name;
}

Putting it together

Here's a way that this could be implemented.  Note that this code does not use std::vector and keeps the fixed size, but it does use all of the other suggestions:

int main() {
    constexpr unsigned ADDRESS_COUNT{10};
    Person address_book[ADDRESS_COUNT];

    std::cout << "Enter name, and then address: " << std::endl;
    for (size_t i = 0; i < ADDRESS_COUNT; ++i) {
        std::cin >> address_book[i];
    }

    std::sort(&address_book[0], &address_book[ADDRESS_COUNT]);
    for (size_t i = 0; i < ADDRESS_COUNT; ++i) {
        std::cout << address_book[i] << '\n';
    }
}


You implied Json -> Java object, but have you considered the other way around?  If so, check out Java object to Json serialization/deserialization using Gson.  Get more at https://en.wikipedia.org/wiki/Gson and https://static.javadoc.io/com.google.code.gson/gson/2.8.5/com/google/gson/Gson.html


Well, I can't say much about your naming, as I cannot read it. For a wider audience than a purely local team - and probably even then - consider switching to english.

What I can tell is that you are very generous with parentheses. Using them everywhere actually reduces readability, you know?

Next, congratulations for working smarter instead of harder, it really pays in speed.
Though there is a down-side to your implementation of the modified algorithm: It encounters Undefined Behavior due to integer-overflow slightly before the brute-force-one does (by about five to six numbers). Why are you using signed arithmetic anyway?

And then you assume the programs input is always well-formed. You know scanf() can fail? So, test the return-value.


Counting the number of alerts by type and partition from a JSON object

Compact Code

If you're looking for more compact code, you can start by avoiding redundant function declarations:

var dataKeys = data.map(function(element) {
  return Object.keys(element);
});

var dataKeys = data.map(Object.keys);

And a compact notation for an empty object.

var result = new Object();

var result = {};

Pivot Table

What you're doing is pivotting data from rows to columns. You are correct to mention reduce as this method could help us out here. It's possible to leave out the switch case if we just loop through the entries and aggregate the results.

var pivotTable = data.reduce((result, item) => {
  Object.entries(item).forEach(([key, val]) => {
    if (result[key] === undefined) {
      result[key] = { unknown: 0, ok: 0, warning: 0, ko: 0 };
    }
    result[key][val.alert]++;
  });
  return result;
}, {});

console.log(pivotTable);


There is this concerning GWT and GAE objects. If that doesn't work for you, I would rather have a class of public static methods that does the conversions rather than sticking it into some kind of "wrapper class" that contains object states. For example,

public final class JDOEntityUtil {

   static public AppointmentDTO toDTO(AppointmentEntity entity) {
       AppointmentDTO dto = new AppointmentDTO();
       dto.setId(entity.getId());
       dto.setFirstName(entity.getFirstName());
       dto.setLastName(entity.getLastName());
       dto.setAppointmentDate(entity.getAppointmentDate());
       dto.setNextAppointmentDate(entity.getNextAppointment());
       dto.setAttendant(entity.getAttendant());
       dto.setDetails(entity.getDetails());
       dto.setDNI(entity.getDNI());
       dto.setTreatment(entity.getTreatment());
       return dto;
   }

   static public AppointmentEntity toEntity(AppointmentDTO dto) {
       AppointmentEntity entity = new AppointmentEntity();
       entity.setId(dto.getId());  /* or however you want to construct this */
       entity.setFirstName(dto.getFirstName());
       entity.setLastName(dto.getLastName());
       entity.setAppointmentDate(dto.getAppointmentDate());
       entity.setNextAppointmentDate(dto.getNextAppointment());
       entity.setAttendant(dto.getAttendant());
       entity.setDetails(dto.getDetails());
       entity.setDNI(dto.getDNI());
       entity.setTreatment(dto.getTreatment());
       return entity;
   }
}


Here are few things I'd do to improve your code:

I would compact your first if statement into something such as if (Categories::where('name', 'LIKE', '%'. $search .'%')->first()) { since you only use $result for that purpose.
Remove that unnecessary horizontal space after your first assignment to $categories.
I hope that your flash messages are only for development purposes. They aren't very useful or user friendly as they are right now. Look at studied websites (Amazon, StackExchange, etc.) and UX.SE for tips on how to improve the user experience of your search function.
Be careful using the compact function. It's easy to lose track of it and forget to update it or your variables and therefore have something throw an error later on.
Fix the format of your else. Pick-and-choose either

} else {

or

}
else
{

Most search functions don't return anything when nothing was found. Again, this an issue to bring up at UX.SE, but your user might find themselves thinking that the results from your else clause are actually what they're looking for.

Overall, very nice. I'm sure you've done this, if not though, read through what you find from a search like this just to see how others have solved this problem. You'll find out good ways and bad ways of doing what you've done.


Delete from multiple tables using temp table variable

p is a cryptic table alias and that != is not ANSI compliant, you should try and use <> instead. Also, the select * from is inefficient because it has to go back to the information schema and look up every column, you should try and only select the columns you really need.


If you have to print a 5x5 box with the a different image or the same you could do something like this. It loops though all the positions that you need and assigns it to a new sprite created. It is more maintaineable, cleaner and easy to read than declaring 25 variables, and it has fewer lines of code.

// Construct the vector with the specified size.
Vec2 size(5, 5);
std::vector<Vec2> positions(size.x * size.y);

// Push back desired positions (you could use C++11 initializer lists or a loop).
// Positions needs to be declared in the same order as the sprites will be
// added with "this->addChild".
positions.push_back(position);
...

float scale(0.5);

// Loop trought the vector and assign values
for (int i = 0; i < size.x * size.y; i++) {
    auto sprite = Sprite::create("theimageyouneed.png");
    sprite->setPosition(positions[i]);
    sprite->setScale(scale);
    this->addChild(sprite, 0);
}


Grid walk problem and solving it recursively

Profiling the code has shown that iterative search in sequential array (integer keys 0, 1, ...) is far slower that simply accessing a value by string key in an associative array of non-sequential keys represented by strings (like '-1,1' or similar). So I modified isPointVisited function:

var isPointVisited = function (x, y) {
    // console.log('isPointVisited, x = %s, y = %s', x, y);
    if (visited[[x, y]])
        return true;

    return false;
};

and monkey function:

var monkey = function (x, y) {
    if (isPointAllowed(x, y) && !isPointVisited(x, y)) {
        visited[[x, y]] = true;
        return 1 + monkey(x - 1, y) + monkey(x + 1, y) + monkey(x, y - 1) + monkey(x, y + 1);
    } else {
        return 0;
    }
};

This code still executes for a bit longer than 10 seconds (11800 ms on CodeEval) but it's at least 8 times faster than before.


Print path (leaf to root) with max sum in a binary tree

You should have a constructor MaxSumPath(TreeNode root).  Otherwise, there's no way for any other class to call the code.

The TreeNode(left, right, item) constructor is awkward.  Consider rearranging the TreeNode constructor arguments to TreeNode(left, item, right) or TreeNode(item, left, right).  I suggest creating a TreeNode(item) constructor as well.

Your TreeInfo could be eliminated by moving its variables into MaxSumPath itself.  I'd rename the variables to TreeNode maxLeaf and int maxSum.

In the maxSumPath() method, you call fetchMaxSumPath(root, treeInfo, root.item).  It should be fetchMaxSumPath(root, treeInfo, 0) if you don't want to double-count the root node.  (Fortunately, this bug happens not to affect the output.)

The space complexity is actually O(log n) when you take into account the stack used in recursion.  The time complexity is O(n), because you visit every node once when discovering the leaf for the path with the maximum sum, and every node again to find that leaf for printing.  You might want to use O(log n) space (which, remember, happens anyway due to the recursion stack) to keep track of the best path while discovering the best sum, which lets you avoid the second pass O(n) pass.


I don't know any Java, but I think I can give you some ideas that may help you refine this code and make it easier to extend.  Take a look at my question about skill upgrades on this site, because I got some very good feedback on this and I think it is relevant to your situation.

Hard coding all of those values into the Upgrades class limits you in many ways.  It is nice that everything is in in one place for the sake of easily editing it all at once, but as you note it is forcing you to change data in multiple places if you want to extend the class at all, or even if you want to add new kinds of Upgrades to the game.

What I suggest (which is also the suggestion made to me in the question I linked above) is to make a base Upgrade class (though possibly with a different name), and then make one for each of the Upgrades that you want in your game.  Give it all the values that you are assigning in the Upgrades class, and give it the logic that you have in the UpgradeProgress class.  This way, all of your Upgrades will have the same underlying properties and functionality, and you can create a limitless number of them without having to change anything.  Just instantiate them with the values you want.

You may need a different base class for DefenseUpgrade or any other Upgrade that has different logic inside.  It may or may not be a good idea to have it inherit from the original class, it just depends on how many of the properties and methods are the same. In general though, I would recommend composition over inheritance whenever possible.

This code may be wrong because I don't know Java but here is the basic idea I am suggesting (syntax improved by @Larethian):

public abstract class Upgrade {

    private int LEVEL_CAP;
    private float EFFECT_PER_LEVEL;
    private int[] UPGRADE_COSTS;

    private int currentUpgradeLevel = 0;

    protected Upgrade(int levelCap, float effectPerLevel, int[] upgradeCosts){
        LEVEL_CAP = levelCap;
        EFFECT_PER_LEVEL = effectPerLevel;
        UPGRADE_COSTS = upgradeCosts;
    }

    public void increaseUpgradeLevel() {
        if (currentUpgradeLevel < LEVEL_CAP) {
            currentUpgradeLevel++;
        }
    }

    // Getter
    public int getUpgradeLevel() {
        return currentUpgradeLevel;
    }

    public int getTotalEffect() {
        return effectPerLevel*currentUpgradeLevel;
    }

    //could have getters or setters for any properties necessary
}

The Player would either have a few of these upgrades and would call the necessary logic to increase their levels when appropriate, or the Player could have another class such as UpgradeCollection that could contain all of the Upgrades inside it.


Collapse long text (with more/less links)

Instead of pn use a longer variable name. A variable like this with such a big scope really deserves a longer name. It would make the code easier to read.

var pn = text.split(' ');

Instead of commenting use the comment name as a function name:

// escape the html code in the text
text = (text || '').replace(/</g, '&lt;').replace(/>/g,'&gt;').replace(/\r/g, ' ').replace(/\n/g, '
 ')

I'd write this:

function escapeHtml(text) {
    if (!text) {
        return "";
    }
    return text.replace(/</g, '&lt;').replace(/>/g,'&gt;').replace(/\r/g, ' ').replace(/\n/g, '
 ')
}

I'd create a createToggleLink function.

function createToggleLink(prefix, linkText) {
    return '(" + linkText + ")');
}

It removes some code duplication and furthermore makes it more explicit that you close the span tag:

if (compacted) {
    var toggleLink = createToggleLink(prefix, '(show less)');
    result.push(toggleLink);
    result.push('');
}

So, the comment is unnecessary, the code says the same.


Leaving aside the algorithm there are a number of points about the code

Naming
Pascal casing is standard for C# - SimplePrimer and FindVersion as opposed to simplePrimer and findVersion.
FindVersion seems unconnected to the functionality.

Structure
public fields are generally frowned upon.  If it needs to be part of the interface, make it a Property so that the implementation can be changed if needed.
Having a separate 'return' as PrimeList seems overly complicated. There is no strong reason for not having List<BigInteger> GetPrimes(BigInteger goal)
Looking at the code, I cannot see anything obvious that might throw an exception that might be caught by the catch (perhaps an out of range on the BigInteger?) Is it needed?
As a shape I would push for any output to be external to the function. Have the calling code catch errors or report results. It makes unit testing a lot simpler


.pop() in a stack can be \$O(1)\$ with a proper implementation of linked list.


I see a number of things that may help you improve your code.

Use only required #includes

The code has a great number of #includes that are not needed.  Some files are even listed twice.  This clutters the code and makes it more difficult to read and understand.  Only include files that are actually needed.

Don't Repeat Yourself (DRY)

The mathematical operations all include large portions of repeated code.  Instead of repeating code, it's generally better to make common code into a function.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Use objects

Since you're writing in C++, what would make more sense to me would be to create a rational fraction object. Then each mathematical operation would be very naturally expressed as an operator on the object.

Use switch instead of nested if

The more appropriate control flow for your if statement in main is a switch statement.  This makes it somewhat clearer to read and understand and often provides a small improvement in performance, especially if there are many cases.

Prefer iostream to stdio.h

Using iostream style I/O makes the code easier to adapt to change.  For example, using scanf, the code has to have the appropriate matching format string for each argument, but using the >> operator, there is no such requirement and the compiler adapts automatically to whatever type is being read.

Omit return 0

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

Putting it all together

Here's an alternative implementation which uses all of these suggestions.  Note that a rational fraction is only reduced when it is being printed.  This saves some time over always maintaining that state.

#include <iostream>

class RationalFraction
{
public:
    RationalFraction(long long a=0, long long b=1)
        : num{a}, den{b}
        { }
    // unary negation
    RationalFraction& operator-() { num = -num; return *this; }
    // add the passed fraction to this one
    // The two-operand addition is built from this, and a
    // similar pattern is used for each of the other operators.
    RationalFraction& operator+=(const RationalFraction &rh) {
        num = num * rh.den + rh.num *den;
        den *= rh.den;
        return *this;
    }
    RationalFraction& operator-=(const RationalFraction &rh) {
        num = num * rh.den - rh.num *den;
        den *= rh.den;
        return *this;
    }
    RationalFraction& operator*=(const RationalFraction &rh) {
        num *= rh.num;
        den *= rh.den;
        return *this;
    }
    RationalFraction& operator/=(const RationalFraction &rh) {
        num *= rh.den;
        den *= rh.num;
        return *this;
    }
    friend std::ostream &operator<< (std::ostream& out, const RationalFraction& f) {
        RationalFraction fr=f;
        fr.reduce();
        return out << fr.num << " / " << fr.den;
    }
    friend std::istream &operator>> (std::istream& in, RationalFraction& f) {
        return in >> f.num >> f.den;
    }

private:
    void reduce() {
        if (num == 0) {
            den = 1;
            return;
        }
        long long mygcd = gcd(num, den);
        num /= mygcd;
        den /= mygcd;
        if (den < 0) {
            den = -den;
            num = -num;
        }
    }
    long long gcd(long long a, long long b) const {
        long long  c;
        while(b != 0){
            c = a % b;
            a = b;
            b = c;
        }
        return a;
    }

    // data members
    long long num, den;
};

RationalFraction operator+(RationalFraction lh, const RationalFraction &rh)
{
    lh += rh;
    return lh;
}

RationalFraction operator-(RationalFraction lh, const RationalFraction &rh)
{
    lh -= rh;
    return lh;
}

RationalFraction operator*(RationalFraction lh, const RationalFraction &rh)
{
    lh *= rh;
    return lh;
}

RationalFraction operator/(RationalFraction lh, const RationalFraction &rh)
{
    lh /= rh;
    return lh;
}

int main()
{
    int numOp;
    for (std::cin >> numOp; numOp; --numOp) {
        RationalFraction lhs, rhs;
        char op[2];
        std::cin >> lhs >> op >> rhs;
        switch (op[0]) {
            case '+':
                std::cout << lhs+rhs << '\n';
                break;
            case '-':
                std::cout << lhs-rhs << '\n';
                break;
            case '/':
                std::cout << lhs/rhs << '\n';
                break;
            default:
                std::cout << lhs*rhs << '\n';
        }
    }
}

A bit more detail

To understand this version of the code, it's useful to look at a few individual class member functions.  First, is the constructor:

    RationalFraction(long long a=0, long long b=1)
        : num{a}, den{b}
        { }

This allows for construction in a few different ways:

RationalFraction half{1,2};   // 1/2 = one half
RationalFraction three{3};    // 3/1 = 3
RationalFraction zero;        // 0/1 = 0

The basic four mathematical functions are all built in the same way.  First, there is a member function such as +=:

    RationalFraction& operator+=(const RationalFraction &rh) {
        num = num * rh.den + rh.num *den;
        den *= rh.den;
        return *this;
    }

This version is a member function and can be used like this:

RationalFraction a{1,3};
RationalFraction b{1,2};
a += b;    // now a = 5/6 and b is unchanged

It's a common idiom to define those member functions first and then construct the two-operand versions:

RationalFraction operator+(RationalFraction lh, const RationalFraction &rh)
{
    lh += rh;
    return lh;
}

This is a bit subtle.  Note that lh is passed by value, so that means a local copy is constructed using the compiler-generated default copy.  By contrast rh is a const reference, so no additional copy is created.  Now all we need to do is apply the member function version and return lh which, remember, is a copy of whatever was originally passed in for that parameter.  It is a standalone function and not a member function so that either of these works:

RationalFraction f={-1,2};
std::cout << f+3 << std::endl;  // (-1/2) + 3 = 5/2
std::cout << 3+f << std::endl;  // 3 + (-1/2) = 5/2

In the expression 3+f first a temporary rational fraction is created from 3.  Then that rational fraction is added to f and the result displayed using the << operator.  That is, it's approximately the equivalent to this:

RationalFraction temp1{3};   // = 3/1
RationalFraction temp2 = temp1 + f;  // do addition using non-member function
std::cout << temp2 << std::endl;  // show the result = 5/2

The only other slightly tricky bit of code is in private member function reduce.  Here I've added comments to make it easier to understand:

void reduce() {
    // if it's of the form 0/x, turn it into canonical 0/1
    if (num == 0) {
        den = 1;
        return;
    }
    // reduce by dividing by the greatest common divisor of
    // numerator and denominator
    long long mygcd = gcd(num, den);
    num /= mygcd;
    den /= mygcd;
    // Only allow the numerator to be negative to simplify printing.
    // Changing sign of both numerator and denominator has no
    // mathematical effect on the value.
    if (den < 0) {
        den = -den;
        num = -num;
    }
}


Determine objects to delete from a database

There is an easier way to find the cars to delete. You just need to use the Except extension.

var carsToDelete = existingCars.Except(newCars);

In order for this to work you have two choices:

you can either implement the IEquatable for each DTO or
you can implement a common interface for the Id and a custom IEqualityComparer<IYourInterface> and use it with the Except extension.


Removing the massive amount of for-loops in this code

There are a few tweaks that can improve this code:

def add_random_fields():
    from numpy.random import rand
    server = couchdb.Server()
    databases = (server[database] for database in server if not database.startswith('_'))
    # immediately fetch the Server object rather then the key,
    # changes to a generator to avoid instantiating all the database objects at once
    for database in databases:
        for document in couchdb_pager(database):
            document = database[document]
            # same here, avoid holding keys when you can have the objects

            for tweet in document.get('results', []):
            # rather then checking for the key, have it return a default that does the same thing
                if tweet and 'rand_num' not in tweet:
                    print document
                    tweet['rand_num'] = rand()
                    database.save(tweet)


The fetch() call only calls a single row from result set.
Your foreach loop will, as a result, just go in the first result and do nothing. It may even produce an error/notice for undefined index in $row.
While using a SELECT statement in PHP, always include the specific columns that you want to fetch. This is among good practices.

$sth = $dbh->prepare("SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp");
$sth->execute();
?>
<?php foreach($sth->fetch(PDO::FETCH_ASSOC) as $row) : ?>

    <?php echo $row['field1']; ?>
    <?php echo $row['field2']; ?>
    <?php echo $row['field3']; ?>
    <?php echo $row['field4']; ?>
    <?php echo $row['field5']; ?>

<?php endforeach;?>

Or, if you want to use a while loop:

$sth = $dbh->prepare("SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp");
$sth->execute();
?>
<?php while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) { ?>

    <?php echo $row['field1']; ?>
    <?php echo $row['field2']; ?>
    <?php echo $row['field3']; ?>
    <?php echo $row['field4']; ?>
    <?php echo $row['field5']; ?>

<?php } ?>


Consider using custom attributes.
Here is a possible variant:
Create a class representing the data from the excel file and decorate it with attributes.

    public class ExcelData
    {
        [ExcelColumn("Name")]
        [Required]
        [MaxLength(27)]
        public string Name { get; set; }

        [ExcelColumn("NextColumn")]
        [Required]
        public string NextColumn { get; set; }
        //...another 94 property.
    }

Then create a class that gets excel and returns a list of this data using ExcelColumn attribute.

    public class ExcelParser
    {
        public IEnumerable<ExcelData> Parse(string fileName)
        {
            //Get file and return ExcelData, using ExcelColumn attribute.
        }
    }

Then create a class to convert this data to XML.

public class ExcelDataToXmlConverter
    {
        private ExcelDataValidator _validator = new ExcelDataValidator();

        public XDocument Convert(IEnumerable<ExcelData> excelData)
        {
            foreach (var data in excelData)
            {
                var errors = new Dictionary<string, List<string>>();
                if (_validator.IsValid(data, out errors))
                {
                    //Convert the row to XML
                }
                else
                {
                    //Do something with errors.
                }
            }
        }
    }

    public class ExcelDataValidator
    {
        //errors - is a list of errors where the key is the name of the field and value is the list of errors.
        public bool IsValid(ExcelData excelData, out Dictionary<string, List<string>> errors)
        {
            //Validate using different attributes: Required, MaxLength and so on.
        }
    }

Maybe you'll be able to use attributes for actual converting data to XML.
Of course it's only a very crude sketch, and only some parts of it may be useful for you, but I hope you've got the idea.


Given a sequence of positive integers A and an integer T, return true if a continuous sequence of A sums up to exactly T

Approach and complexity

It is a pleasure to tell you this: Excellent!

Your approach is precisely what I had in mind when I read the challenge description (before looking at your code).

Unit tests

Excellent that you have unit tests! Definitely helps in checking if it's possible to clean up your method. My only suggestion would be to make them Parameterized, which should be a lot more helpful if one or more of them fails.

Some simplifications

I was slightly confused by this code at first:

if (array[i] > k) {
    i += 2;
    start = i;
    sum = 0;
    continue;
}

Then I noticed that it checked if the value at the current position in the array was more than the target k. Then I figured: "Why use this as a special case? The rest of the code should be able to handle this." And it does. Removing this part of the code doesn't change a thing on your unit tests either. While I can understand why you are doing this (it probably does help a bit with performance in some cases), I don't think it's worth it. Don't add unnecessary special-cases.

Next thing I noticed is that sum < k will always be true. Therefore, that if can be removed and be simply:

sum += array[i];
i++;

And now, speaking of i++, we can transform this for-loop into a traditional for loop, by adding both the initialization and the iteration to it:

for (int i = 0; i < array.length; i++) {

This makes it:

static boolean findSum(final int[] array, final int k) {
    int start = 0;
    int sum = 0;
    for (int i = 0; i < array.length; i++) {
        sum += array[i];
        while (sum > k) {
            sum -= array[start];
            start++;
        }
        if (sum == k) {
            return true;
        }
    }
    return false;
}

Nitpicks

k is a bad variable name. target or targetSum would be better.

I am not a big fan of int start = i; in your original code. start is not dependent on i at all. They start at the same value, sure, but it's more clear to set start = 0;

Your method lacks an accessibility modifier, you probably want to make it a public method.

Overall

Well done!


Break some of the functionality into functions. For instance, notice that all line types except for 4 behave similarly. So how about you do:

bool isSimpleType(char c) {
    return (c >= '0' && c <= '3') || (c == '5');
}

With this, you can now simplify your main loop:

for(int i = 1; std::getline(stream, line); ++i)
{
    if (line == "")
        continue;

    const char type = line.front();

    if (isSimpleType(type)) {
        std::cout << "Line " << i << " type " << type << ": " << line << "\n";
    }
    else if (type == '4') {
        // Omitted to reduce clutter
    }
    else {
        std::cout << "Line " << i << " No type" << std::endl;
    }
}

Finally, let us proceed along similar lines to simplify the case of '4'. I'll let you take over from here, but read the inputs to a vector and pass that onto a function that is responsible for verifying if the line is OK and constructing a suitable object from the data then.

Also, instead of relying on "naked values", you could also consider using a class enum Type { ... } to define the different line types. I recommend you read more about enums for this.


Finding the longest word from a list of words

Whenever I only use the extracted value once in a simple group / map / sortBy monadic operations I use the _ placeholders.  I think it makes the code a little more compact and readable, especially if it was just a placeholder value like x

.groupBy(x => x._1) becomes .groupBy(_._1)

.mapValues(x => x.toSet) becomes .mapValues(_.toSet) or even mapValues toSet if you like infix

It's not a universal rule by any means, sometimes you really need a meaningful name so that another coder could make sense of it.

Edit
Also you can go straight to the group by and remove redundant counts

val oneLiner = line.groupBy(_.length).mapValues(_.toSet).maxBy(_._1)

//> oneLiner  : (Int, scala.collection.immutable.Set[String]) = (3,Set(abc, pqr, mnp, jkl, xyz))


What's the most optimal way to see if a string is included in a list of strings?

If you really have just three words, then the performance most likely won't matter. In other words, unless profiling shows that this method is performance-critical, use the method that you find most readable.

Some other options you could consider:

Using a switch:

switch (word)
{
    case "Foo":
    case "Bar":
    case "FooBar":
        return true;
    default:
        return false;
}

This has the advantage that it can use compiler optimizations. (Under certain circumstances, the compiler will turn such switch into a Dictionary lookup.)
Use a HashSet<string> instead of an array. Looking up in a hash set is O(1), but O(n) for an array. This could make sense if you had large number of strings to search for.
Use a trie. This has the advantage of comparing only relevant parts of the input string. This could make sense if you had long input strings or if you huge number of strings to search for.


Counting words, letters, average word length, and letter frequency

It's gonna be a small review, but do you know strtok ? As said on the link I provided :

  A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

So if you want to split this into words, just put the delimiters to space and punctuation, and you already have most of the job done.

An other thing :

float avg(float words, float letters)
{
    float a = (double)(letters / words);
    return a;
}

If you want a float, why do you explicitly cast it to a double ? That's why you have warnings.

Same goes for the typing of words and letters : can it take a negative value ? If not, why does your type allows it to do so, instead of using an unsigned type ?

And last, I think you are re-inventing strlen with this piece of code : for (size = 0; array[size]; size++);. And of course you should not, just use the function instead.


Python factory method with easy registry

1. Stop writing classes

The title for this section comes from Jack Diederich's PyCon 2012 talk.

A class represents a group of objects with similar behaviour, and an object represents some kind of persistent thing. So when deciding what classes a program is going to need, the first question to ask is, "what kind of persistent things does this program need to represent?"

In this case the program:

knows how to load NumPy arrays from different kinds of file format (CSV and plain text); and
knows how to compute the relative difference between two NumPy arrays (so long as they come from files with the same format).

The only persistent things here are files (represented by Python file objects) and NumPy arrays (represented by numpy.ndarray objects). So there's no need for any more classes.

2. Other review points

The code calls numpy.seterr to suppress the warning:

RuntimeWarning: invalid value encountered in true_divide

but it fails to restore the original error state, whatever it was. This might be an unpleasant surprise for the caller. It would be better to use the numpy.errstate context manager to ensure that the original error state is restored.
When dispatching to NumPy functions, it usually unncessary to check shapes for compatibility and raise your own error. Instead, just pass the arrays to NumPy. If they can't be combined, then NumPy will raise:

ValueError: operands could not be broadcast together ...

3. Revised code

Instead of classes, write a function!

import numpy as np

def relative_difference(t, r):
    """Return the relative difference between arrays t and r, that is:

    0              where t == 0 and r == 0
    (t - r) / r    otherwise

    """
    t, r = np.asarray(t), np.asarray(r)
    with np.errstate(divide='ignore', invalid='ignore'):
        return np.where((t == 0) & (r == 0), 0, (t - r) / r)

Note the following advantages over the original code:

It's much shorter, and so there's much less code to maintain.
It can find the difference between arrays that come from files with different formats:

relative_difference(np.loadtxt(path1), np.fromfile(path2))

It can find the difference between arrays that don't come from files at all:

relative_difference(np.random.randint(0, 10, (10,)), np.arange(1, 11))


Replace fixed width values over 530px with 100% using RegEx

Disclaimer

As pointed out in a comment by Thomas Ward, RegEx should not be used to parse HTML or CSS. This answer should only be taken as a review of your regular expressions only, and doesn't imply that I recommend using RegEx to parse HTMl/CSS.

As mentioned by Phrancis, you may use DOM manipulation methods to iterate over elements and set styles on them. Or, you can also use CSS to set styles to containers, such that the elements inside it respect the cascaded styles. For example, setting max-width on container and overflow will make the width of the container fixed and show scroll bars when content inside it overflows.

If you add more context regarding how and where this RegEx is being used, there might be better ways than RegEx. Please edit the question to add more context.

Review

(\:\s?|=)\s*: In this group, it is matching either : followed by optional space or = symbol. : has no special meaning in regular expression i.e. it is not meta-character thus there is no need to escape it. Next, \s? is not required here. As there is \s* after the group, it'll match any number of spaces followed by the one of the symbol from the group. So, \s? can be safely removed.

After making these changes the group will become (:|=)\s*.

It is also observed that character class is faster than OR in groups. Check the demo for [:=] and (:|=) for same input data. Notice the number of steps required to finish match. Character class took 12 steps while group with OR condition took 30 step which is more than twice of the character class.

Now, after using character class the group will become [:=]\s*

Similarly, in other character class 0 is escaped as \0 which is not necessary and can be safely removed.

Let's look at the group (\s*(cm|in|mm|pc|pt|px|q)|(?!%|vw|vh|vmin|vmax|em|ex|ch|rem)).

This matches the unit f or the width property. First, \s* to match space is used. Space cannot be used between the value and unit in CSS. That'll make the property invalid and will not be applied.

After that, there are two groups of units separated by |-OR. These two can be combined in one as (cm|in|mm|pc|pt|px|q|%|vw|vh|vmin|vmax|em|ex|ch|rem).

At the end of regex, [ ]* is used to match any number of spaces. This can be simply written as *(Note this is space followed by *). What is there is a tab instead of space? \s* will solve the problem.

Oh wait, that space is not used anywhere, so it can be removed from regex.

Mistake

If you look closely at the input and output string, you'll notice that the regex is removing single and double quotes from the attribute styles.

width='530' has become width=100%'.

To solve this, simply add $3 in the replacement part. The replacement will be now $1$2$3100%.
Another one is that the regex leaves width: 600rem; which is not intended.

This will be solved when two groups of units are combined. But, this will create an issue of not matching unit-less values like width: 600. By adding empty option in group using | will solve the problem(notice the end of group). Here's how the group will look like

(cm|in|mm|pc|pt|px|q|%|vw|vh|vmin|vmax|em|ex|ch|rem|)

Improvements

Does the above changes really improve the regex?

The above changes brings the number of steps to 1630 from 1881 with one increase in match(rem).

RegEx: ((?:m(?:in|ax)-)?width)\s*([:=])\s*(['"0])?\s*([1-9]\d{3,}|5[3-9][0-9]|[6-9][0-9]{2})(cm|in|mm|pc|pt|px|q|%|vw|vh|vmin|vmax|em|ex|ch|rem|)

Replacement: $1$2$3100%

Demo

UPDATE:

  The emails which get sent contain media queries in the header, which are lost as our system only pulls in the of the content.

The media queries related to email can be stored in a separate CSS file and it can be included on the page where email content is shown on your site.

You can also remove all the inline styles from email content HTML and put them in separate CSS file. When sending email, include this CSS file in HTML and when showing the content in your site, include other CSS file. This will show the content correctly in respective sites.


void getInitialization()

The name of the method implies that we would get something but the return value is void. Maybe a better name would be in order. How about Initialize() ?

an empty catch block is always a very bad sign. If you want to swallow any exception, you should clearly state with a comment why you are swallowing the exceptions.

it is always recommended to use braces {} for single statment if to make the code less error prone.

images = new Images(); where is images declared ? It would be better to have this as a method scoped variable instead of reusing a class level one.
In addition the name Images implies that it contains multiple Image items which it doesn't do.

If an exception is thrown from inside the try block after the call to  dao.open(); the dao will stay open.
You should use a finally block to close the dao.


Dynamic Programming: Fibonacci-like recurrence relation

Recursive Solution

Code-wise, I see no issues. The one thing I'd point out is that it might be clearer to name your functions A and B instead of Nth and Aux, since the problem has to do with finding A and it isn't readily apparent what Aux means. It's a little unclear, but not a dealbreaker.

Bottom-up method

I don't really understand why your memoized map contains an array. If it's really a "pair" type such that memoizedMap[n] is \$(A_n, B_n)\$, then I'd introduce a new type for that. Arrays can mean anything, so once you make the decision to go with an array, the code is very difficult to follow. You're introducing some boolean flags, which are probably unnecessary too.

That said, I'm not sure that simply memoizing the recursive solution is what the problem intended. The intent seems to instead suggest that you compute the arrays iteratively. That is just the same way you could compute the Fibonacci sequence iteratively (in fact, the two sequences are very closely related, as \$A_1, B_2, A_3, B_4, ...\$ is the Fibonacci sequence): just keep the last few elements and update them as you go:

public static int getAn(int n) {
    if (n <= 2) return 1;

    int a0 = 1;
    int a1 = 1;
    int b0 = 2;
    int b1 = 2;

    for (int i = 0; i < n-2; ++i) {
        int nexta = b1 + a0;
        int nextb = a1 + b0;

        // updates
        a0 = a1;
        a1 = nexta;
        b0 = b1;
        b1 = nextb;
    }

    return a1;
}


Your code is compact, and yet still highly readable. Nice work! Here are some suggestions:
Avoid Global Data
The tree and n variables are global data meaning that any function anywhere in your application can change them. This makes it very difficult to follow the flow of control and figure out where data is modified. It's not a big deal for this little program, but there's no reason you can't put them into main().
Also, while we're talking about your variables, n is not a terribly descriptive name. I would call it something like numNodes or something along those lines.
Don't Traverse the Tree So Many Times
In your Height() function you traverse the tree n^2 times! At the very least, once you've found the parent you shouldn't traverse the rest of the array. But an even better way is to only traverse the entire tree once.
That's what I did in the example below. Note that I couldn't try it out on the website you mentioned because it requires one to sign up for an online course, and as you mentioned, the site was in Russian which I don't understand.
The first thing I did differently was to make a data structure to hold my node data. While the input only contains integers, that doesn't mean that you have to only put integers into your array. I created a type called Node that holds the parent index, a pointer to the actual parent node, and an array of pointers to child nodes. It looks like this:
typedef struct Node {
    int                 parentIndex = { kParentUnset };
    Node*               parent      = { nullptr };
    std::vector<Node*>  children;
} Node;

Which reminds me of my next point - it's a good idea to avoid magic numbers like -1 bare in your code. I made some enums to describe different values for parentIndex:
enum {
    kNoParent       = -1,
    kParentUnset    = -2
};

This makes the code a little easier to read and understand.
You'll notice that I also didn't actually use C arrays, but instead went with std::vector<>. I did this because it allows me to add and remove items without knowing the size ahead of time, and to avoid putting a large block of data on the stack. It's also more standard C++.
So what this code does is read in the number of nodes and the parents of each node. As it reads in a parent, it not only sets the next node's parent index, it also actually sets the pointer to the parent and adds the current node to the parent's list of children. By the time the for loop in main() is complete, we have the entire tree built in memory. The fact is, we don't even need the parent indexes anymore. We could just discard that field, but I've left it to be more clear.
Next, we traverse the tree and calculate the maximum height. This is done using a depth first search. I implemented the search without recursion again to save space on the application stack and avoid a potential stack overflow. We start with the root node and push it onto our local stack variable. Then we enter a loop where we increment the current height, and see if it's greater than the max. If so, we set the max to the current height. Next, we pop the top off the stack. If it has no children, we've hit a leaf node. We decrement the current height and continue on. If it does have children, we push each one onto the stack and loop again.
Here's the code:
int findTreeHeight(Node* rootNode)
{
    int maxHeight   = 0;

    std::stack<Node*>   nodeStack;
    nodeStack.push(rootNode);

    int currentHeight   = 0;
    while (nodeStack.size() > 0)
    {
        currentHeight++;
        if (currentHeight > maxHeight)
        {
            maxHeight = currentHeight;
        }

        Node*   top = nodeStack.top();
        nodeStack.pop();

        if (top->children.size() == 0)
        {
            currentHeight--;
        }

        for (auto iter = top->children.begin(); iter < top->children.end(); iter++)
        {
            nodeStack.push(*iter);
        }
    }

    return maxHeight;
}

int main ()
{
    int numNodes = 0;
    std::cin >> numNodes;

    std::vector<Node> tree(numNodes);

    int rootNodeIndex   = -1;
    for (int i = 0; i < numNodes; ++i)
    {
        int parentIndex;
        std::cin >> parentIndex;

        tree [ i ].parentIndex = parentIndex;

        if (parentIndex == kNoParent)
        {
            rootNodeIndex = i;
        }
        else
        {
            tree [ i ].parent = &tree [ parentIndex ];
            tree [ parentIndex ].children.push_back(&tree [ i ]);
        }
    }

    std::cout << findTreeHeight(&tree [ rootNodeIndex ]) << "\n";

    return 0;
}


Using serializable to preserve/save objects

If this is a private project, where you're free to use alpha-staged libraries I'd strongly recommend you take a look at Android Architecture Components. A great talk about the subject was given at the recent Google I/O.

Restructuring your app's architecture and using Android Architecture component - the LifeData and LifecycleObserver in particular will very much ease the problem of having to deal with LifeCycle events (such as screen orientation change).

If you're writing a game, then the Component-based Architecture may be interesting for your purposes. You'll very likely come across it when investigating architectures suitable for Games (render loops etc).

The general idea is:

Separation of concerns and improving testability. Ideally you should be able to unit-test your entire game with locally running Java tests and no UI necessary whatsoever. This however requires you to separate your Game instance from your activity - something I'd highly recommend either way.
Making your game modular and plugging it together in the form of components (this architecture style is a matter of preference but lends itself quite well to games)

Let me know, if you want me to elaborate on any of the points I mentioned.


Good job on adding the test suites; they make testing code extremely easy.

Recursion often results in a clean solution. However, I think that this problem can be solved just as well with an iterative approach.

The key to innermost_parens is to return the text between the last ( and the first ). Recursion is a viable solution, but I find that this for loop does the job better and in a cleaner way:

def innermost_parens(text):
    """
    Returns the innermost parenthesis.

    >>> innermost_parens('* 1 2')
    '* 1 2'
    >>> innermost_parens("1 + (2 * (4 - 1))")
    '(4 - 1)'
    >>> innermost_parens("1 + (2 * (4 * (2 + (8 * 7)) - 1))")
    '(8 * 7)'
    >>> innermost_parens("(1 + 2) * (3 + 4)")
    '(1 + 2)'
    """
    start = 0
    end = len(text)
    for (i, c) in enumerate(text):
        if c == '(':
            start = i
        if c == ')':
            end = i + 1
            break
    return text[start:end]

Take note that this function will return the first innermost expression with brackets. The reason for this will be clear later.

As for polish_eval, your program doesn't follow the standard Polish notation. In the standard Polish notation you can only perform operations on two numbers. It is also unclear what 'start' does. I modified your code to do the above and added tests for subtraction and division:

def polish_eval(expr):
    """
    Reduced Polish notation.

    >>> polish_eval('+ 4 1')
    5.0
    >>> polish_eval('* 4 5')
    20.0
    >>> polish_eval('- 20 3')
    17.0
    >>> polish_eval('/ 20 5')
    4.0
    """
    oper, a, b = expr.split()
    return OP_FOR_SYMBOL[oper](float(a), float(b))

I'll leave the documentation of the Polish notation to you. No changes were made to infix_eval.

Finally, we're on to full_eval. Since there's been a major change in the notation we support, we'll have to rewrite the code. First, to start off with the tests:

>>> full_eval("* (* 4 5) (+ 4 1)", polish_eval)
100.0
>>> full_eval("* 4 (/ 1 10)", polish_eval)
0.4
>>> full_eval("1 + (5 * 2)", infix_eval)
11.0

Rewriting Polish notation without brackets would require the use of a stack. This will not fit nicely in your full_eval function, so I will not implement the notation without brackets. In this function, the use of recursion is unnecessary and a while loop will fit the problem nicely.

def full_eval(expr, eval_type):
    """
    Evals by the rules of eval_type starting from the inner
    parenthesis.

    >>> full_eval("* (* 4 5) (+ 4 1)", polish_eval)
    100.0
    >>> full_eval("* 4 (/ 1 10)", polish_eval)
    0.4
    >>> full_eval("1 + (5 * 2)", infix_eval)
    11.0
    """
    while len(expr.split()) != 1:
        inn = innermost_parens(expr)
        result = eval_type(inn.strip('(').strip(')').strip())
        expr = expr.replace(inn, str(result))
    return float(expr)

Before I evaluate inn, I first strip off the brackets which enclose the expression, as well as any remaining whitespace.

The reason why I wrote innermost_parens as shown above is to allow for the easy replacement of the expression. Here's a trace of an expression in Polish:

  * (/ 9 3) (+ (/ 3 5) (- 20 5))
= * (/ 9 3) (+ 0.6 (- 20 5))      # '(/ 3 5)' -> '0.6'
= * (/ 9 3) (+ 0.6 15.0)          # '(- 20 5)' -> '15.0'
= * 3.0 (+ 0.6 15.0)              # '(/ 9 3)' -> '3.0'
= * 3.0 15.6                      # '(+ 0.6 15.0)' -> '15.6'
= 46.8                            # '* 3.0 15.6' -> '46.8'

and the same expression in infix:

  (9 / 3) * ((3 / 5) + (20 - 5))
= (9 / 3) * (0.6 + (20 - 5))      # '(3 / 5)' -> '0.6'
= (9 / 3) * (0.6 + 15.0)          # '(20 - 5)' -> '15.0'
= 3.0 * (0.6 + 15.0)              # '(9 / 3)' -> '3.0'
= 3.0 * 15.6                      # '(0.6 + 15.0)' -> '15.6'
= 46.8                            # '3.0 * 15.6' -> '46.8'

Extensions:

Write your program such that it can parse Polish notation without brackets. That's what Polish notation is invented for.
Handle edge cases such as ((* 3 15)) (Polish).
Write test suites to ensure that the expressions are evaluated correctly. While addition and multiplication is commutative, subtraction and division are not, and the order of the numbers matter.
Follow suggestions in l0b0's answer, which are cosmetic. I did not make any cosmetic suggestions as I thought that it was more important to settle the logic of the program first.
Have your program create an abstract syntax tree instead of doing string operations (such as replacing innermost expression with its value).

Feel free to ask questions in the comments.


Aside from using a naive function to find prime, the GetPrimeOccurrence function could use some tightening up.  Most specifically the loop should use a shortcut and return as soon as the nth occurrence is reached:

static long GetPrimeOccurence(int NthOccurence)
{
    if (NthOccurence==1)
        return 2;

    int primePosition=2;
    bool numberIsPrime =false;
    for (long testForPrime=3; primePosition <= NthOccurence; testForPrime +=2)
    {
        numberIsPrime = IsPrime(testForPrime);

        if (numberIsPrime)
        {
            if(primePosition == NthOccurence)
            {
                return testForPrime;
            }
            primePosition++;
        }
    }
    return 0;
}


TL;DR: no.

The construction that is shown in the original example provided the following functionality:

decoupling from MySQL (you dont, need disable emulation of prepared statements, if you are not using mysql, and you usually dont need to provide username and password with SQLite)
option to use MySQLi or SOAP or any other DAL without rewriting the factory (see OCP)
replacing PDO with a mock object, when running unit tests
a way to alter the anonymous function, so that you can share the same PDO instance among multiple factories (when appropriate changes added)
establishing a connection to data source, only when it is necessary (connecting to SOAP can be really slow, and RDBMS under heavy load can actually run out of "connections" that can be opened)


HackerRank (Stacks) - Maximum element solution gets a timeout

Performance review
These code challenges have tight constraints (a very good thing in my view) so you you must be aware of the actual load on the CPU for every line you write.
Also these code challenges run on V8, and sometimes that version is not up to date. It helps to have some knowledge of some of V8's oddities, past and present.
Looking at your code.
The first problem is the parsing of the input. Using Array.map is convenient but slow.
Rather than parse the input before you process it, combine the processing with the parsing. This will save a significant amount of time.
Don't slice arrays if you don't need to, there are better ways to access data in arrays if speed is important.
Same with Array.reduced, there is no need for it in this example.
Use Number("42") to convert to number rather than parseInt as it is quicker. There really is only one use for parseInt and that is to convert numbers from bases other than 10.
The commands (first value per line after first line) are not used as numbers, you don't need to convert them.
RegExps are very quick compared to loops, iterators, and many of the array functions. Its well worth learning RegExps to get the most out of your code.
You can use a RegExp to split the input. input.split(/[^0-9]/g); will split on each non digit and a zillion times faster than using String.split and array.map
Function calls add overhead that is not related to the algorithm. Avoid needless function calls if you can. That does not mean flatten out your code that means dont create indirect function calls if there is no need.
// completely redundant and only adds overhead.
let maxNum = (acc, curr) => Math.max(acc, curr);

V8 specific
Watch out when using let. Some of these code challenge sites are still running on older versions of V8 and let used to add a big overhead especially inside loops.
Careful with indexing indexing. Some JS engines are not as efficient as others when it comes to array indexing and property referencing.
For example V8 will be slower when you reference an array elements using multiple indexes
var c = 0;
for(var i = 0; i < 10; i ++){
   for(var j = 0; j < 100; j ++){
      c += myArray[i][j];
   }
}

You can improve the performance by staying as close to the required index as possible.
var c = 0;
for(var i = 0; i < 10; i ++){
   const innerArray = myArray[i]; // only need to calculate i index 10 times
                                  // rather than 1000 times.

   for(var j = 0; j < 100; j ++){
      c += innerArray[j];
   }
}

Note V8 has made some amazing improvements over the past months. It always pays to test performance when in doubt.
Rewrite
The following will be about the fastest possible. the only performance increase you could get is using a typed array and implementing your own stack (which is worth the effort for larger array sizes)
/* Commands first item is command count
1 x  -Push the element x into the stack.
2    -Delete the element present at the top of the stack.
3    -Print the maximum element in the stack. */
function processData(data) {
    const stack = [];
    const input = data.split(/[^0-9]/g); // RegExp to split the data
    var max, i, inPos = 0; // inPos is data read pos
    var count = Number(input[inPos++]); // You could get away without Number
                                        // but using a number type is faster
    while (count--) { //simplify the loop
       const command = input[inPos++];  // The command is not used as number
       if (command === "1") { // compare to the string not number as its quicker
                            // in this situation
            // Older V8 the following is the fastest way to push to an array
            stack[stack.length] = Number(input[inPos++]);
       } else if(command === "2") {
            stack.pop();
       } else {
            // for and while loops are faster than array methods.
            i = stack.length;
            // you dont know if length could be zero
            // but it says nothing about what to do for no value so I am
            // assuming it safe to get max from the top.
            max = stack[--i];
            while (i--) {
                // there may be a slight advantage to using the next line
                // but cant remember how much to, indexing stack twice may
                // swing the balance
                // max = max < stack[i] ? stack[i] : max;
                // over calling Math.max
                max = Math.max(max, stack[i]);
            }
            console.log(max);
       }
    }
}

I find expanded and commented code hard to read so below is a neater version in my prefered style.
function processData(data) {
    const stack = [];
    const input = data.split(/[^0-9]/g);
    var count, max, i, inPos = 0;
    count = Number(input[inPos++]);
    while (count--) {
       const command = input[inPos++];
       if (command === "1") { stack[stack.length] = Number(input[inPos++]) }
       else if (command === "2") { stack.pop() }
       else {
            i = stack.length;
            max = stack[--i];
            while (i--) { max = Math.max(max, stack[i]) }
            console.log(max);
       }
    }
}


Object-oriented JavaScript and Google Maps objects memory management

Theory
Fist of all check this article about memory management, it will help to find leaks if any.
Look closer at this part

Limitation: cycles
There is a limitation when it comes to cycles. In the following example two objects are created and reference one another – thus creating a cycle. They will not get out of the function scope after the function call, so they are effectively useless and could be free'd. However, the reference-counting algorithm considers that since each of both object is referenced at least once and none can be garbage-collected.

Also

Mark-and-sweep algorithm
This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".
This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.
This algorithm is better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

Second quote sad that it is enough to be unreachable from so called roots objects to be collected with garbage collection.
So if you follow all recommendation and memory still leaks, than there is one of problems:

library you are using not release objects
garbage collector has not started (I mean it has some timeout when to collect objects)

Garbage timeout
Look at dummy example of garbage timeout at fiddle. I'm creating array of 30M elements of int, that are binded to root object - window.
window.data = [];
for (var i = 0; i < 30*1000*1000; i++)
    window.data.push(i);

Then on click, i'm releasing this object
function onDelete(event) { window.data = null; }

But, memory get free only after 3 minutes in my Google Chrome 43.0.2357.125 (64-bit). I was looking in htop, so chrome could free objects instantly, but return to system only after 3 minutes.
Profiling
If everything looks impossible, you can always try experimental way, using profiling. There is awesome article about profiling in Google Chrome also Firefox Developer Tools.
I have applied chrome heap profiles for my example, and it says that data object doesn't exist in window scope any more after pressing "delete" button.
Hopes it will help.


Merging worksheets and using find/replace

To supplement Gaffi's suggestions, I think you would benefit from changing this:

'Char mishap replacements
With Workbooks("CompanyBook.xlsm")
.Worksheets("Report1").Cells.Replace What:="&quot;", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="â€™", Replacement:="’", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="â€¦", Replacement:="…", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="Â£", Replacement:="£", LookAt:=xlPart, MatchCase:=False
'.Worksheets("Report2").Cells.Replace What:="â€˜", Replacement:="‘L", LookAt:=xlPart, MatchCase:=False
.Worksheets("Company").Select
End With

To this:

Dim r1 As Excel.Range, r2 As Excel.Range
Set r1 = Workbooks("CompanyBook.xlsm").Worksheets("Report1").Cells.SpecialCells(xlCellTypeConstants)
Set r2 = Workbooks("CompanyBook.xlsm").Worksheets("Report2").Cells.SpecialCells(xlCellTypeConstants)

With r1
    .Replace What:="&amp;", Replacement:="&", LookAt:=xlPart, MatchCase:=False
    .Replace What:="&quot;", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False
End With

With r2
    .Replace What:="â€¦", Replacement:="…", LookAt:=xlPart, MatchCase:=False
    .Replace What:="Â£", Replacement:="£", LookAt:=xlPart, MatchCase:=False
End With

This way, you narrow down the selection to only cells that have content for Excel to find/replace. Also, because you set the range to a variable once, Excel doesn't have to search through all cells multiple times like it is now.


Describe your problem better

While this may seem not be a thing to be pointing out in a code review it is important to describe your problem in a nice way.
I would describe it as follows:

I want to yield each property of an object every three seconds. However the first one should be delayed by 10 seconds.

Separation of concerns

You are mixing the time repeating problem with the property yielding.
You also don't allow a way to specify a different strategy for what to do whenever another property comes (in this case that would be the console.log).

function setIntervalDelayed(delay, interval, cb){
    setTimeout(function(){
        if(cb()){
            setIntervalDelayed(interval, interval, cb);
        }
    }, delay);
}

function yieldProperties(obj, delay, interval, cb){
    var props = Object.getOwnPropertyNames(obj);
    setIntervalDelayed(delay, interval, function(){
        if(props.length == 0) return false;
        cb(obj[props[0]]);
        props.shift();
        return props.length > 0;
    })
}

yieldProperties({x:0, y:1, z:2}, 1000 * 10, 1000 * 3, console.log);

EDIT

While my approach is sligthly better then yours there is still mixed code. Again yieldProperties is doing more then it should, it still has that depedency of the delay and interval arguments, that don't really fit there.
Solution: implement iterator pattern.

    function setIntervalDelayed(delay, interval, cb){
        setTimeout(function(){
            if(cb()){
                setIntervalDelayed(interval, interval, cb);
            }
        }, delay);
    }

    function iterate(arr, cb){
        var i = 0;
        return function(){
            if(i >= arr.length) return false;
            cb.apply(arr[i]);
            ++i;
            return true;
        };
    }

    function yieldProperties(obj, cb){
        return iterate(Object.getOwnPropertyNames(obj), function(){
            cb({
                name: this.toString(),
                value: obj[this]
            });
        });
    }

    setIntervalDelayed(10 * 1000, 3 * 1000, yieldProperties({x:0, y:1, z:2}, console.log.bind(console)))


Transforming a list of two-dimensional coordinates into a flat list of relative changes

for i in xrange(1, len(coords)) is a red flag, since it is preferred in python to iterate directly over the elements rather than the indices. If you trully need the indices, you can still use enumerate.

Here it would look like

for i, coord in enumerate(coords[1:]):
    previous = coords[i]
    parsed.extend([int(previous[0] - coord[0]), int(previous[1] - coord[1])])

which seems worse as it

creates a copy of coords when slicing it;
still uses an index to retrieve the previous element.

Instead, it seems better to convert the list into an iterator an manually handle the current/previous coordinates. Something like:

def parse_coordinates(coords):
    iterator = iter(coords)
    previous_x, previous_y = iterator.next()
    parsed = [int(previous_x), int(previous_y)]
    for current_x, current_y in iterator:
        parsed.append(int(previous_x - current_x))
        parsed.append(int(previous_y - current_y))
        previous_x, previous_y = current_x, current_y
    return parsed

You can note the use of append instead of extend that will avoid building a temporary list. append try to be smart when resizing the underlying array so that two consecutive appends should not have more performance hit than extend.

But all in all, using append or extend in a for loop is often better written using a list-comprehension or a generator. You can easily turn this function into a generator by turning these append into yields:

def parse_coordinates(coords):
    iterator = iter(coords)
    previous_x, previous_y = iterator.next()
    yield int(previous_x)
    yield int(previous_y)
    for current_x, current_y in iterator:
        yield int(previous_x - current_x)
        yield int(previous_y - current_y)
        previous_x, previous_y = current_x, current_y

There is an other advantage to this approach: if the coords parameter is empty, your approach using coords[0] and the first one building a list using iterator.next() will crash raising either an IndexError or a StopIteration.

This generator can easily be fed to the list constructor or a for loop and won't crash; producing either an empty list or not entering the loop.

Lastly, you could drop manually managing the previous/current thing by using itertools.tee which is the key feature of the pairwise recipe:

from itertools import tee, izip

def parse_coordinates(coords):
    prev, cur = tee(coords)
    x, y = cur.next()
    yield int(x)
    yield int(y)
    for (previous_x, previous_y), (current_x, current_y) in izip(prev, cur):
        yield int(previous_x - current_x)
        yield int(previous_y - current_y)


I'd say there is two major issues in your code.

First one is that main loop which is very unclear, many if statements, filled with continue and quit() , this is spagetthi code and it is makes your code harder to read, so harder to debug, because that jumps everywhere.

The second one is the lack of OOP design, which could be very adapted to this case. Games are usually developped with strongly object oriented languages (Unreal engine uses C++ and Unity uses C# among others) because of the strong interactions between components, and a very favorable context to abstraction and modularity. To be fair, that's not really needed for short games like rock paper scissors but it prevents you to scale the game further.

There is few design improvements I suggest you:

Split your code into functions, first one could be the game winning condition that should be used in your game loop to avoid unwanted infinite loops, common with constant conditions like while True:. Replace this statement instead by while has_game_ended():, with has_game_ended looking like:

    def has_game_ended(player_score: int, ia_score: int) -> bool:
        if player_score == 3 or ia_score == 3:
            print("Game over: {} won!".format("player" if player_score == 3 else "AI"))
            return True
        return False

Then use an enum to list you moves to make them easier to reuse in your code (PAPER makes more sense than 1) and enable comparison using operator overload, note that this is a tricky comparison specific to game rules.

from enum import Enum

class Move(Enum):
    PAPER = 1
    ROCK = 2
    SCISSORS = 3

    def __lt__(self, other):
        return (self is Move.ROCK and other is Move.PAPER) or (self is Move.Paper and other is Move.SCISSORS) or (self is Move.SCISSORS and other is Move.ROCK)

Now you can write:

>>> player_choice = Move.PAPER
>>> ia_choice = Move.ROCK
>>> player_choice < ia_choice
True

and something like

player_score = player_score + int(player_choice > ia_choice)
ia_score = ia_score + int(ia_choice > player_choice)

This works well because it's not comparing two integers anymore, it's comparing two Move, which makes all the difference thanks to operator overloading.

Avoid quit() in your scripts, it totally cuts the code flow and doesn't allow nice error handling, prefer instead loop conditions or try except statements with customized Exception for unexpected behaviors (for example when you use invalid command, as in the example below).

def WrongCommand(Exception):
    pass

if __name__ == "__main__":
    try:
        play()
    except WrongCommand:
        print("Invalid command, exiting program...")


jQuery form preview using the Instagram plugin

//$(document).ready(fn) can be shortened to $(fn)
//you can use it to avoid global scope pollution so we place everything in here
$(function () {

  //IDs are unique, so we drop input
  //cache values that are static and used more than once
  var instagramHashtag = $('#instagram_hashtag_hashtag');
  var pattern = /(^#|\s#)([a-z0-9]+)/gi;
  var instaContainer = $('.instagram');
  var timer;

  function doneTyping(tags) {

    //why create the timer check? besides, if the function was called and
    //tags was blank, the loop wouldn't run since there are no matches

    //these variables are only used here, so declare them in here
    var tagsa = tags.match(pattern);
    var length = tagsa.length;
    var i = 0;

    while(i < length) {
      instaContainer.instagram({
        hash: tagsa[i++].replace('#', ''),
        clientId: 'instagramclientid',
        show: 4
      });
    }
  }

  //use jQuery on, which accepts a map of events
  //that way, you write the selector part only once
  instagramHashtag.on({
    keypress: function () {
      if(timer) clearTimeout(timer);
      timer = setTimeout(function () {
        doneTyping(instagramHashtag.val());
      }, 350);
    },
    blur: function () {
      doneTyping(instagramHashtag.val());
    }
  });
});