Imports

import java.io.*;
import java.util.*;

It's more common to import just what you need.  E.g.

import java.io.Scanner;

Then a reader can easily see what your dependencies are.  Many IDEs will manage dependencies for you.

Naming

public class Candie{

The more common spelling is

public class Candy {

When I first read this problem I was wondering why the children needed candles.

The space between Candy { won't matter to the compiler but makes it easier for humans to read.

 static int candieCalculator(int[] numbers) {

As a general rule, objects and classes get noun names (e.g. Candy) while methods get verb names.  Consider

 static int calculate(int[] ratings) {

We already knew that this involved Candy, so we don't have to say that again in the method name (although you could).  An even better name in this case might be apportion, as that better reflects what we are doing with the candy.  We are apportioning them between students.  We do have to calculate that apportionment, but apportion seems a more specific (less generic) name.  And if we name it apportion, we can still name another method calculate.

Similarly, numbers is a pretty generic name.  In this case, we know that the numbers represent a "rating score" for each student, so let's base the name on that.  E.g. ratings, scores, or ratingScores.

Don't Repeat Yourself

        if (i==0) {
            if (numbers[i] > numbers[i+1]) {
                result++;
            }
        }
        else if (i==len-1) {
            if (numbers[i] > numbers[i-1]) {
                result++;
            }
        }
        else {

            if (numbers[i] > numbers[i+1]) {
                result++;
            }

            if (numbers[i] > numbers[i-1]) {
                result++;
            }
        }

This is longer than it needs to be.  You currently check for each edge condition and then apply a general condition if they aren't true.  Instead, consider the real problem:  if i == 0, you don't want to subtract from it as the index would be out of bounds.  So you can just say

        if (i + 1 < ratings.length) {
            if (ratings[i] > ratings[i+1]) {
                result++;
            }
        }

        if (i > 0) {
            if (ratings[i] > ratings[i-1]) {
                result++;
            }
        }

In the typical case, you'll do the same number of comparisons as previously.  The only time you do more is if i is equal to 0.  But you can make that back by getting rid of

    if (len==1) {
        return 1;
    }

As the new code will handle that case.  This will do two extra comparisons in that case, but that shouldn't matter as that case is pretty fast regardless.

Correctness

I don't believe that this returns the desired result for all inputs.  Consider

  7 1 2 3 4 5 6 7

This has an easy solution of \$1+2+3+4+5+6+7 = 28\$ but your code will instead return 13.  But that's not enough candy!  We can easily see that the first child must have a piece.  So the higher rated second child needs two pieces, etc.

Dynamic Programming

I would agree that this is not dynamic programming.  As a general rule, dynamic programming is a system to reduce recursive calculations.  This doesn't recurse at all.

You should think about how to express the problem in terms of subsets of the problem.  For example, if you know the apportionments for all the children less than i and greater than i, then what is the apportionment for i?

If you figure that out, you will have fixed the bug.

Hint:  what do you do if the apportionment for i is 0?  Obviously that's an incorrect answer to the problem.  So what should you do in that case?


Look here it is already tested on live projects error catcher.
Fatal errors can be catch only by 'register_shutdown_function'
You do not track uncatched Exceptions, it can be done by 'set_exception_handler'
If code runout all memory it will not able to log error, but if you does not catch Fatal errors so it is not your case.


Codeigniter calling conditional data retrieval model method from controller

Readability and Usability

Your function is indeed quite generic, which does give you a lot of power in your controller. But I would agree with you, that this is not necessarily a good thing.

Just looking at your controller line, I would have no idea what it does, because it's impossible to know what all the NULL values stand for. Apart from it being hard to read, I would also think that this function is hard to use. I would have to look up the order of the parameters each time when I write a query.

Need for Flexibility

The first thing I would check is if your models actually need to be this flexible. Because that way, you do blow up your controller a bit, as it has to make the decision of what to actually extract.

In your example, you don't actually need the limit, offset, or order_by, so if it's not needed elsewhere (and probably also not needed in the future), think about removing it.

I'll just assume that you do indeed need the flexibility, but it's something to think about.

Two Possible Alternatives

I could think of two different ways to improve your code, one offering reduced flexibility, the other keeping the existing flexibility and increasing readability.

Option 1

The first option is to write additional functions which access your find_all function internally:

function find_all_sorted($order_by) {
    // call find_all
}

function find_from_to($from, $to) {
    // call find_all
}

// [...]

You loose some flexibility (or you have to add quite a lot of methods to get the same flexibility), but your controller will be slimmer. If you can cover all needed use-cases with a couple of these methods, this might be the way to go.

Option 2

The second possibility is to expose the database methods to the outside as you did with the where method. You will have the same flexibility as before, but your code will be more readable.

If you don't want to expose the actual methods of the database (which would be cleaner, as the controller shouldn't actually care about the way the database is accessed), you could also just add setters to it:

function from_to($from, $to) {
    $this->from = $from;
    $this->to = $to;
}

function order_by($order_by) {
    $this->from = $from;
    $this->to = $to;
}

function select($fields) {
    $this->fields = $fields;
}

function query() {
    // call find_all with the set parameters, like you did before from the controller
}

In the controller, it would then look like this:

$this->request_form_model
    ->select(['title', 'id', 'service_category_id'])
    ->where('status', Request_form_model::STATUS_ON)
    ->from_to('1', '10')
    ->order_by('title')
    ->query();

Each of the method calls is optional, and it's clear for the reader what the query will return, without looking up the documentation for each method.


Spacing

The usage of (horizontal) space is not consistent, you have a space
after if and switch, but not after else and while.
I would generally use more whitespace to increase the readability, in particular after keywords, around operators, etc. For example

while (answer.length() >= i) {

Scope

It is a good habit to declare variables at the narrowest scope where they are used, and not at the top of the function. This applies for example
to digit and stringDigit, which are only used inside the while-loop.

Input validation

std::stoi(instring, nullptr) silently ignores leading whitespace
and trailing non-digits, that might or might not be wanted.
The pos parameter could be used to check if the complete string
has been converted successfully.

Also std::stoi(instring, nullptr) throws an std::invalid_argument
exception if the input string contains no valid digits at all,
you might want to catch that.

Iterating too far

In

int i = 0;
while(answer.length()>=i){
    switch (answer[i]-'0'){
        // ...
    }
    i++;
}

the last iteration accesses answer[answer.length()], which is
the null character. Even if this causes no harm (answer[i]-'0'
then matches none of the cases) it is probably unintended and you'll
want answer.length() > i instead. (See below for further improvements
of this part.)

Simplifications

The remainder modulo 7 cannot be >= 10, so the while loop
simplifies to

while (in != 0) {
    int digit = in % 7;
    std::string stringDigit;
    stringDigit = '0' + digit;
    answer = stringDigit + answer;
    in /= 7;
}

which can further be simplified to

while (in != 0) {
    char digit = '0' + in % 7;
    answer.insert(0, 1, digit);
    in /= 7;
}

making the stringDigit variable obsolete, and mutating answer
instead of concatenating strings.

Iterating over all valid string indices is better done with a for loop:

for (int i = 0; i < answer.length(); ++i) {
    // ... use `answer[i]` ...
}

But actually you don't need the index, only the characters, and
iterating over all characters in a string can be done more simply
with a range-based for loop (added in C++ 11):

for (char& c : answer)
    // ...
}

The switch statement can be replaced by an array lookup:

std::string blameStrings[] = {
    "\u180E", "\u200B", "\u200C", "\u200D", "\u2060", "\u2063", "\uFEFF"
};
for (char& c : answer) {
    std::cout << blameStrings[c - '0'];
}

(You can probably choose a better name for the array, but I have no
idea what those strings stand for.)

Get rid of the intermediate string storage

Your code computes answer as the base-7 representation of the
input number, and then iterates over the characters in that string.

The conversion from digits to characters in a string and back to
digits can be avoided by storing the integer digits in a vector
instead. And instead of prepending additional digits, we can append
them (to avoid that memory needs to be moved repeatedly) and then iterate
over the result in reverse order:

#include <vector>

// ...

int in = std::stoi(instring, nullptr);
std::vector<int> digits;
while (in != 0) {
    digits.push_back(in % 7);
    in /= 7;
}

std::cout<<"!!/blame\u180E ";
for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
    std::cout << blameStrings[*it];

}
std::cout<<"a\n";


Classes for background layer and parallax effect

Just a couple nit-picky things...

InitialOffsetOf: should instead be initialOffset:

withScrollSpeed: should just be scrollSpeed:

I'd probably also add factory methods.  When I'm writing code, no class is complete until it has its factory methods.


Improving efficiency and flow by changing subroutine orders

1) What is this line supposed to do?

%comspec% /c exit %0%

I can almost guarantee it is not doing what you think. The most it can do is set the ERRORLEVEL. However, The EXIT command expects a numeric argument, but you pass %0%. The EXIT command returns 0 if it does not receive a numeric argument.

I doubt you have a variable with a name of "0", so the EXIT command sees a string literal value of %0%, which is non-numeric. It consequently returns 0 every time.

Your very next command (FINDSTR), is an external command, so it will set the ERRORLEVEL anyway. There is no need to initialize it.

2) It is generally a good idea to enclose SET assignments in quotes. This guards against poison characters, and inadvertent trailing spaces. (There are some exceptions, but it is a good rule of thumb).

3) It is generally a good idea to always enclose file paths in quotes if a portion is a variable. You never know if the variable may contain spaces or poison characters. The %TEMP% value normally does not have spaces, but it certainly could.

4) There is no need to delete "%temp%\rdcto.txt" when you immediately turn around and recreate it. You can simply redirect using overwrite mode (>) instead of append mode (>>). This will guarantee you start out with a fresh file each time.

5) Why do you write the value of %MailDst% using a FOR statement? You can simply echo the value directly.

>"%temp%\rdcto.txt" echo %MailDst%

6) You do not need to create an :end label and GOTO that label. Instead you can do either of the following: goto :eof or exit /b. They are identical, and neither form requires an explicitly declared label. The only difference is that exit /b can take an optional argument specifying the returned errorlevel.

7) You should encapsulate the logic for writing an email into a subroutine that accepts the variable portion as arguments. It reduces the amount of code, and eases maintenance.

8) I've simplified your ERRORLEVEL logic by using an extra variable to store the return code. I also make use of the conditional && and || operators with FINDSTR - I find them to be more convenient then checking the ERRORLEVEL. But I didn't use them with WinSCP because the logic is a bit complex.

Note that if the last command within a &&( successCommands ) block raises an error, then it would cause the ||( errorCommands ) block to fire. That is why my :sendMail routine explicitly exits with a return code of 0 (success).

Using the above principles, I would write the code as follows:

SET "MailSrc=downloader@mydomain.com"
SET "MailSrcName=Automated FTP Process"

SET "MailDst=successful_code@mydomain.com"
SET "FailMailDst=failed_code@mydomain.com"

SET "OKMailSub=Files Have Been Moved"
SET "NoFileMailSub=Files Not Present - Maybe Next Time"
SET "FailMailSub=An Error Occurred!"

SET "LOG=WSCPLog.txt"

IF EXIST "%LOG%" DEL "%LOG%"
START /WAIT WinSCP.exe /console /script=WSCP-GetC.txt /log="%log%"
SET "RTN=%ERRORLEVEL%"
FINDSTR /C:"Test_File.ext: No such file or directory" "%LOG%" && (
  CALL :sendMail "%MAILdST%" "%NoFileMailSub%"
) || (
  IF %RTN% EQU 0 (
    CALL :sendMail "%MAILdST%" "%OKMailSub%"
  ) ELSE (
    CALL :sendMail "%FailMailDst%" "%FailMailSub%"
  )
)
EXIT /B

:sendMail
>"%temp%\rdcto.txt" ECHO %~1
"%~dp0sendmail.exe" /TO="%temp%\rdcto.txt" /FROM=%MailSrcName% ^<%MailSrc%^> /REF=%~2 /MESSAGE=%log% /HOST=mail.mydomian.com
EXIT /B 0

Other possible changes:

I didn't make any of the changes below because you said your code was working, and I don't know those programs enough to guarantee the changes are an improvement.

A) I don't see why you run WinSCP via START. I believe you could simply use:

WinSCP.exe /console /script=WSCP-GetC.txt /log=%log%

B) Your sendmail arguments look very suspicious to me. Normally values that contain spaces should be enclosed in quotes. Note that the :sendMail routine above preserves the lack of quotes by using %~1 and %~2 instead of %1 and %2.

C) I don't know WinSCP, but I suspect it will overwrite any existing log file, in which case you could remove the prior DEL command.


Using namespace std: I've already mentioned this in the comments.  Although it's not a huge deal for small programs such as this, it's still not a good habit to develop.
While loop: Put std::cin << ch both before the loop and after the switch.  You could also change the loop condition to

(ch == '1' || ch == '2' || ch == '3' || ch == '4')

if you really want to make sure that the program will only proceed with a valid input.    Other than that, your original condition is okay.
std::cin: You don't need std::cin.get() alongside std::cin >>.  Just use std::cin >> for char inputs.  However, you'll need a std::cin.ignore() before each getline since you're doing a char input (menu prompt) before a std::string input in your cases.  For case 4, keep a consistent getline for the filename input and put an ignore before it.

Also, you don't need any cins after your cases since your while loop will always ask for an input for ch.  I do see what you're doing with your outputs in your cases, but you don't need to do that.  Just let your cases do their things and go straight to the menu and/or prompt again.
Filename input: You should provide validation for the filename input.  If the user enters in invalid filename, what should happen?  Consider implementing a loop asking the user for a valid filename as long as such file cannot be opened.  With the provided code here, it's a bit tough for me to give a piece of example code for that.
Functions: You could nicely organize your switch statements by putting the body code into functions.  Just name them as they appear in your menu.  Call each one in your respective cases, along with the breaks.  Also, it might be better to have separate procedures for add/remove.
Exit: You don't really need exit(EXIT_SUCCESS) here if the program will always terminate successfully.  You also don't need system("cls"), so just leave it out.  If you're doing that just to prevent the menu from appearing before each prompt, just pt it before the while loop.


Compare two version numbers in the form Major.Minor.Patch.Build to see if one is less than or greater than the other

First of all, have you looked at LooseVersion and/or StrictVersion from distutils.version?  They might already provide you with exactly what you need.

General “PEP-8” Comments:

You should have a blank line after your import, after class Version, and after the def __repr__(self) method.  The blank-lines inside of __lt__ and __gt__ functions before the else: clause are inconsistent.

Your class and methods could benefit from """doc strings""".

The class members Major, Minor, Patch and Build should all be lower case.  Only class names should begin with capital letters.  Since the members should be private to the class, they should also be prefixed with an underscore.

The constructor will silently fail if type(ver_str) != 'string' is ever False, and then the instance becomes useless, as the members which are required in every other method of the class become reference errors.  There is no need to check if ver_str is a string; just try to split it, and convert the parts to integers.  If you haven’t passed in a string, the split or conversion to integers will cause an exception.  (You could add a check that the split produces exactly 4 parts, to reject a version such as "1.2.3.4.5.6".)

Fortunately (as noted by @200_success in the comments), type(ver_str) will never equal 'string', because type(...) doesn't return strings; it returns types.  The code only works because the test inverts the condition, and reads != when the intention is for the type to == a string.  The correct test would be closer to if isinstance(ver_str, str):, but again explicit type checking is an anti-pattern.

Without the explicit type checking, and using a more functional approach, the constructor could be written as a one line method.  As a side-effect of the deconstruction assignment, the version string must contain exactly 4 parts or an exception will be raised.

def __init__(self, ver_str):
    self.Major, self.Minor, self.Patch, self.Build = map(int, ver_str.split('.'))

printme() is unused and could be deleted.  If you don’t wish to delete it, at least name it using snake_case to make it more readable: print_me().  You could write the function as simply print(repr(self)) to avoid duplicating code.

__repr__(self) should actually return a string like Version("1.2.3.4"), not the string "1.2.3.4" to conform to the repr() contract.  What you have written would make a great __str__(self) method though, and you could then implement __repr__(self) using the str() method.

Inside def main(...):, you are using argv.  This is a different argv, shadowing the one you import from sys using from sys import argv.

You should avoid shadowing the imported name, by using:

import sys

# ....

if __name__ == '__main__':
    main(sys.argv)

There is no need to exit(-1) from main(), since the program will terminate anyway immediately.  exit() will terminate the Python interpreter, which can be unexpected, and can cause resources to not be properly closed.  A unit test framework will abruptly terminate, preventing recording of the test results, and preventing other unit tests from running.  In short, don’t ever use exit().  Ever.

Since you are explicitly writing for Python 3.7.0, you can use f-strings.  This means you can replace many of your .format(...) calls with a more compact, readable representation where the substitution location and value are combined.  Ie:

    print("{} < {}: {}".format(ver_1, ver_2, ver_1 < ver_2))

could become simply:

    print(f"{ver_1} < {ver_2}: {ver_1 < ver_2}")


I couldn't spot any problems with your implementations, but caveat lector: I'm not a cryptography expert, so take that with an appropriate pinch of salt.

I'm also concerned about the output:

$ python reinvent.py
msg = CTR mode lets yo▒B▒▒▒c▒?▒N▒▒w▒▒ap▒9▒uz▒▒▒3▒▒▒o▒V_M▒▒A
msg = Always avoid the▒?A▒▒r    ▒ά

It looks as if the first block has been decrypted correctly, and then it all falls over. Probably a bug, but I didn't dig into what's causing it.

Edit: Turns out this was an indentation problem – the code as posted had lost some indentation, and I guessed wrong when I tried to add it back.

The biggest problem with this code is the lack of docstrings and comments. Especially when you're dealing with cryptography – it's important to explain why you wrote the code you did, and how it relates to the original problem. This makes code easier to read, review and maintain – and would probably make it much easier to spot the bug above.

A variety of comments below.

IVCounter class

There should be a docstring explaining what this class represents, and what sort of values it expects as input.  I had lots of fun hassle trying different inputs and hitting a variety of errors before I got it working.
Your __repr__ method is mutating the internal state of the object – that seems like a really bad idea. The usual use case for repr() is as a debugging tool; changing the instance you're trying to debug will be a bundle of laughs.

Here's an alternative repr you could use:

def __repr__(self):
    return '%s(%r)' % (self.__class__.__name__, self.value)

This returns a string that could be eval'd to get something equivalent to the current object, which is a much more conventional use of this function.
I'm not sure why you have a string method. It would be better for callers to access self.value directly, and if you want a string representation of an object, you should define __str__ instead.
What happens when the counter overflows? You get a nasty TypeError:

>>> x = IVCounter('\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe')
>>> x.increment()
'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
>>> x.increment()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in increment
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Odd-length string

You should think about how you want to handle an overflow like this – at the very least, you should wrap the exception and provide a more intelligible error message.

CTR class.

Should subclass from object.
Avoid single letter variable names where possible; try to prefer descriptive and expressive names. For example, __init__(self, key) instead of __init__(self, key). Or for block in blocks.
In your __strxor method, you have repeated code – the only thing that changes is the arguments to zip(). Would be good to cut down that repetition.
The variable name lenght is misspelt in the definition of the __split_len method.
When I hear the word cipher, I think of things like AES, whereas you seem to be using it to describe a message text. That's a little confusing – docstrings would help.
In the decrypt() method, rather than:

self.IV = IVCounter(blocks[0])
blocks.remove(blocks[0])

you could just use:

self.IV = IVCounter(blocks.pop(0))

which will remove the item and extract it.

Misc

You appear to be importing Crypto.Cipher.AES twice. Why?


Welcome to Code Review!

Bugs

For every node you insert, next is null.

Encapsulation

Your code is written almost exclusively using C features.  First things first, instead of using a single global variable, use a class to encapsulate the data structure.

class Stack {
public:
    Stack() = default;
    Stack(const Stack&) = delete;
    Stack& operator=(const Stack&) = delete;
    ~Stack();

    void push(int data);
    void pop();
    void display() const;
    bool empty() const { return top == nullptr; }
private:
    struct Node {
        int data;
        Node* prev;
        Node* next;
    };
    Node* top = nullptr;
};

The way the function works is exactly the same.  A destructor should be provided to systematically handle memory deallocation:

Stack::~Stack()
{
    while (!empty()) {
        pop();
    }
}

Now Stack can be used like a normal C++ container:

int main()
{
    Stack stack1;
    stack1.push(3);
    stack1.push(1);
    stack1.push(4);
    stack1.display();
    stack1.pop();
    stack1.display();

    Stack stack2;
    // stack2 is a stack independent from stack1
} // the existing nodes are automatically freed when the main function returns

Miscellaneous

#include "..." is for your own headers.  For standard headers, use #include <iostream>.

using namespace std; at global level is considered bad practice and should be avoided because it defeats the purpose of namespaces and introduce name clashes.  You will have trouble using identifiers as common as size or count.  See Why is using namespace std; considered bad practice?

A class can be referred to directly with its name.  You don't need to add struct.  So instead of struct Node*, just say Node*.

Instead of NULL, use nullptr for null pointer constants.

It's more common to write functions in this way:

bool isempty()
{
    // ...
}

Instead of declaring a variable uninitialized and then assigning to it immediately, use initialization.

The push and pop functions are way too convoluted.  Remember you are implementing a stack, not a complete doubly linked list.  Aggregate initialization with new can be used to simplify the code:

void Stack::push(int value)
{
    top = new Node{value, top, nullptr};
    if (auto old = top->prev) {
        old->next = top;
    }
}

void Stack::pop()
{
    if (empty()) {
        throw Stack_underflow{};
    }
    delete std::exchange(top, top->prev);
}

Note that heap overflow is not something you need to worry about because new already throws an appropriate exception on allocation failure.  Also, do not free memory allocated by new with free.  This is undefined behavior.  Use new with delete instead.

When an error happens, throw an exception instead of printing a message and then exiting or even continuing execution.  There is not always an open stdout file, and if it exists, that's now how everyone wants error to be handled.  Throwing an exception allows the user to handle it in the convenient way.

The while loop in the display function should have been simplified with a for loop:

for (Node* itr = top; itr; itr = itr->prev) {
    std::cout << itr->data << '\n';
}

Note that std::endl should be avoided when you don't need the flushing semantics.  Unnecessary flushing can cause performance degradation.  See std::endl vs \n.

return 0; can be omitted in a main function.

Refined version

Putting everything together:

#include <iostream>
#include <stdexcept>
#include <utility>

struct Stack_underflow :std::exception {};

class Stack {
public:
    Stack() = default;
    Stack(const Stack&) = delete;
    Stack& operator=(const Stack&) = delete;
    ~Stack();

    void push(int value);
    void pop();
    void display() const;
    bool empty() const { return top == nullptr; }
private:
    struct Node {
        int data;
        Node* prev;
        Node* next;
    };
    Node* top = nullptr;
};

Stack::~Stack()
{
    while (!empty()) {
        pop();
    }
}

void Stack::push(int value)
{
    top = new Node{value, top, nullptr};
    if (auto old = top->prev) {
        old->next = top;
    }
}

void Stack::pop()
{
    if (empty()) {
        throw Stack_underflow{};
    }
    delete std::exchange(top, top->prev);
}

void Stack::display() const
{
    for (auto it = top; it; it = it->prev) {
        std::cout << it->data << ' ';
    }
    std::cout << '\n';
}

int main()
{
    Stack stack;
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    stack.push(5);

    stack.pop();
    stack.display();
    stack.pop();
    stack.display();
}

Output:

4 3 2 1
3 2 1

(live demo)


It isn't clear to me what you are asking. However, I was able to update your code and run it:

use std::thread;

struct PrimeIncrement(i64);

impl Iterator for PrimeIncrement {
    type Item = i64;
    fn next(&mut self) -> Option<i64> {
        self.0 += 4; // What do you mean "integer overflow"? ^_^
        Some(self.0)
    }
}

fn main() {
    let path_1 = thread::scoped(|| {
        PrimeIncrement(3).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });
    let path_2 = thread::scoped(|| {
        PrimeIncrement(5).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });

    let a = path_1.join();
    let b = path_2.join();

    println!("{}", 2 + a + b);
}

fn prime(n: &i64) -> bool {
    match n {
        &1 => false,
        &2 => true,
        &3 => true,
        n if *n % 2 == 0 => false,
        _ => {
            let max = (*n as f64).sqrt() as i64 + 1;
            !(2..max).any(|i| *n % i == 0)
        }
    }
}

The main changes were:

Removing Unfold, as it isn't stable in the 1.0 beta.
Using thread::scoped instead of a Future.
Using i64 instead of int

Update for Rust 1.3

The thread::scoped API was found to have soundness problems and has been deprecated. In this case, thread::spawn is powerful enough, so I've replaced that:

use std::thread;

struct PrimeIncrement(i64);

impl Iterator for PrimeIncrement {
    type Item = i64;
    fn next(&mut self) -> Option<i64> {
        self.0 += 4; // What do you mean "integer overflow"? ^_^
        Some(self.0)
    }
}

fn main() {
    let path_1 = thread::spawn(|| {
        PrimeIncrement(3).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });
    let path_2 = thread::spawn(|| {
        PrimeIncrement(5).filter(prime).take_while(|&n| n <= 7919).fold(0, |a, b| a + b)
    });

    let a = path_1.join().unwrap();
    let b = path_2.join().unwrap();

    println!("{}", 2 + a + b);
}

fn prime(n: &i64) -> bool {
    match *n {
        1 => false,
        2 => true,
        3 => true,
        n if n % 2 == 0 => false,
        n => {
            let max = (n as f64).sqrt() as i64 + 1;
            !(2..max).any(|i| n % i == 0)
        }
    }
}

Additionally, I now match on *n, which avoids the need to have quite as many dereferences.


Nice exercise!

  But the big decision I needed was how to store the 3 elements of state

  The results
  The Dijkstra scores of the points not yet turned into results; and
  The set of points already found (i.e. the keys of the results)

An important feature of the algorithm is that the scores are kept in a min-priority-queue. Keeping the scores in a vector requires O(n) cost at every step. Also note that having using a priority queue API would simplify the mainLoop, as the operations on a vector are somewhat low-level wrt the task (remove the minimal value from the queue, if it exists).

The explored nodes form a set, to it'd be indeed more appropriate to use IntSet or Set. Whenever you use elem with [], it's a sign to think of a better data structure (unless you know the list length is bounded by some small constant).

Regarding the results, we know we add each node only once, so [] seems to be OK. Adding is then O(1) and whatever manipulation we want to do at the end can be deferred until then.

I don't think there is anything wrong with your approach to keeping the state. While you could use the State monad (or perhaps RWS where the reader part would be the graph, the writer part the results and the state the scores), it'd force (as any monad) more imperative, sequential style. And it'd cloud which part of the code needs what information. And having the value that's being modified as the last argument (like ... -> Results -> Results) allows to use point-free style where appropriate.

You might want to check if your mainLoop is tail-recursive.

Perhaps one way how to make mainLoop have less imperative feel would be to check for the termination condition first (which isn't such a bad idea, if the input is an empty graph or so). Something like:

mainLoop gr = loop
  where
    loop exs ds res | ifQueueEmpty ds = res
                    | otherwise =
      let ...
      in loop exs' newDs res'

There are multiple reasons for separating the loop in an inner function. One (that doesn't really apply here) is that by having the top-level function non-recursive, it allows it to be inlined. The other is that this clearly expresses what changes during the loop and what not.

Some more remarks:

I like that you included types for all functions, including helpers, that's often very convenient. And that you gave descriptive names to the types.

From the types it's not that obvious how are graphs represented. If an edge is

type Edge = (NodeName, Dist)

what is the other node it connects? My guess is that the other node is determined by the index of the [Edge] list in the vector. In any case, this should be documented in comments for the types.

Also, a question comes to my mind, why the graph is a Vector, but the list of edges is a []?

Regarding comments, I'd suggest you to use the Haddock syntax, as it's then very easy to generate documentation from the code.

Also it's not clear what Nothing means in the vector. It could mean that an element hasn't been explored yet (infinite distance), which would work well with manipulating distances, but it seems to be used for elements that have been removed from the queue. I'd rather use a queue that allows proper removal of elements, and use Dist that deals with infinity (see below)

For representing distances it'd be useful to have a separate data type, something like

newtype Dist = Dist (Maybe Int)

with the appropriate Ord instance and supply the minimum monoid instance where mempty is the infinity and mappend takes the minimum of its arguments. For example process could be greatly simplified by this.

The comments are sometimes somewhat misleading, for example in Nothing is interpreted as 0 otherwise it's not clear what "otherwise" means.


Various things about your code seem odd.

Field level values

There's no reason for these variables to be declared at a class level, you only ever use them within a single function:

private NetworkStream sendStream;
private NetworkStream recvStream;

btnSend_Click bug

If the user clicks on the send button, before they've clicked on the Listen button, your client member won't have been initialised so will throw an exception when you do:

if (client.Connected)

Listen/Read Thread

It looks like you're only expecting a single client (your listen thread doesn't contain a loop to accept more than a single connection).  Rather than spinning up another thread to perform the receive functionality, you might as well be doing it in the same thread that you performed the listen on.

Listen Management

Your listen code doesn't check the state of the Server before calling start.  If you click it twice, it seems likely that this is going to cause a problem.

Exception Handling

You don't have any exception handling around your read/write calls.  TCP can be a bit of a pain at times, depending upon how the connection has been shutdown it may throw various exceptions rather than just returning 0 from the read call.  It's also worth remembering that since you're accessing the socket from multiple threads it can change state between your is connected call and your write operation.


I am currently using the RK-4 method to update position

Firstly, the naming is unhelpful here. A name like RK4_1 implies that the method does the quadrature. I think that function is really dx_dt, RK4_2 is really dvx_dt, and there would be room to pull out a function like

def RK4_step(t, x, dx_dt, dt):
    k1 = dt * dx_dt(x, t)
    k2 = dt * dx_dt(x + k1 / 2, t + dt / 2)
    k3 = dt * dx_dt(x + k2 / 2, t + dt / 2)
    k4 = dt * dx_dt(x + k3, t + dt)
    return x + (1/6) * (k1 + 2 * k2 + 2 * k3 + k4)

But secondly, RK4 is completely overkill here. If we inline

@jit(nopython=True)
def RK4_1(x, vx):
    return vx

@jit(nopython=True)
def RK4_2(x, vx):
    return 0

@jit(nopython=True)
def iterate(x1, x2, vx1, vx2, col):
    k1 = dt*RK4_1(x1, vx1)
    k2 = dt*RK4_1(x1 + k1/2, vx1)
    k3 = dt*RK4_1(x1 + k2/2, vx1)
    k4 = dt*RK4_1(x1 + k3, vx1)
    x1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)

    ...

    k1 = dt*RK4_2(x1, vx1)
    k2 = dt*RK4_2(x1, vx1 + k1/2)
    k3 = dt*RK4_2(x1, vx1 + k2/2)
    k4 = dt*RK4_2(x1, vx1 + k3)
    vx1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)

we get

def iterate(x1, x2, vx1, vx2, col):
    x1 += dt*vx1

    ...

    vx1 += 0

It seems that it would be much quicker to solve simultaneous linear equations to work out when the collision will happen rather than to use quadrature. In fact, I had a go, and the actual simulation takes less than a second for N = 5.

  My code shows that I have tried to use Numba to speed up the runtime, but that doesn't seem to be helping.

The jit is on the wrong parts. I added some debug printing and observed that it slowed down over time, at which point I very quickly spotted the real problem:

    x1arr = np.append(x1arr, x1)
    x2arr = np.append(x2arr, x2)
    y1arr = np.append(y1arr, y1)
    y2arr = np.append(y2arr, y2)
    vx1arr = np.append(vx1arr, vx1)
    vx2arr = np.append(vx2arr, vx2)
    colarr = np.append(colarr, col)

This is copying the entire array every time, so the length of a step is proportional to the number of steps taken.

Solution: use normal lists rather than numpy arrays. numpy is not a panacea: it's good for parallel processing, but that's not what you want here.

However, the one advantage that numpy arrays give you here is that they don't have length bounds. In testing with N = 3 using normal Python lists I got a memory error after slightly more than 245 million steps and 3140 collisions. It might need a 2D structure to handle the large quantities of data. Of course, that doesn't prevent the extremely likely problem of the plot running into memory problems too. A complete structural rethink may be necessary.

If you do decide to implement RK4, it's more correct to do a single multi-variable quadrature rather than multiple single-variable ones. Here is where there is a good reason to use numpy arrays. What I mean by multi-variable quadrature is something like

k1_x, k1_vx = dt * RK4(x, vx), dt * RK4(vx, ax)
k2_x, k2_vx = dt * RK4(x + k1_x / 2, vx + k1_vx / 2), dt * RK4(vx + k1_vx / 2, ax)

etc. (NB For clarity I separated out the variables. For speed you'd put x and vx in a single numpy array).

It makes no sense to start timing before taking the input: the time I take to type 3 and press Enter is not really runtime.

In terms of general readability, the inline mixing of functions and top-level code is not helpful. It's good to put constants like dt at the top, so that when the reader comes to the usage of dt in iterate they've already seen it. The main loop should probably be a function which returns the arrays (or perhaps a single 2D array) with intermediate values; the plot creation should be a function, and then Python best practice is for the "main" functionality to go at the end with a guard:

if __name__ == "__main__":
    N = int(input("Enter an integer N that will determine the mass of the second block: "))
    start = time.time()
    data = generate_collisions(N)
    plot = graph_collisions(data)
    end = time.time()
    print("Total runtime in seconds:  ", end - start)
    plot.show()


Webapp Substrate script for WordPress on Debian-Nginx

The outer heredoc construct isn't really required.
You do not verify that you have command line arguments.
You do not assign your command line arguments to the variable domain.
You use the variable domain when it is uninitialised.

You make a number of assumptions, any one of which could bite you hard.

You assume that the nginx package has been installed and that it has created the paths and other things you require.
You assume that the MySQL packages have been installed.
You assume that the certbot package has been installed.
You assume that the /var/www/html directory exists.
You assume that the www-data user exists.
You assume that this is the first time that the script has been run for domain. It will have unexpected results if domain already exists.

Think about those assumptions and what would happen if they were incorrect and things didn't exist as you expect.

Your variable names are not good - why, for example, is the database user's password assigned to waps and not something like dbpassword?

It's not clear if you are planning on passing more than one domain to the script per invocation. If you only plan one domain per invocation you do not need the for loop.

You assume that all of your commands will complete correctly. You really should check the exit status of those that could reasonably be expected to fail. For example the wget could fail for many reasons. If it does then everything after it should not be run. What happens if certbot fails or mysql or tar or ...

Your chown -R... command assumes that nothing else is installed in /var/www/html or that everything installed there should be owned by www-data, this may not be the case, use /var/www/html/${domain}. Your find commands are the same.

Your find commands will exec chmod for every file found. It is more efficient to use find ... -exec {} + which optimises the size of the command line and reduces the number of execs.

  I especially hope to learn how I could shorten this code in at least 10 rows, if at all.

How sweet, I can see it being considerably larger.


The thing that leaps out at me is that the normal way to avoid redirecting valid files to the pageLoader.php handler is to use RewriteCond like so:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . PlugCMS/public/pageLoader.php [L]

Doing it this way means that you can easily add a new file to the site without having to add to the RewriteRule to avoid it matching.

You usually shouldn't have to use the slug hack to get the original URL.  See here for more discussion.

You may want to set a RewriteBase for this.  Perhaps

RewriteBase /PlugCMS/

Which would make your rewrite rules a little shorter.  See here for more discussion.


Is there a better way to write this jQuery UI effect animation?

You could create a function that will set up the animation of text or color and then just call it a few times to set up your animation:

$.fn.animateIt = function(color, text) {
    var that = $(this);
    if (text) {
        that.queue(function(next) {
            that.text(text);
            next();
        });
    }
    if (color) {
        that.animate({
            color: color
        }, 500);
    }
    return that;
};

$textarea.animateIt('rgb(41, 41, 41)')
    .animateIt('#FFF', 'Please enter your reply here')
    .delay('1000')
    .animateIt('rgb(41, 41, 41)')
    .animateIt('#a7a7a7', body)
    .queue(function(next) {
        $textarea.focus().putCursorAtEnd();
        next();
    });

Gets rid of the nested functions.

http://jsfiddle.net/petersendidit/LYsQM/1/


permutation -> permutationHelper -> permutation -> ...

As @MartinR pointed out,
the permutation and permutationHelper functions calling each other are confusing.
In fact, permutation is actually pointless,
as it does nothing but call permutationHelper.

To give permutation some purpose,
you could do this:

Make permutationHelper call itself instead of permutation
Drop the array length parameter from permutation: it can derive it from the array it receives, and pass that to permutationHelper

Why Integer[] instead of int[] ?

In the posted program, there's really no need for Integer objects.
You can work with int[], which is slightly lighter.

Code duplication

There are several duplicated elements in this code:

permutation(integerArray, currentPosition - 1);

if (currentPosition % 2 == 0) {
    swap(integerArray, i, currentPosition - 1);
} else {
    swap(integerArray, 0, currentPosition - 1);
}

First of all, the currentPosition - 1 is duplicated.
It would be good to store it in a local variable.

Secondly, swap is called with almost the same parameters, except one.
This could be expressed more compactly using a ternary operator.

int nextPosition = currentPosition - 1;
permutation(integerArray, nextPosition);
swap(integerArray, currentPosition % 2 == 0 ? i : 0, nextPosition);

Initializing arrays

A simpler way to initialize arrays is using { ... }, like this:

int[] a = { 1, 2, 3, 4 };


Method to delegate command to other methods

Spread Similar to Mohammed's answer, but without mutation and with spread syntax, which I find easier to read than .apply, you can do something like:
const executeModeration = async (command, channel) => {
    await moderation[command.command](...command.parameters);
}

Default parameters
You use a number of conditional operators when calling functions, eg:
.ban(
    channel,
    command.parameters[0],
    command.parameters[1] !== undefined ? command.parameters[1] : ''
);

.timeout(
    channel,
    command.parameters[0],
    command.parameters[1] !== undefined ? command.parameters[1] : 300,
    command.parameters[2] !== undefined ? command.parameters[2] : ''
);

If possible, it would be good to define the methods such that they assign default parameters, rather than having to pass the defaults from up above. For example, for the timeout method, you could define it like:
timeout(arg1, arg2 = 300, arg3 = '') {
}

and then simply pass the spread parameters when calling timeout from the script in your question, and the default parameters will take care of the rest.
If you cannot modify the moderation object's methods, then a DRY way to create these default parameters would be to make an object indexed by command, whose values are functions which need default parameters and call the moderation method. For example, for .ban and .timeout:
const executeModeration = ({ command, parameters }, channel) => {
    const fnsWithDefaultParams = {
        ban(arg1, arg2 = '') {
            return moderation.ban(channel, arg1, arg2);
        },
        timeout(arg1, arg2 = 300, arg3 = '') {
            return moderation.timeout(channel, arg1, arg2, arg3);
        },
        // ...
    };
    return fnsWithDefaultParams[command]
        ? fnsWithDefaultParams[command](...parameters)
        : moderation[command](...parameters)
};

Note that there's now no need for an async function if the function explicitly returns a Promise, like above.


inString() Helper Function - Check if substring is in string

I like YourCommonSense's unconditional casting of $needle as an array.

bumperbox's advice on preg_quote() is good and necessary.

bumperbox's patterns will have the desired accuracy because word boundaries (spelled with an 'a') when used with alternatives (|) must wrap each alternative or the alternatives must be grouped.  Otherwise, if you have a pattern like: /\bdog|cat|fish\b/ then doghouse, category, scat, and blowfish will be unintentionally matched.  (Bad Pattern Demo)  In this case, /\b(?:dog|cat|fish)\b/ takes fewer steps than /\bdog\b|\bcat\b|\bfish\b/.

Capture groups () will not be necessary for this task, so use a non-capturing group (?:).  The fullstring match will contain the substring.  Unnecessary capture groups bloat the output array (although only by one element in this case).

Different from the other answers, I have built in a shortcut to a non-regex method.  The rationale behind this is the general knowledge that regex functions are notoriously/usually slower than non-regex functions.  The cost of building the path to the non-regex processes is minimal -- just 3 conditions, only the 2nd condition uses a function call.  I suspect any gains in performance to only manifest when dealing with rather large haystacks.  Regardless, I think it is worth considering.

My function performs more checks than the others to prioritize building a lean, accurate pattern.

My function will return false or the matched needle string.

*For those who might not know the behavior of alternatives in regex, the match will be the alternative found with the lowest "offset".  Regex will not prioritize matching by the order of the alternatives.

Code: (PHP Demo)

function inString($needle, $haystack, $checkBoundaries = false, $caseSensitive = false){
    $needle=(array)$needle;  // unconditionally cast $needle to be an array

    // conditional shortcut to non-regex method:
    if(!$checkBoundaries && sizeof($needle)==1){
        $needle=$needle[0];  // or current($needle) if not indexed
        if(!$caseSensitive){
            return stripos($haystack,$needle)!==false?$needle:false;
        }
        return strpos($haystack,$needle)!==false?$needle:false;
    }

    // build regex pattern
    foreach($needle as &$word){
        $word=preg_quote($word,'/');  // escape regex-sensitive characters
    }
    $pattern=implode('|',$needle);  // pipe together the alternatives
    if($checkBoundaries){
        if(sizeof($needle)>1){
            $pattern="(?:{$pattern})";  // non-capture group required
        }
        $pattern="\b{$pattern}\b";  // word boundaries required
    }
    $pattern="/{$pattern}/";  // add pattern delimiters
    if(!$caseSensitive){
        $pattern.='i';  // case-insensitive modifier required
    }
    // execute pattern and return string on true
    return preg_match($pattern, $haystack, $matches)?$matches[0]:false;
}

Alternatively, if you are seeking pattern accuracy with fewest function calls here is something new to consider:

Code #2: (Demo)

function inString($needle, $haystack, $checkBoundaries = false, $caseSensitive = false){
    $pattern='\Q'.implode('\E|\Q',(array)$needle).'\E';  // build "literal" alternatives
    if($checkBoundaries){
        $pattern="\b(?:{$pattern})\b";  // word boundaries required
    }
    $pattern="/{$pattern}/";  // wrap with pattern delimiters
    if(!$caseSensitive){
        $pattern.='i';  // case-insensitive modifier required
    }
    // execute pattern and return string on true
    return preg_match($pattern, $haystack, $matches)?$matches[0]:false;
}

Running conditional checks on $checkBoundaries and $caseSensitive is completely unavoidable for this task.  This second method will make just one function call: implode() to complete the pattern!

By utilizing an "escape sequence" (\Q and \E), I was able to remove the foreach() loop and iterated call of preg_quote()!  The addition of the escape sequence seems to have no impact on regex step count; it is just a different syntax.  The effect on the pattern is in some cases a visual improvement, and in other cases a detriment to pattern readability (though I don't think pattern readability is a focus for this task).  The above method wraps each alternative in \Q...\E whether it needs it or not.  To contrast, preg_quote() will (only as necessary) add \ before each and every character in its list . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - /.  As I mentioned before either approach risks obfuscating the pattern.
In all fairness, this method builds a less lean pattern than my first method, but you can logically expect that it will construct pattern with the greatest efficiency and with minimal drag from preg_match().


String.collect is equivalent to Select+Concat.

let padWithSpace =
    String.collect (fun c -> (if Char.IsUpper c then " " else "") + string c)
    >> fun s -> s.TrimStart()


First there is no C++ here.
You are simply doing C (use class and member functions that way you will not be passing pointers around).

So what you have implemented is a chunked set.
Each chunk trie uses 2048 integers to hold existence information and somewhere outside the scope of code review you are creating arrays of theses to define your set.

Looking at the code:

uint16_t dir, pos;
uint8_t x, y = getData(data, dir, pos, x);

This is awful. The first think I am thinking is that x is undefined because you think that functions can return multiple values. BUT I read on and find that x is passed in and is assigned inside the function. This is just horrible in terms of style and readability.

Rues of thumb:

Declare one variable per line (and make their names meaningful).
Don't mix input/output parameters and return values all in the same function.
When you use output parameters the result is usually a success value.

What is trie.

bool find(trie *root, int data)

It looks like you have to pass an array of them through for this to work. From inside this function I can not tell how legal it is to access multiple elements. I am assuming the memory management is done somewhere else but who know.

You are making the assumption that an unsigned int is 32 bits.

return pos % 32; // assigned to y

// All your code then calculates bit offsets like this
(1 << y)

The standard only requires 16. https://stackoverflow.com/a/271132/14065

Overall I think this is marginal for C code as you can not do much more.
But for C++ code this absolutely terrible. There is no encapsulation, there is no protection from using the code wrong. There is no initialization to make sure it is all set to zero.


Using rotation of proxies within a Python script

Every time you call scrape_page() with some URL, you end up making at least two requests: at least one request to verify that the randomly chosen proxy works, and then to make the main request.  Isn't that overhead a bit excessive?  Why not optimistically assume that a proxy works, and verify the proxy only if the main request fails?

If many requests fail — for example, if your network is down — then your program would get stuck in a tight, infinite retry loop.  Even a 0.1-second delay in the exception handler would be very helpful to prevent the CPU from going haywire.

The code in check_proxy() is a bit redundant with the code in scrape_page().  Also, check_proxy() is inappropriately recursive.  I would create a set_proxy() function that has a more comprehensive mission.

Instead of assuming that each proxy is HTTPS, I would write the URL of each proxy with the explicit protocol, then infer the protocol by parsing the URL.

from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from random import choice
import requests
from time import sleep
from urllib.parse import urlparse

PROXIES = [
    'https://128.199.254.244:3128',
    'https://95.85.79.54:53281',
    'https://128.199.125.54:2468',
    'https://178.45.8.113:53281',
    'https://206.189.225.30:3128',
]

def set_proxy(session, proxy_candidates=PROXIES, verify=False):
    """
    Configure the session to use one of the proxy_candidates.  If verify is
    True, then the proxy will have been verified to work.
    """
    while True:
        proxy = choice(proxy_candidates)
        session.proxies = {urlparse(proxy).scheme: proxy}
        if not verify:
            return
        try:
            print(session.get('https://httpbin.org/ip').json())
            return
        except Exception:
            pass

def scrape_page(url):
    ua = UserAgent()
    session = requests.Session()
    session.headers = {'User-Agent': ua.random}
    set_proxy(session)

    while True:
        try:
            response = session.get(url)
            break
        except Exception as e:
            session.headers = {'User-Agent': ua.random}
            set_proxy(session, verify=True)
            sleep(0.1)

    soup = BeautifulSoup(response.text, 'lxml')
    for items in soup.select(".question-hyperlink"):
        print(items.text)


I have had this problem several times and have tried different solutions. This is my current solution.

I use an associative array as a key-value list of message strings. Then I set the errors to a specific key name and fetch the corresponding message in a appropriately named file like english.php etc. This file can be all types of formats, but I will stick with PHP.

This has two main advantages:

Human readable key names
A central place all message string are stored, which in turn makes reuse of messages easier.

An example would be:

/*
* File: english.php
* This must return an associative array. This array can be multidimentional to better
* group different messages.
*/
$lang = [];
$lang['field_required'] = 'The field is required.';
$lang['success'] = 'The post was successfully created.';

// A grouped entry.
$lang['registration']['email_unavailable'] = 'The provided email is already in use.';

/*
 * A message string that requires some input that cannot be determined beforehand can
 * be solved by using the sprintf() or vsprintf() functions with the latter using an
 * array as an argument.
 */
$lang['shopping']['cart']['items']['amount_of_items'] = 'There are %d item(s) in your shopping cart.';

return $lang;

/*
 * File: bootstrapper.php (example)
 *
 * Some centrally available file. The $languages variable should be provided to
 * classes using dependency injection or made available otherwise.
 */
$current_language = 'english'; // Detected in a class or some other code.

$file = "path/to/language/{$current_language}.php"; // This file must return an array.

/*
 * Include the currently supported language file.
 * You can also make a list of supported languages before trying to load the file.
 */
if(!is_file($file) || !is_readable($file)) {
    // Do something here...
}

$languages = include $file;

/*
 * (OPTIONAL)
 * Here you can check if the language file returned the expected format.
 * Example: if(!is_array($languages)) { // do something }
 */

/*
 * Some model or controller (if you're validating input before sending it to the
 * model).
 * Here the language key is the same for all languages and only the value is
 * different.
 */
 $field_id = 'username';
 $field = filter_input(INPUT_POST, $field_id, FILTER_SANITIZE_STRING); // Just as good practice

 if(!check_required_field_function($field)) {
     $errors[$field_id] = $languages['field_required'];
 }

 /*
  * File: some view.php
  * Since this file properly contains some HTML I have used an alternative PHP syntax
  */
 <?php if(isset($errors) && !empty($errors)): ?>

The following errors occurred.

     <?php foreach($errors as $error): ?>

<?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?>

     <? endforeach; ?>

 <?php endif; ?>

The output escaping isn't stictly related to this question, but I added it as good practice.

This approach can properly be refactored a lot. Please let me know if you have any questions or something you would point out.

This is a very simple outline of the strategy I use. Hope it helps.


First of all, you are promising to return Int from printSeries. Why? If method is printing, isn't much more natural* to make it return Unit (aka void). This is usually can be done either explicitly

def printSeries(upTo: Int): Unit = { .... }

or implicitly:

def printSeries(upTo: Int) { .... }

(see, no equals sign in code above).

Next, why do you have explicit doNothing method? I think it would be better to write something like:

def printSeries(upTo: Int) {
  if(upTo > 0) {
    println(upTo)
    printSeries(upTo - 1)
  }
}

You also might want to place @tailrec annotation to ensure that code will be optimized and won't fail with Stackoverflow at big upTo numbers (if it will and function is annotated compiler will yell on you).

@annotation.tailrec
def printSeries(upTo: Int) {
  if(upTo > 0) {
    println(upTo)
    printSeries(upTo - 1)
  }
}

Finally, generally, it is better to produce sequences and only then make something with them.

P.S. you might better to post questions like this on code review site, not on stackoverlow itself

* there is a good rule in programming to make functions do one thing and be good at it so getXandMakeY usually is bad idea.


My time became limited so here is the first and probably the preferable as it would facilitate migrating the data (lots of data) to a proper database.

Note I have mixed some StackExchange code and Microsoft code with my code (that was never intended for excel) to accomplish a form of data manipulation for you, as an example.

Please note you probably need to look at the connection string in "Public Function RecordSetFromSheet" specifically this part "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"

Option Explicit

' How to use as a memory file
'  DataSet.Fields.Append "FileName", adVarChar, 254
'  DataSet.Fields.Append "FileType", adVarChar, 254
'  DataSet.Fields.Append "FileDateTime", adDBTimeStamp
'
'  OpenData
'  DataSet.Sort = "FileDateTime DESC, FileType ASC, FileName ASC"

' Use Save / CreatePersistant / OpenPersistant as required

' Create a Recordset
Public DataSet As Object 'Facilitate Late Binding
Public MyFSO As New FileSystemObject
Private Sub Construct()

  Set DataSet = CreateObject("ADODB.Recordset") ' New ADODB.Recordset

  'See this link for datatypeenum "https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/datatypeenum"

  DataSet.Fields.Append "FileName", adVarChar, 254
  DataSet.Fields.Append "FileType", adVarChar, 254
  DataSet.Fields.Append "FileDateTime", adDBTimeStamp

End Sub
Private Sub Destruct()

  Set DataSet = Nothing

End Sub
Public Sub CloseData()

' Close the Recordset
  DataSet.Close

End Sub
Public Function FileExist(pFileName as string) as boolean

DIM RetValue as Boolean

  RetValue = False

  If MyFSO.FileExists(sFilename) Then
     RetValue = True
  End If

  FileExist = RetValue

End Function
Public Sub CreatePersistData(sFilename As String)

' Create the Recordset

  If FileExist(sFilename) = True Then
     MyFSO.DeleteFile sFilename
  End If

  DataSet.Save sFilename, adPersistADTG

End Sub
Public Sub OpenPersistData(sFilename As String)

' Open the Recordset

  If FileExist(sFilename) = True Then
     DataSet.Open sFilename, , adOpenStatic, adLockOptimistic, adCmdFile
     If DataSet.RecordCount > 0 Then
        DataSet.MoveFirst
     End If
  End If

End Sub
Public Sub Save()

  DataSet.Save

End Sub
Public Sub DeleteAllRecords()

  While DataSet.RecordCount > 0
        DataSet.MoveFirst
        DataSet.Delete
  Wend

End Sub
Public Sub Sort1

  DataSet.Sort = "FileDateTime DESC, FileType ASC, FileName ASC"

End Sub
Public Sub Sort2

  DataSet.Sort = "FileDateTime ASC, FileType ASC, FileName ASC"

End Sub
Public Sub Sort3

  DataSet.Sort = "FileType ASC, FileName ASC, FileDateTime DESC"

End Sub
Public Sub LoadWorkSheet(ws as string)

' See this Microsoft Document "https://msdn.microsoft.com/en-us/library/office/ff839240(v=office.15).aspx"

  For iCols = 0 to DataSet.Fields.Count - 1
      ws.Cells(1, iCols + 1).Value = DataSet.Fields(iCols).Name
  Next

  ws.Range(ws.Cells(1, 1), _

  ws.Cells(1, DataSet.Fields.Count)).Font.Bold = True

  ws.Range("A2").CopyFromRecordset DataSet

End Sub
'
' See here for how to create initial file as in I have adapted it for consistency "http://stackoverflow.com/questions/2484516/vba-create-adodb-recordset-from-the-contents-of-a-spreadsheet"
'
Public Function RecordSetFromSheet(sheetName As String)

'Dim rst As New ADODB.Recordset
Dim cnx As Object ' To facilitate late binding New ADODB.Connection
Dim cmd As Object ' To Facilitate Late binding New ADODB.Command

  Set cnx = CreateObject("ADODB.Connection") ' New ADODB.Connection
  set cmd = CreateObject("ADODB.Command") ' New ADODB.Command

  'setup the connection
  '[HD    R=Yes] means the Field names are in the first row
  With cnx
      .Provider = "Microsoft.Jet.OLEDB.4.0"
      .ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
      .Open
  End With

  'setup the command
  Set cmd.ActiveConnection = cnx
  cmd.CommandType = adCmdText
  cmd.CommandText = "SELECT * FROM [" & sheetName & "$]"

  DataSet.CursorLocation = adUseClient
  DataSet.CursorType = adOpenDynamic
  DataSet.LockType = adLockOptimistic
  'open the connection
  DataSet.Open cmd
  'disconnect the recordset
  Set DataSet.ActiveConnection = Nothing

  'cleanup
  If cmd.State = adStateOpen Then
     Set cmd = Nothing
  End If

  If cnx.State = adStateOpen Then
     cnx.Close
  End if

  Set cnx = Nothing

  '"return" the recordset object
  Set RecordSetFromSheet = DataSet

End Function

' This plus the use of the DataSet.Sort = "String" examples may be all you need or want
' In addition this Answer may be all you need to persist vs the more generic I created
' Easiest would be to use rs.Save "filename" and rs.Open "filename" to serialize client-side recordsets to files.
' DataSet.Save "FileName" .... DataSet.Open "filename"

Public Sub Test()

'Dim rstData As ADODB.Recordset

  Set DataSet = RecordSetFromSheet("Sheet1")

  Sheets("Sheet2").Range("A1").CopyFromRecordset DataSet

End Sub

Public Sub Main

  Construct

  If FileExist("YourFileNameGoesHere") then
     OpenPersistData "YourFileNameGoesHere"
  Else
     CreatePersistData "YourFileNameGoesHere"
  End If
'
' These are for examples only and initial debuging / understanding uncomment one or build your own
'
'  Sort1
'
'  LoadWorkSheet "YourWorkSheetNameGoesHere"
'
'  Sort2
'
'  LoadWorkSheet "YourWorkSheetNameGoesHere"
'
'  Sort3
'
'  LoadWorkSheet "YourWorkSheetNameGoesHere"

  Destruct

End Sub


A different way would be to use primeHashes  (see https://stackoverflow.com/a/4237875/461499).

This prevents the need to sort.

private static void printAnagrams2(List<String> input) {

    // our result structure.
    // key in the map is the sorted list of characters of the string
    // value is the list of anagrams found for this key
    Map<BigInteger, List<String>> result = new HashMap<BigInteger, List<String>>();

    for (String s : input) {
        BigInteger primeHash = calcPrimeHash(s);

        // Then add-or-create this in the resultmap
        if (result.containsKey(primeHash)) {
            result.get(primeHash).add(s);
        } else {
            List anagrams = new ArrayList<String>();
            anagrams.add(s);
            result.put(primeHash, anagrams);
        }
    }

    // sort each anagram-list
    result.values().forEach(Collections::sort);

    // and print
    result.values().forEach(System.out::println);
}

private static int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};

private static BigInteger calcPrimeHash(String s) {
    BigInteger i = BigInteger.valueOf(1);
    for (char ch : s.toCharArray())
    {
        if (Character.isLetter(ch))
        {
            char c = Character.toLowerCase(ch);
            i = i.multiply(BigInteger.valueOf(primes[c - 'a']));
        }
    }
    return i;
}


Some basic refactoring, and using ? placeholders in sql queries,

use strict;
use warnings;
use DBI;
my $dbh;
my $bad_form = "text.txt";

sub prepare_execute {
    my ($sql, $values, $dbh) = @_;

    my $item = $dbh->prepare($sql) or do {
        log_error("Couldn't prepare statement: " . $dbh->errstr);
        die;
    };
    $item->execute(@$values) or do {
        log_error("Couldn't execute statement: " . $item->errstr);
        die;
    };
    return 1;
}

open (my $OUT, "<", $bad_form) or die "$! $bad_form";
while (<$OUT>) {
   chomp $_;
   my ($item_id, $description, $form_id_1, $form_id_3) = split(/\|/, $_);

   my $new_form_id_1 = form_1($form_id_1);
   my $new_form_id_3 = form_3($form_id_3);

   if ( $new_form_id_1 ne 'null' ){
        my $sql = "update item_table set form_id_1 =? where item_id =?";
        eval { prepare_execute($sql, [$new_form_id_1, $item_id], $dbh) }
          or return 2;
   }
   else {
        $form_id_1 = "correct value";
        $new_form_id_1 = "no updated";
    }

   if ( $new_form_id_3 ne 'null' ) {
        my $sql = "update item_table set form_id_3 =? where item_id =?";
        eval { prepare_execute($sql, [$new_form_id_3, $item_id], $dbh) }
          or return 2;
   }
   else {
        $form_id_3 = "correct value";
        $new_form_id_3 = "no updated";
   }
}


Extension pattern in a flask controller using importlib

the idea is nice, but I have few concerns.
Firs of all, trying to call importlib every time you are accessing the API endpoint is a bit expensive. It will be a way better if you will introduce some cache first.

You can use 2 approaches to build that cache:

Lazy, where you lookup cache first and if you cannot find the proper handler, you are trying to load it using your trick with importlib
The standard approach where you can use e.g. pkgutil.iter_modules (https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules) and build the handler cache before you are actually start handling the API endpoints.

I have also few notes regarding your code:

Use format functions instead of concatenating strings:

".{}".format(endpoint)

Don't catch general exceptions (just use more specific classes than Exception class) and try not to put more then 1 statement under the try...except block.
Use pythonic naming handlerClass -> handler_class
In your handlers you can make names as read-only properties:

@property
def name(self):
    return "sample"

Try to follow PEP8 in module imports:

# System modules
import importlib

# 3rd party
from flask import Flask, abort

# your modules
import handlers


Remove the parent element when user clicks on the remove icon

In general classes are used for collections of things that should exhibit the same behaviour. Your buttons here are perfect candidates for this, so you should give them the same class name - remove-form-btn

Then give your divs a class name of form and you can write just one handler:

$('.remove-form-btn').click((event) => {
  $(event.target).parents('.form').hide();
});


Was this use of  tags in this HTML over background images better?

The use of ul seems appropriate. My concern with using <img>s would be with the image dimensions. From what I can see above, unless you create your images specifically in those dimensions, it will become a pain to ensure they scale correctly.

I've found that if you want to preserve a predetermined width and height for your images without ruining the aspect ratio it's almost always easier to use background-image rather than <img> tags.

Using background-size: cover you can ensure that the image covers the available space, without losing the ratio:

  The cover value specifies that the background image should be sized so
  that it is as small as possible while ensuring that both dimensions
  are greater than or equal to the corresponding size of the container


Adding a checkbox to a JavaScript class object

In my opinion, it seems like this should be it's own class. You should have another object to control the FamousPerson objects and add them when they are instantiated. I would also decouple the checkbox from the FamousPerson class itself and tie the behavior in elsewhere.

As for the solution part, if you still want to add it in here, check out this. There's an example of creating a checkbox with a label and adding it to the DOM. Shouldn't be too hard to patch some of it in to your existing class.


One of the pitfalls with any language using formatting constructs you're not that familiar with, is that it becomes an unreadable mess. Your code though is properly formatted, properly indented (it would be poor style for an indentation script to be badly indented itself, wouldn't it?) and even self-documenting. On every line, it's perfectly clear where we are, what's going on and how it's done.

If we're really going to nitpick, the documentation of Emacs Lisp uses the following indentation style for conditionals:

(cond ((file-exists-p filename)
        (find-file filename)
        (indent-region (point-min) (point-max))
        (save-buffer))
      (t (message "File not found (need existing file): %s" filename))))

Which slightly differs from yours, and is more in line with the rest of the language. But I can understand a preference for either.


Create array with id's of needled input's:

var inputs = ["clase_via", ...], i, count;
for (i = 0, count = inputs.length; i < count; i += 1){
    $(inputs[i]).prop("disabled", true);
}

Add "data" attribute for needled input's:

<input type='text' data-lockable="true"/>
$("input [data-lockable='true']).prop("disabled", true);

Place all input's into one block and call jQuery as:

$("#maindiv > input").prop("disabled", true);


You've got a bug here.

headers = file.gets.chomp.split(", ")

There is no requirement in a *.csv file that there be a space after the comma between items. In fact, if there is a space, that space should be considered part of the item, not part of the delimiter.

The next thing I notice is that comma separated files are not strictly separated by commas. Other delimiters are possible, and likely to be come across. Things such as pipes | are common. I would consider supporting other delimiters. For example, Excel supports Tabs, Semicolons, Commas, and Spaces, along with an option for a custom defined delimiter. You might not want to fuss with supporting user defined delimiters, but certainly your class becomes more useful if you support the ones I've mentioned.

The process of implementing this should clean up the string literal duplication you have here.

  def initialize file
    @rows = []
    headers = file.gets.chomp.split(", ")
    file.each do |line|
      values = {}
      headers.zip(line.chomp.split(", ")).each do |key, value|
        values[key] = value
      end
      @rows << CsvRow.new(values)
    end
  end

But minimally, you should replace ", " with a constant value so you never accidentally change the delimiter in one place, but not the other.


Section 2: Classes - Design a StackOverflow Post

I don't know which version of C# you use, but as of C# 6 it's possible to set initial values on property definition, which has 2 advantages:

Can eyeball the initial values quickly by looking at the property definitions.
Doesn't require you to copy the same initial value assignment code into additional constructors you may create.

Example initial value definition:

public int VoteCount { get; private set; } = 0;

Also in the case of int with initial value 0 you don't have to explicitly set it because when an instance of the class is initialized all the ints are initialized with the default value 0 unless you specified otherwise. Just like the bools are false by default (you didn't set them in the constructor).

You could add another layer of protection to the creation date:

public DateTime TimeDateCreated { get; } = DateTime.UtcNow;

Without defining a setter, TimeDateCreated is set when you create an instance of Post and can never be changed again for that instance. It makes sense here because the only date you'd ever want to change on a post is the date it was edited.

Not a big deal for now, but it's better to develop early the habit of giving good variable names, this means being descriptive, concise and consistent with the naming of things around the code base. Most of your names are good, but TimeDateCreated is a bit counter-intuitive because once you'll get used to the name DateTime you'll expect this property to be named DateTimeCreated.

It's good that you protected VoteCount, but your vote function does something unwanted: if you first downvote and then upvote, you will be back to 0 votes but without the ability to upvote. I suggest you rethink this part of the code.


Can I use a header tag in footer inside section?

It's not valid HTML5 to have a <header> element inside a <footer> element. You could have checked this yourself on this site:

http://validator.w3.org/check

For using <header>, <footer> and <section> correctly, see this page:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer

For even more technical details, see the HTML5 specification:

http://www.w3.org/TR/html5/sections.html#the-footer-element

Special thanks to @amon for the links!


Calculating how long sales reps are idle

First, let's give this some proper indentation so we can see what's going on.

Sub Latency()
    ' this sub-routine is used to calculate the no of recent idle months by an agent
    Application.ScreenUpdating = False
    For Each rng In Range("BL1:BL13000")
        j = 1
        Do Until ActiveCell.Offset(0, -23 - j) > 0    ' this reads the sales flag
            j = j + 1
            If j > 12 Then Exit Do
        Loop
        ActiveCell.Value = (j - 1)   ' inserts the value to the cell
        ActiveCell.Offset(1, 0).Select
    Next rng
End Sub

Do you see it now? Freeman was absolutely right. You're not looping over 20 rows. You're looping over 13000. Why such a large range? Ohhh I know. You want to make sure you're getting all of the data, right? Okay, but what if the data range extends past row 13k? You don't just have a performance problem, you also have a correctness problem. Find the last row instead.

Let's see what else we've got while we're here though.

Sub Latency()

The default scope for VBA procedures is Public. So, you should ask yourself if this is the right thing here. I don't have enough context to say, but you should really be explicit whenever possible anyway. Don't rely on another developer's knowledge. Ever. Be explicit.

' this sub-routine is used to calculate the no of recent idle months by an agent

Cool! I like seeing short comments like this explaining what the purpose of the procedure is. It's a good comment. The problem is though, I can't figure out how the Sub's name (Latency) has anything to do with this. Try to come up with a better name for it.

Application.ScreenUpdating = False

Cool! Good idea! Make it look magical when you turn the screen updating back on! But wait.... you never turn it back on. That's bad. Real bad. If you're going to use this, you need to not only turn it back on at the end of the procedure, but you'll also need to make sure it always gets turned back on with an error handler.

For Each rng In Range("BL1:BL13000")

We talked about this already. Find the last row instead.

j = 1

Why are we starting with j? If you're going to use a generic counter variable, start at i and work your way up through j and k. It's just an expected convention.

What I'm actually worried about here is that you've not declared the variable. That means two things.

You've not declared Option Explicit.
This is implicitly a Variant type.

I cannot impress this on you enough. Use Option Explicit. It turns run time bugs into compile time bugs by forcing you to define all of your variables up front.

Why is Variant bad? It's bad because a variant can be anything. Yes. Anything. I could do this and VBA wouldn't blink twice.

j = 1
j = ActiveSheet

Seriously, yes. You can do this if you're using variant types. So don't.

Do Until ActiveCell.Offset(0, -23 - j) > 0    ' this reads the sales flag
    j = j + 1
    If j > 12 Then Exit Do
Loop

What are all these numbers??? I have no idea what this means at all. Use some well named constants instead.
Great comment again! However, instead of using a comment, create a function that returns a boolean value.
Avoid Activate and Select.


Yes, your function is still pure. A pure function has only two requirements:

The return value will always be the same given the same arguments.
Evaluation will produce no side effects.

Since filterMultipleOf only uses integers, the second is obviously met, no mutation is possible. The first requirement is also met. Calling filterMultipleOf(1) creates a function which is distinct from the function created by calling filterMultipleOf(2). See this question on software engineering for an alternative explanation.

Is there a better way to express this function? Yes.

Just because your functions are short doesn't mean stop thinking about names. x and y are about as vague as you can get. Renaming x to factor and y to multiple immediately makes the function clearer. Also, multiplesOf takes a list of factors, not a list of multiples.

Naming variables after their type is generally a bad idea. int should be called multiple. list is a bit more difficult. In this case I would leave it as is since I can't quickly come up with a better name (numbers really doesn't help much).
You can pass functions around without specifying a single partial. Do multiples.map(filterMultipleOf) instead of multiples.map(filterMultipleOf(_))
I don't see the need for filterMultipleOf, you can just use an anonymous function without losing any meaning. factors.map(factor => (multiple: Int) => multiple % factor == 0)
Choosing to create a function for each factor makes your function logic take more space since you now have to call each function. I believe it is more clear to create a helper function that checks all factors:

def multiplesOf(list: List[Int], factors: List[Int]): List[Int] = {
  val isMultiple = (multiple: Int) => factors.exists(factor => multiple % factor == 0)
  list.filter(isMultiple)
}

You could further reduce this function by providing isMultiple as a lambda, but this is really dependent on your style. I'd go for it in this case.

def multiplesOf(list: List[Int], factors: List[Int]): List[Int] = {
  list.filter(multiple => factors.exists(factor => multiple % factor == 0))
}

It might be worth questioning the public API for this function. As it stands, it is only useful for lists of integers. What happens if you have a list of another type - say, Person and you want all people whose age is a multiple of 3 or 5? Right now, you can't use this function.

If the function was slightly modified to tell if a single integer is a multiple of some factor, then you can use the function.

val multipleOf = (multiple: Int, factors: List[Int]) =>
  factors.exists(factor => multiple % factor == 0)

class Person(var name: String, var age: Int) {
  override def toString: String = s"$name is $age"
}

val people = List(
  new Person("Adam", 25),
  new Person("Bob", 7),
  new Person("Cate", 12),
  new Person("Dave", 20),
  new Person("Edward", 8)
)

people
  .filter(person => multipleOf(person.age, List(3, 5)))
  .foreach(println)

With this change, your original function can be trivially defined:

val multipleOf = (multiple: Int, factors: List[Int]) =>
  factors.exists(factor => multiple % factor == 0)

val multiplesOf = (list: List[Int], factors: List[Int]) =>
  list.filter(multipleOf(_, factors))


Regarding try/catch: this depends on whether your user class can handle errors or not.

An exception you can't handle is for example if the SQL-statement has a syntax error or the SQL-server being down. You can't do anything about it programatically during runtime except for displaying a nice error message to the user. In that case I wouldn't surround the DB-code with try/catch but implement a global try/catch which does just display a nice error message to the user and log the errors for you, the developer.
But if you have an exception because for example your username-field is UNIQUEand someone tries to insert an username which already exists you could resolve that problem automatically by just adding a number to the username and retry the insert (okay it's a dumb example, but I hope the point comes across). The pseudocode for this dumb example could be like:

$statement = $db->prepare("INSERT INTO user (username, ....) values (?, ...)");
$tryInsert = true;
$tries = 0;
while($tryInsert) {
    $insertName = $username;
    if($tries > 0) {
        $insertName .= $tries;
    }
    try {
        $statement->execute(array($insertName, ...));
        $tryInsert = false; // it worked, stop trying
    } catch(PDOException $e) {
        if($e->code() == "23000") {
            // 23000 means unique constraint violation, probably
            // duplicate username
            ++$tries;
        } else {
            // we can't handle the exception, therefore we just re-throw it
            throw $e;
        }
    }
}

I think in your code are no exceptions which you could handle. If an exception occurs it is most probably due to some issue with the SQL-server or the SQL-statement is wrong. In that case it doesn't make sense to wrap any of your code in try/catch. But you should add some kind of global exception handler which displays a nice error message (like: oops something went wrong, the developers have been informed).
In login change the last two lines to:

if (($row = $this->STH->fetch()) !== false)
    return $row;

The problem with PDOStatement::recordCount() is, that it's not portable for SELECT queries and the above code does the same thing as your code.
Then in create_account, you use PDO::setAttribute to change the PDO error mode of the supplied PDO-instance. Change that so that this is called when the PDO is initialized and not deep down in some mapper-class.
Your activate method could be rewritten to just execute one query:

public function activate($key) {
    $this->STH = $this->DBH->prepare("UPDATE users SET activated = 1, activation_key = null WHERE activation_key = ?");
    $this->STH->execute(array($key));

    // rowCount is set to the number of rows affected by UPDATE
    return $this->STH->rowCount() > 0;
}

Optional: This could be simplified:

if (isset($_SESSION['userid']) && isset($_SESSION['hash'])) {

To that:

if (isset($_SESSION['userid'], $_SESSION['hash'])) {

Optional: Consider using phpass for hashing your passwords. It's definitely more secure that just sha1 with some salt thrown in and the class is simple to use. If you're doing this you would have to rework your login method a bit  (meaning the password verification must be done in PHP when using phpass).
If you like to change your check_*-methods you could do something like that:

protected function check_record($field, $value) {
    $this->STH = $this->DBH->prepare("SELECT COUNT(*) FROM users WHERE {$field} = ?");
    $this->STH->execute(array($value));

    $count = $this->STH->fetchColumn();

    if($count !== false) {
        return (int)$count > 0;
    }

    return null;
}

public function check_username($username) {
    return $this->check_record("username", $username);
}

public function check_email($username) {
    return $this->check_record("email", $username);
}


Fast Factorisation (Python Implementation)

sqrt is expensive.  You can avoid it by reworking your test condition from:

p > int(sqrt(n)) + 1

to:

p*p > n

You can skip one while n%p == 0 iteration by initializing e = 1 and unconditionally dividing by p once you’ve found a prime factor:

if n%p == 0:
    e = 1
    n //= p
    while n%p == 0:
        # ...etc...

Avoid putting “then” statements on the same line as  the if statement:  place the “then” statement indented on the next line.

The algorithm should be a comment, not part of the """docstring"""; callers generally only care about how to use the function, not the implementation details.


Removing entries with duplicate columns from large .vcf files

Some notes:

Run it through pycodestyle to learn how your style differs (at least in machine detectable ways) from idiomatic Python. This makes code not only easier to review, but also easier for seasoned Python developers to read and maintain. I would recommend not silencing any of the complaints, and instead fixing every one of them. It quickly becomes second nature to write idiomatic Python that way.
Abbr. var nams hindr rdability, makin it hardr to rd. Unless D1 is absolutely clear from context to anyone in your field I would rename it until it is. The same of course goes for f, which could be semi-tolerable if your script only ever processed one file, but is baffling if you're processing several. "More typing" is not an argument against this, because there are editors which will happily auto-complete any identifier for you.
You have a nested loop where both loops use the same instance variable. That means that the outer loop variable is useless.
You have huge files you want to process, so you really, really don't want to read whole files before starting processing. The way to avoid that is to process each line as you read it, as in for line in file_pointer rather than lines = file.readlines() + a loop.
The main parts of this should be split into functions, called by a short main function which is triggered only if __name__ == '__main__': - this rather unfortunate pattern is idiomatic Python, and allows reuse of the functions and objects in your module.
You have completely open ended except clauses, which is almost universally a bad idea. Exception handling is expensive, and you'll be much better off checking for the existence of an index than throwing an exception and catching it again immediately. In general, the anti-pattern is to use exceptions for flow control.
There are several patterns in use which may be fine for most processing, but which are not optimal for large amounts of data, such as splitting and joining of strings, regular expressions, and accumulating strings and then writing once rather than just writing every substring. From a cursory look it seems that your processing would be very much quicker if done with a database, if at all possible.
You are taking care to close some files by using with open(), but the second D2 is not closed.
Reusing variables for different things also makes code really hard to read, and it a common misconception that it is more efficient. Maybe in some niche corner cases, but for this kind of processing you will be much better off with evidence-based optimisation - prove where the code is slow with a profiler and fix those parts.


Implementation of insertion sort in JavaScript

Your function can only sort numbers and strings

The built in Array.sort function offers an optional compare function as a parameter. Adding this feature to your insertionSort function would allow for users to sort any type of object:

function defaultCompare(x, y) {
  if (x < y)
    return -1;
  else if (x > y)
    return 1;
  else
    return 0;
}

function insertionSort(array, compare) {
  compare = compare ? compare : defaultCompare;
  //...
}

You have quite a few variables that aren't necessary

totalElements

You only use this variable once, in the condition of your first for loop. JavaScript has some incredibly fast engines and with JIT-Compiler (just in time compiler) you don't have to worry about micromanaging optimizations like what if js isn't smart enough to know that it's recalculating inputArray.length - 1 each iteration. Defining totalElements arguably makes your code harder to read by adding another variable the scope, and the JS engines are smart-enough/fast-enough that performance isn't likely affected, so I would recommend getting rid of it.

temp

You could eliminate temp by abstracting out a function to swap indices in an array:

function swapIndices(array, index1, index2) {
  var temp = array[index1];
  array[index1] = array[index2];
  array[index2] = temp;
}

This also improves your code's cohesiveness by abstracting out the technicalities of swapping variables, and it allows you to use swapIndices elsewhere in your code.

lastIndex

This one is just a constant for zero. At the very least you should change the var to const:

const lastIndex = 0;

But I'd recommend to just get rid of it.

prevIndex

I find currentIndex - 1 more clear than prevIndex. The former is obviously the index 1 less than currentIndex whereas the latter could also mean the previously swapped element (precedingIndex is another possible name).

Summary

With all the above changes your code would look like:

function defaultCompare(x, y) {
  if (x < y)
    return -1;
  else if (x > y)
    return 1;
  else
    return 0;
}

function swapIndices(array, index1, index2) {
  var temp = array[index1];
  array[index1] = array[index2];
  array[index2] = temp;
}

function insertionSort(array, compare) {
  compare = compare ? compare : defaultCompare;

  for (let i = 0; i < array.length; i++) {
    for (let currIndex = i; currIndex > 0; currIndex--) {
      if (compare(array[currIndex], array[currIndex - 1]) < 0) {
        swapIndices(array, currIndex, currIndex - 1);
      }
      else {
        break;
      }
    }
  }

  return array;
}


jQuery animate opacity, fade, & slide up page load effect

Interesting concept, and I do see some improvements that could be made.

First off though, it's true that the semicolons aren't necessary in JavaScript. It's a matter of preference really. If you think the people who will read your code would prefer semicolons, then use them where necessary. I suggets you try JSLint in the future!

I think that your animation is somewhat strange, but I'm not here to argue that! (The change in height of .overlay is what I'm talking about) I think that combination of animations is fine, and could be left as is.
Perhaps the one thing you could do: add some space to improve readability. Packing that last closure onto one line is just restrict breathing room, and it would be easier to quickly read it if it was spread out.
Your second animation could simply be:

$('#frame').delay(300).fadeIn(300)

You weren't the first one who thought about fading ;)

So my ideal function would be as follows:

$(window).load(function () {
    $('.overlay').animate({
        opacity: 1,
        height: 0
    }, 1000, function () {
        $(this).remove()
    });

    $("#frame").delay(300).fadeIn(300)
});


Am I using copy ctors/move ctors/shared_ptr correctly?

Firstly, in your header file, you don't need the Hero:: qualification on your move assignment operator. Secondly, you are defining it as Hero& Hero::operator=(const Hero &&hero);. Think about what this is saying - it's saying if you have an rvalue reference to a Hero object, then:

You cannot modify it because it is const
You want to utilize move semantics (specifically, std::move) which will modify the original object and leave it with an empty value.

Hence, your move constructor should always be of the form Hero& Hero::operator=(Hero&& hero). The implementation should also be using std::move:

Hero& operator=(Hero&& hero)
    : id(std::move(hero.id),
      name(std::move(hero.name),
      level(std::move(hero.level)
{ }

For your AddHero methods, a Hero&& hero might be an rvalue reference, but without the std::move for its elements, you're basically saying "take an rvalue reference to Hero, and call copy constructors on each of its elements when you utilize make_shared<Hero>".

Note that moving vs copying for basic types like int or long won't have any performance difference.

That being said, you're doing a lot of work here for no benefit. The rule is, unless you have written a custom destructor, you don't need to write custom copy constructors, copy assignment operators or move assignment operators - the compiler will generate defaults which are correct. It is only when you are managing memory (hence have a delete or delete[] in a destructor somewhere) that you need to implement these.

Finally, a few other small points. Your constructors should be taking strings by const &, ie, explicit Race(const std::string& name). Usage of this-> to return member variables is a bit unidiomatic in C++, likewise in copy constructors and the like, instead of this->id = hero.id; it's more idiomatic to simply write id = hero.id;.

I'd suggest reading the Rule of Three post on stackoverflow to get a better understanding of copy construction and copy assignment.


There are several improvements that can be done, starting from the class declaration:

The class name is not very descriptive. MRBST could be an initialism for many things. BinarySearchTree is much better. Don't be afraid of using long names if they convey information more clearly.
One thing doesn't make sense here: The class is a template class, but the data field of the treeNode is an int. If you are only storing ints, then the class doesn't have to be a template. You should however replace that int with T and make it generic.
The naming convention of treeNode is a little unusual for types. This kind of camelCase notation is usually applied to variables. Types themselves are more commonly declared using CamelCase, fist letter uppercase.
PrintPreorder() breaks your naming convention for methods. printPreorder() would be more consistent.
Ordering of class data and member methods: I find more adequate placing public methods and data first, followed by protected methods/data and lastly anything private. This is convenient for readers of the class declaration, since they will be interested in the public interface most of the time.
Order of the public fields: Place constructors first, followed by assignment/move operators, then the destructor and the rest after those. The fist thing you want to inspect when reading a class declaration is how the constructor(s), destructor and assignment are implemented, because that gives you hints about how the class lifetime is managed.
Unnamed function parameters in push() and search(): You should always name function parameters in the header declaration because that's a form of code documentation.
Remove excessive blank lines from the header file. There are some unexpected blank lines in there that serve no purpose. It looks untidy.

More aspect to improve in the implementation:

Please don't use NULL in C++ code. Your compiler should be C++11 ready by now, so use nullptr.
PrintPreorder() and preorder() should also be const methods since they don't mutate member state. Also the treeNode pointer that preorder() takes should be a const pointer. E.g.: const treeNode* pre.
Currently, your class leaks memory. You are only deleting the root of the tree. All leaf nodes will leak. You need to recursively delete all nodes before deleting the root. The process is basically the same as how you did to print the tree.

There are probably more details that can be improved, as well as architectural improvements. Other reviews might want to expand on those.