I cannot check all because I use a phone at the moment, but here are some quick observations I saw skimming thru the code:

Never call main ()

-It is not defined in C++ what happens if you call main from another function. It is undefined behavior.

You could instead put your while (1) loop in a function and call it instead of main.

Use of C++ Features

-Consider using std::array or std::vector instead of using plain C style arrays.

Formating

-Formatting seem to be off in some places. Add a space between functions and don’t put several instructions on one line.

e.g.

if (win()) {std::cout << "Player 2 wins!\n";break;}
    ++count;

Should become:

if (win()) {
    std::cout << "Player 2 win\n";
    break;
}
++count;

Also you should avoid having to long lines. Get used to break the code after max 80 lines. It has the advantage that you can view two source codes next to each other.

for example make this:

if (pos[w_combinations[i][0]] == pos[w_combinations[i][1]] && pos[w_combinations[i][0]] == pos[w_combinations[i][2]])
{
    return true;
    break;
}

Into this:

if (pos[w_combinations[i][0]] == pos[w_combinations[i][1]]
    && pos[w_combinations[i][0]] == pos[w_combinations[i][2]])
{
    return true;
    break;
}

or this

void printMatrix() {
std::cout << "|" ; check(pos[0]) ; check(pos[1]) ; check(pos[2]);std::cout << "\n";
std::cout << "|" ; check(pos[3]);check(pos[4]) ; check(pos[5]);std::cout << "\n";
std::cout << "|" ; check(pos[6]) ; check(pos[7])  ;

It’s very important for code to be easy to read. You may be only write a program once but most of the time you read it while debugging or maintaining it. If the code is good formatted this task becomes a lot easier.

Avoid redundancy

In you’re while loop you use the same instructions except the messages for player 1 and 2.
Make them a function with parameters for the messages. This way you make sure you handle both players the same.

Avoid global variables

Don’t use global variables they make the code hard to maintain. They can lead to obscure bugs.
Consider passing them between you’re functions or even better check out OOP and work with a class who stores the state of the Board.

Functions should do one thing

You’re function check () should only return the string not also print it. It should become this:

std::string check (int x)
{
    if ( x == 10) {
        return "X|";
    }
    else if (x == 11) {
        return "O|";
    }
    return std::to_string (X)
}

This function now gets called and the string is directly printed. No need to change anything in the call code.

Also consider using switch instead of a long if else chain if there are many cases.

Calls to std::cout

No need to call std::cout several times. Just do this :

std::cout << '|' + check(pos[0]) + check(pos[1]) + check(pos[2]) + '\n';

Single chars should be quoted ' ' not " " to avoid getting a more expensive string use instead of a char.

Handle invalid input

Try to enter something which is not a the expected number. What happens? The program probably loops endless or crashes because you read no int.
You should handle this case.
One approach would be reading the in put as a std::string and check this string if it is a digit.
If it is not prompt an invalid input and let the user enter again.

But wait. you can also break the program if it is an int but not in range. Handle also wrong range. for example when you input 1234 the program will crash currently as well. You could do all this in a function:

int get_input();

So you can write:

int x = get_input();

Use descriptive names

Function names like Check or Input are very mysterious to me about what they are doing.

The same goes for variable names like x, y  or w_combinations.
Try to self document youre code by using clear names which describe what the variable or function does.

Ask yourself if you check this code in 1 or 2 months yourself if you still can get what the program does. With good naming’s and a clear structure it becomes a lot easier.

Use C++ Features like Classes

Youre code looks very C like. Make more use of C++ features like classes etc.
I rewrote the program with classes to demonstrate a more C++ Style as an inspiration (maybe I should also post it for review?).
Don't get overwhelmed it takes a lot of time and practice to get into C++...

tic_tac_toe.h

#ifndef TIC_TAC_TOE_020120180815
#define TIC_TAC_TOE_020120180815

#include <array>
#include <string>

namespace tic_tac_toe
{
    class TicTacToe final{
    public:
        TicTacToe() = default;
        ~TicTacToe() = default;

        // delete copy and move mechanism, we don't want to
        // copy a running game
        TicTacToe(const TicTacToe&) = delete;
        TicTacToe(TicTacToe&& other) = delete;
        TicTacToe& operator=(const TicTacToe& other) = delete;
        TicTacToe& operator=(TicTacToe&& other) = delete;

        void print_state_of_board() const;
        bool draw(int field);
        bool board_full() const;
        bool player1_win() const
        {
            return check_win_condition(FieldState::player1);
        }

        bool player2_win() const
        {
            return check_win_condition(FieldState::player2);
        }
    private:
        enum class FieldState {
            empty,
            player1, // X
            player2, // O
        };

        bool check_win_condition(FieldState state) const;
        char field_state_to_char(FieldState state) const;

        std::array<FieldState, 9> m_board{ FieldState::empty };
        bool m_player1_active{ true };

        static constexpr char m_player1_token{ 'X' };
        static constexpr char m_player2_token{ 'O' };
    };

    int get_user_input(const std::string& user_message);

    void play_game();   // main routine to run the game logic;
}  // namespace tic_tac_toe
#endif

tic_tac_toe.cpp

#include "tic_tac_toe.h"

#include <algorithm> // std::find
#include <cctype> // std::stoi
#include <iostream>
#include <vector>

namespace tic_tac_toe
{
    void TicTacToe::print_state_of_board() const
        /*
        Print the board. e.g:
        |X| |O|
        | |X| |
        |O| | |
        */
    {
        for (auto i = 0; i < m_board.size(); ++i) {
            if (i % 3 == 0 && i != 0) {
                std::cout << "|\n";
            }
            auto token = field_state_to_char(m_board.at(i));
            std::cout << '|' << token;
        }
        std::cout << "|\n";
    }

    bool TicTacToe::draw(int field)
        /*
        Tries to draw the next symbol in the field.
        Each time the function is called the player is changed.
        The user input has to be done out side. This way also a bot
        could play the game.
        If the selected field can not be set because its already
        occupied by player1 or player2 or out of range the return
        value becomes false
        */
    {
        if (field < 1 || field > m_board.size() ||
            m_board.at(field - 1) != FieldState::empty) {
            return false;
        }
        if (m_player1_active) {
            m_board.at(field - 1) = FieldState::player1;
            m_player1_active = false;
        }
        else { // player 2 active
            m_board.at(field - 1) = FieldState::player2;
            m_player1_active = true;
        }
        return true;
    }

    bool TicTacToe::board_full() const
        /*
        search for a empty field in the board
        indicating that board is full if no empty field available.
        */
    {
        auto it = std::find(
            m_board.begin(), m_board.end(), FieldState::empty);

        return it == m_board.end();
    }

    bool TicTacToe::check_win_condition(FieldState state) const
    {
        constexpr std::array<std::array<int, 3>, 8> combinations =
        {
            std::array<int, 3>{0,1,2},
            std::array<int, 3>{3,4,5},
            std::array<int, 3>{6,7,8},
            std::array<int, 3>{0,3,6},
            std::array<int, 3>{1,4,7},
            std::array<int, 3>{2,5,8},
            std::array<int, 3>{0,4,8},
            std::array<int, 3>{2,4,6}
        };

        for (const auto& combination : combinations) {
            if (m_board.at(combination[0]) == state &&
                m_board.at(combination[1]) == state &&
                m_board.at(combination[2]) == state) {
                return true;
            }
        }
        return false;
    }

    char TicTacToe::field_state_to_char(FieldState state) const
    {

        if (state == FieldState::player1) {
            return m_player1_token;
        }
        if (state == FieldState::player2) {
            return m_player2_token;
        }
        return ' ';
    }

    int get_user_input(const std::string& user_message)
    {
        while (true) {
            std::cout << user_message;
            std::string input;
            std::cin >> input;
            /*
            If input is not an integer the stoi function will raise
            an exception. We use this to determine if the input was
            an int
            */
            try {
                return std::stoi(input);
            }
            catch (std::invalid_argument&) {
                std::cout << "\nInput is not a number. Try again:";
            }
        }
    }

    void play_game()
        /*
        Main routine to play the game with 2 players
        */
    {
        while (true) {
            TicTacToe game;
            bool player1_active{ true };
            while (!game.board_full() &&
                !game.player1_win() && !game.player2_win()) {

                game.print_state_of_board();

                std::string user_message;
                if (player1_active) {
                    user_message = "1[X]:";
                }
                else {  // player2 active
                    user_message = "2[O]:";
                }
                if (!game.draw(get_user_input(user_message))) {
                    std::cout << "\nInvalid! Try again: \n";
                }
                else {
                    player1_active = !player1_active;
                }
            }

            game.print_state_of_board();

            if (game.player1_win()) {
                std::cout << "Player 1 wins!\n";
            }
            else if (game.player2_win()) {
                std::cout << "Player 2 wins!\n";
            }
            else {
                std::cout << "Draw!\n";
            }

            int choice{};
            while (true) {
                choice = get_user_input(
                    "Play again[Yes = 1, No = 0]: ");

                if (choice == 0) {
                    return;
                }
                if(choice == 1) {
                    break;
                }
            }
        }
    }
}  // namespace tic_tac_toe

main.cpp

#include "tic_tac_toe.h"

#include <iostream>

int main()
try {
    tic_tac_toe::play_game();
}
catch (std::runtime_error& e) {
    std::cerr << e.what() << "\n";
    std::getchar();
}
catch (...) {
    std::cerr << "unknown error " << "\n";
    std::getchar();
}


It has a bug: very small numbers are completely ignored:

sum({0.1, 0.0000001}) -> 0.1

If technical limitations do not allow you to change this behaviour, you should:

Document it in a comment as a know limitation
Put a condition in the loop if x < min_tolerance {fail}, to adhere to fail fast fail loudly, instead of silently failing.


Holy incomprehensible comprehensions!

There is no good justification for defining seq, freq, and sample all as one statement.  Each of them is already complex enough on its own.

There is also no good reason to write your last while loop as a one-liner.

With just those changes and some indentation…

from collections import defaultdict

import nltk
import numpy as np

seq = [
    t for ts in [
        [None] + nltk.casual_tokenize(line) + [None]
        for line in open("file.txt").readlines()
    ]
    for t in ts
]
freq = defaultdict(lambda: defaultdict(int))
sample = lambda curr: np.random.choice(
    list(freq[curr].keys()),
    p=[x / sum(freq[curr].values()) for x in freq[curr].values()]
)
for a, b in zip(seq[:-1], seq[1:]):
    freq[a][b] += 0 if a is None and b is None else 1
curr = sample(None)
while curr != None:
    print(curr, end=" ")
    curr = sample(curr)

… we might start to hope to understand the code.

What's [t for ts in [[…]] for t in ts]?  It's just flattening a list of lists.  I'd write that as list(itertools.chain(*[[…]])).

with open("file.txt") as f:
    seq = list(itertools.chain(*[
        [None] + nltk.casual_tokenize(line) + [None]
        for line in f
    ]))

However, once you flatten it, you get …, None, None, … as placeholders for the linebreaks.  You later have to do extra work to filter out if a is None and b is None when constructing the freq matrix.  So why even bother creating seq as a flattened list in the first place, if all you want is a frequency matrix?

from collections import Counter

def frequency_table(file):
    freq = defaultdict(Counter)
    for line in file:
        tokens = nltk.casual_tokenize(line)
        for a, b in zip(tokens + [None], [None] + tokens):
            freq[a][b] += 1
    return freq

sample would be clearer if written as a function.  I'd make it take a freq parameter instead of using freq as a global.

def sample(freq, curr):
    return np.random.choice(
        list(freq[curr].keys()),
        p=[x / sum(freq[curr].values()) for x in freq[curr].values()]
    )

I don't know if performance is an issue here, but you might be better off normalizing the probabilities instead of recalculating [x / sum(freq[curr].values()) for x in freq[curr].values()] with each call to sample().

It would be nice to convert your final loop into a generator:

def markov_chain(freq, word=None):
    while True:
        word = sample(freq, word)
        if word is None:
            break
        yield word

With those three function definitions in place, the rest of the code looks pretty straightforward:

with open("file.txt") as f:
    freq = frequency_table(f)
for word in markov_chain(freq):
    print(word, end=" ")


You can simply use thee vars() built-in function with a dictionary comprehension here:

def get_state(self):
    return {k: v for k, v in vars(self).items() if not inspect.isfunction(v)}

Note that the methods are usually defined in the class so they actually never show up in instance dictionary, while looking up for them Python can find them from the class dictionary. With that said, in case you defined a functions on the instance:

self.func = lambda: 'func called'

And then tried to run your code then you will notice that your code actually nukes that function itself from the instance when you call get_state, that's because you're deleting them from the instance dictionary. Don't do that, instead create a new dictionary.

class Dumpable:

    def __init__(self):
          self.x = 1
          self.y = 2
          self.func = lambda: 'func called'

    def get_state(self):
        no_funs = self.__dict__
        no_fun_list = [no_fun_key for no_fun_key in no_funs.keys() if inspect.isfunction(no_funs[no_fun_key])]
        for fun in no_fun_list:
            del no_funs[fun]
        return no_funs

d = Dumpable()
print(d.func())
print(d.get_state())
print(d.func())

Output:

func called
{'y': 2, 'x': 1}
Traceback (most recent call last):
  File "/home/ashwini/py/so.py", line 25, in <module>
    print(d.func())
AttributeError: 'Dumpable' object has no attribute 'func'

Other minor nitpicks:

To get the key as well as items from a dict use its .items() method.
To loop over a dict, never call its .keys() method. A dict is an iterable and iterating on it yields one key at a time. The .keys() can be very expensive in Python 2 where it actually creates a list of all keys first.
 -


Remove all vowels from a string except an initial character

removeVowels is not quite an accurate name.  Furthermore, by PEP 8, the official Python style guide, function names should be lower_case_with_underscores unless you have a good reason to deviate.  Therefore, I recommend renaming the function to remove_non_initial_vowels.

Your function crashes on string[0] if the input is an empty string.

I don't recommend writing string[1:], since that would entail making a temporary copy of nearly the entire string.

'aeuio' is a bit weird.  Why not 'aeiou'?  (I assume that for this exercise, you don't care that y is sometimes a vowel, w is a semivowel, and assume that the string contains no diacritics.)

Fundamentally, this operation is a fancy string substitution.  Typically, such substitutions are best done using regular expressions.

import re

def remove_non_initial_vowels(string):
    return re.sub('(?<!^)[aeiou]', '', string, flags=re.I)

The (?<!^) part of the expression is a negative lookbehind assertion that means "not at the beginning of the string".


you want a separate model for search, i.e.

class SearchResult < AR::Base
  #columns: content, title, user
  belongs_to :searchable, polymorphic: true
end

class Book < AR::Base
  has_one :searchable, polymorphic: true, class_name: 'SearchResult'
  belongs_to :user

  after_create :autobuild_searchable
  after_commit :update_search

  private

  def autocreate_searchable
    self.create_searchable
  end

  def update_search_content
    searchable.update_attributes(content: "#{title} #{author}", title: title, user: user.username)
  end
end

class SearchController
  def search
    @result = SearchResult.where("content like ?", "%#{params[:q]}%")
    if params[:user]
      @result = @result.where(user: params[:user])
    end
  end
end

Finally in view you can render the actual results, i.e.

= render @result.map(&:searchable)

(rails will render correct partial for each element, whatever it's book, magazine or anything, it will look for views/magazines/_magazine, views/books/_book)

You can extend the search with extra columns to use them as additional filters (here i've added user) and you don't pollute your models with extra search logic.
How will you handle the searchable content is up to you (here is just a primitive example). You can split it into separate columns (ie. search_field1, search_field2, search_field3), you can tokenize the input or build a fulltext index.

you can store a permalink in SearchResult or you can generate in on the fly. You may have some issues with rails path helpers on polymorphic associations, but those are easy to overcome.

If you have postgres as database i advise you to take a look on pg_search, it's simple and brilliant solution: https://github.com/Casecommons/pg_search and should give you better understanding on this topic.

The above code may not work, I didn't check it against Ruby/Rails, just trying to show an idea.


Filtering large lists and returning values that match a test

The problem with the solution posted in the question is that it goes
through all the possible combinations of two elements in the array
when this is not really needed.

The pseudocode for a more efficient strategy would be as follows:

Read and sort the integers
For each integer (a), calculate the lowest and highest values of (b) that satisfy the inequality
Look for the position in the array for those values (take advantage of the values being ordered, use binary search)
Note that all the numbers between the two positions found satisfy the inequality since they are ordered

In python code, it should be something like this:

import bisect

MIN_SUM_VALUE = -10000
MAX_SUM_VALUE = 10000

with open('large.txt', 'rU') as f:
    integers = sorted(set(int(item) for item in f))

count = 0
for index, a in enumerate(integers):
    # Low and high values of b that still satisfy the inequality
    b_low = MIN_SUM_VALUE - a
    b_high = MAX_SUM_VALUE - a

    # Look for the index in the array for the values above
    b_low_index = bisect.bisect_left(integers, b_low, index + 1)
    b_high_index = bisect.bisect_right(integers, b_high, index + 1)

    # Increment count by the number of values found
    count += b_high_index - b_low_index

print count

Note that the way to avoid repetitions is to restrict the binary search to look for b values whose position is after the a values in the array (that's the index + 1 parameter).

Edit: To get the actual sums printed the following snippet can be used:

for b_index in range(b_low_index, b_high_index):
    b = integers[b_index]
    print a, b, a + b


Producing triangles of asterisks based on height

You should read Naming guidelines and apply them to your code.
pyramid should be a local variable. Otherwise calling makeTriangle more than once will produce incorrect results.
There is no need for biggestOddNumber to be public.
singleElement should be a constant field.
You can use String.PadRight and String.PadLeft methods to pad the string with spaces (or any other character) from both sides. Instead of manually doing it in hard-to-understand loop.


Set openCV basic structures to zero in a unique way

If you want to zero a Matx, you can take advantage of its val public data member, which is a good old C array. Then you can rely on the standard library algorithm std::fill to set every element of the matrix to 0; the algorithm generally does static dispatch at compile time to call std::memset whenever possible. Using it should allow you to always be safe but also to be safe when possible:

template < typename Tp, int M, int N>
void zero( cv::Matx<Tp, M, N>& m ) {
  std::fill(std::begin(m.val), std::end(m.val), 0);
}

Since Matx::val is a fixed-size C array, std::begin and std::end should work. If you don't use a C++11 standard library, you can implement it as follows instead:

template < typename Tp, int M, int N>
void zero( cv::Matx<Tp, M, N>& m ) {
  std::fill(m.val, m.val + M*N, 0);
}

For cv::Mat, the documentation says that:

  To set all the matrix elements to the particular value after the construction, use the assignment operator Mat::operator=(const Scalar& value).

It means that you can zero the matrix like this (I couldn't find equivalent overloads for Matx or SparseMat):

inline void zero( cv::Mat& m ) {
  m = 0;
}

Also, as a side note, most modern compilers just don't care about inline, at least they don't take it as a hint for inlining since they already do a great job when it comes to inlining stuff. Nowadays, inline is just a way to solve ODR problems, which don't happen with templates. All of your functions are function templates, so you can safely remove inline.


Your AverageHalfSpreadIndicator doesn't implement IIndicator. I think you just forgot to

public class AverageHalfSpreadIndicator : IIndicator

You should instantiate your _lastUpdates:

public AverageHalfSpreadIndicator(IMarketDataFeed marketDataFeed)
{
    _lastUpdates = new List<MarketDataUpdate>();
    marketDataFeed.Update += OnMarketDataUpdate;
}

I don't like this code:

_lastUpdates.Add(updates);
if (_lastUpdates.Count == 20)
{
    _lastUpdates.RemoveAt(0);
}

I mean, it's fine, but I'd prefer to implement the _lastUpdates as a fixed sized queue. You can find many implementations on SO, for example: 1, 2, 3.

Also, your code is not thread-safe. If your code'd be called by many threads it'd break.

Don't use DateTime to measure execution time. There is a special class for this task: System.Diagnostics.Stopwatch.

var stopWatch = new Stopwatch();
stopWatch.Start();
var spreads = _lastUpdates.Select(x => 100 * (x.Mid - x.Bid) / x.Bid);
Console.WriteLine("Time to compute spreads: " + stopWatch.ElapsedMilliseconds + " ms");

var averageSpread = spreads.Average();
Console.WriteLine("Total time:" + stopWatch.ElapsedMilliseconds + " ms");
stopWatch.Stop();

This is not a big deal, but instead of encapsulating just Mid you can encapsulate whole 100 * (x.Mid - x.Bid) / x.Bidin your MarketDataUpdate.


Python program that checks connections based on URLLIB response

It's a neat idea, I like it! There is however a couple different things that could be done differently, while retaining the original idea.

Syntax

Have a look at PEP-8, it's a universal style guide for Python, it will give you an idea of how to style your code. As an example: functions, methods and variables should be snake_case, not mixedCase or CamelCase. While the use of the latter won't raise a syntax error, using PEP-8 is preferred.

Try to avoid wildcard imports (importing contents of entire libraries), as it will pollute your namespace. In the point below I suggest a library that's not part of the standard library, which should be separated from standard library imports, by one line.

import tkinter as tk

import requests

attemptConnect function

I would consider switching to a higher level web request solution, the requests library. It comes with all the features we need out of the box and additionally it provides an extremely handy Session object. Basically, it will use the underlying TCP connection making the subsequent requests faster. We will send a HEAD request, so the content won't be requested.

At first I thought the global variable is a counter of some sort, but a closer look made me realise it acts as a boolean variable. Why not make it one? This change will also have an effect in your ternary: "#38f789" if request_successful else "#ff6656".

I've taken the liberty to start changing function and variable names to follow PEP-8.

session = requests.Session()
...
def verify_url_status():
    global request_successful
    try:
        session.head('https://stackoverflow.com/')
        request_successful = True
        status_label.config(text="Connection Established", bg="#2ecc71", font="Bahnscrift 10")
    except requests.exceptions.ConnectionError:
        status_label.config(text="No Connection", bg="#e74c3c", font="Bahnscrift 10")
        request_successful = False

Classes

I have never worked much with tkinter, but this problem begs for the use of a class, encapsulating your code with it would make it more modular and would solve the need for a global variable. I will refer you to this tutorial, as it will be more comprehensive than what I know. If you haven't touched object oriented programming in Python yet, I'd recommend reading up on it as well. Below is the basic idea.

import tkinter as tk

import requests

class URLStatus:

    def __init__(self):
        self.session = requests.Session()
        self.request_successful = None
        self.master = tk.Tk()
        ...
        self.status_label = tk.Label(bg="#e67e22", fg="#fff", width=29, height=1, text="Pending", font="Bahnscrift 10")
        self.status_label.place(x=10,y=8)

    def verify_url_status(self):
        try:
            self.session.head('https://stackoverflow.com/')
            self.request_successful = True
            self.status_label.config(text="Connection Established", bg="#2ecc71", font="Bahnscrift 10")
        except requests.exceptions.ConnectionError:
            self.status_label.config(text="No Connection", bg="#e74c3c", font="Bahnscrift 10")
            self.request_successful = False


Finding out the prime factors of a number

The efficiency can be improved. As Simon already said, the condition

n != java.lang.Math.sqrt(n)

is equivalent to n != 1, and therefore not of much use.
Perhaps you meant something different: A composite number \$ n > 1 \$
must have a prime factor \$ p \$ for which  \$ p \le \sqrt n \$. Therefore,
as soon as md > java.lang.Math.sqrt(n) in your iteration,
n is either equal to 1 or a prime number.

The code then is

    long md = 2;
    while (md <= java.lang.Math.sqrt(n)) {
        if (n % md == 0) {
            System.out.print(" " + md);
            n /= md;
        } else {
            md++;
        }
    }
    if (n > 1) {
        System.out.print(" " + n);
    }

which reduces the number of iterations considerably:
For n = 64_548_621 the loop runs until md = 283 instead of
md = 25343.

Another small improvement is to repeatedly test a possible factor
in a while-loop, in order to save some square root computations
of the (updated) number n:

    long md = 2;
    while (md <= java.lang.Math.sqrt(n)) {
        while (n % md == 0) {
            System.out.print(" " + md);
            n /= md;
        }
        md++;
    }
    if (n > 1) {
        System.out.print(" " + n);
    }

A simple measure to reduce the number of iterations to about 50% is to
test the factor 2 separately, and then only odd numbers starting
at 3:

    while (n % 2 == 0) {
        System.out.print(" " + 2);
        n /= 2;
    }
    long md = 3;
    while (md <= java.lang.Math.sqrt(n)) {
        while (n % md == 0) {
            System.out.print(" " + md);
            n /= md;
        }
        md += 2;
    }
    if (n > 1) {
        System.out.print(" " + n);
    }

As pointed out by @CodesInChaos in a comment,
computing the square root of a long integer via floating point
arithmetic can suffer from rounding issues.
This would be an issue for numbers greater than 2^52.
From the analysis at How can you easily calculate the square root of an unsigned long long in C?
it follows that the difference between
(long)java.lang.Math.sqrt(n) and the correct
value \$ \lfloor \sqrt n \rfloor \$ is at most one.
Since only an upper bound is needed, replace the loop condition by

    while (md <= java.lang.Math.sqrt(n) + 1) {

If you want  reusable code then move the computation of
the prime factors in a separate function which returns the list
of primes. This also separates the computation from the I/O
and keeps the main function short:

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class PrimeFactorFinder {

    public static void main(String args[]){
        long n = 64_548_621;
        List<Long> factors = primeFactors(n);
        System.out.println(Arrays.toString(factors.toArray()));
    }

    static List<Long> primeFactors(long n) {
        List<Long> factors = new ArrayList<Long>();
        long md = 2;
        while (n % md == 0) {
            factors.add(md);
            n /= md;
        }
        md = 3;
        while (md <= java.lang.Math.sqrt(n) + 1) {
            while (n % md == 0) {
                factors.add(md);
                n /= md;
            }
            md += 2;
        }
        if (n > 1) {
            factors.add(n);
        }
        return factors;
    }
}


Creating website via SQL table and PHP object

It's simple. It looks nice enough.

But please, for the love of little Bobby Tables, bind your variables: http://www.wikihow.com/Prevent-SQL-Injection-in-PHP . That would work out to:

$stmt->bind_param("s", $pageName);

once you've created a prepared statement.

Also, consider using a numeric identifier which maps to a pageName, similar to how StackExchange maps 174740 to "creating-website-via-sql-table-and-php-object".

Wrap very long lines, please. After commas in your array() would be a good place.

You didn't show your schema. I hope you have a compound unique key on (page_name, ord). Perhaps it's your PK.

Sometimes HTML tags aren't perfectly nested, and such errors might become stored in your database. I don't know what the PHP equivalent of python BeautifulSoup is, but at the DB->web interface your loop has an opportunity to ensure only well-formed HTML is sent to clients.


jQuery function to display an alert when submitting blank fields

Your code can be refactor in multiple ways. To remove code repetition, create a new function for repeated code and use it as a callback of each filter.

function someFunc(e) {
  if (this.value === "") {
    alert('Please Fill In Or Remove The Blank Fields First')
    e.preventDefault();
    should_run = 0
  }
}

Use above function as

$('.key_field:not(:first)').filter(someFunc);

This will automatically remove redundant code as well as reduce number lines.

Suggestions:

Instead of playing around DOM and get value for each field separately, try to use serializeArray method of JQuery. See example

Please make habit to use ; to terminate line.

Hope this is helpful.


Regarding your validations - extract each of your validations in validation object.
You can do something like:

class Validator {

isValid(obj) {
//return false if obj is not valid
}

message(obj) {
//return error object if obj is not valid
}

status() {
//error status if validation fails
}

}

Then you can have like EmailValidator, Required, etc. implementation, which validates email strings, etc.
You then just iterate through all current validators and if any of them fails to validate, you use it's error message and status to return error object. That way you can easily configure this by editing current validator list and reuse them in different parts of code.


Clarity of Approaches

With the first approach, I look at it and I can tell straight away that you are reversing a string.  With the second approach, I need to study it for a minute or two to work out what you're doing.

Unnecessary Code

In the first approach, the check for an empty string is not necessary.  In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.

Performance

As you may know, strings are immutable objects in .Net.  It is good practice to use a StringBuilder to create strings in this way, like so:

var reversedString = new StringBuilder(input.Length);
for (int i = input.Length - 1; i >= 0; i--)
{
    reversedString.Append(input[i]);
}
return reversedString.ToString();


Finding sessions associated with an IP address using PDO

There are two main points of improvement:

First of all, never ever use die(error message) in your scripts. Neither try/catch should be ever used only to echo the error message out. You'd be surprised, but you will have more informative error message if just get rid of the whole try/catch/die stuff. Please read my article on PHP error reporting for the details
PDO code itself could be made more tidy, thanks to various helper functions PDO offers

So the whole code should be

$sql_ip = inet_pton($ip); // IPV6

$stmt = $pdo->prepare('SELECT 1 FROM sessions WHERE s_ipv4 = ? OR s_ipv6 = ?');
$stmt->execute([$sql_ip,$sql_ip]);

if ($stmt->fetchColumn()) {
    // Do something
} else {
    // No rows
}

Here I used positional placeholders for brevity, and sent your variables directly to execute for the same purpose.

Also I recommend to avoid rowCount() function as it would be more logical: in your code you are selecting some data, but never use it. Instead, I would suggest to use the actual data selected (just a literal "1" in your case, fetched directly using fetchColumn() method).


check features a well-known anti-idiom:

if (condition) {
    return false;
}
return true;

is a long way to say

return !condition;

Testing for j == N - 1 in a loop looks unappealing. The code would be much cleaner if the inner loop (which actually decides on the problem) were factored out into a function:

bool is_position_valid(....)
{
    ....
    for (int j = 0; j < N; j++) {
        if (check(....)) {
            paint(....);
        } else {
            return false;
        }
    }
    return true;
}

and the caller produced the required output.
The complexity is quadratic in both time and space. There is a way to drive the down to linear: have 4 arrays of sizes N, N, 2*N - 1, 2*N - 1 (for files, ranks, and left and right diagonals respectively), and for each queen mark a corresponding entry as taken; if the entry is already taken the position is invalid.


The code and the test look very good. I only found these nit-picks:

There's a typo in the method name Poppint.
The test sometimes uses Assert.IsTrue(a == b), which should be Assert.IsEqual(a, b).
The name underTop does not sound perfect to me, since it refers to a top, which is meaningless for a single node. A single node doesn't have a top, therefore I would call it next or below.
The property Size should be renamed to Count to align with the other collection types.
I prefer to have the same namespace for the main code and the testing code. But I don't know the official convention for organizing tests.


Vector with move constructor and move assignment operator

Default constructor

    MyVector():m_Size(0), m_pInt(nullptr)
    {   }

Stop trying to save space like that. THe point of good coding is to make it readable by humans. The computer can read any style so try and make it more maintainable by making it readable.

I would write it like this:

    MyVector()
        : m_Size(0)
        , m_pInt(nullptr)
    {}

Sure you can use nullptr for the zero sized array. But this seems like a premature optimization. You can make the rest of your code less complicated by never having a null m_pInt. If there is never a null then your code does not need to check for it.

Also currently you have different behavior for:

MyVector  x;
MyVector  x(0);

Constructor

    MyVector(int x)
       // Use the initializer list to initialize the elements.
    {
        m_Size = x;
        m_pInt = new int[m_Size];
        for (int i = 0; i < m_Size; ++i)
        {
            m_pInt[i] = i;
        }
    }

Print

Sure this works. But std::cout is not the only stream you way want to print too

    void print() const
    {
        for (int i = 0; i < m_Size; ++i)
        {
            cout << m_pInt[i] << endl;
        }
    }

So I would pass a stream to print(). It can default to std::cout. Then you should add an operator<<. As the normal way of printing something is via <<.

  MyVector  d(15);
  std::cout << d;

Note: prefer "\n" to std::endl. The difference is a stream flush. The stream will already flush itself when required. So you adding extra flushes is only going to cause the flushes to be less optimal.

Copy Constructor

    MyVector(const MyVector& rhs)
        // Use the initializer list
    {
        m_Size = rhs.m_Size;
        m_pInt = new int[m_Size];
        for (int i = 0; i < m_Size; ++i)
        {
            m_pInt[i] = rhs.m_pInt[i];
        }
    }

Move constructor

    MyVector(MyVector&& rhs):m_Size(move(rhs.m_Size)), m_pInt(move(rhs.m_pInt))
    {
        rhs.m_Size = 0;
        rhs.m_pInt = nullptr;
    }

Yes that works. But you should also mark the move constructor as noexcept. The standard containers have optimizations that can be applied if they know tour class will not throw when being moved. Otherwise they have to fallback to copying to provide the strong exception guarantee.

The standard technique is to use swap though. It makes it look and behave just like move assignment. See below.

Copy Assignment

Yes the test for self assignment looks like a good optimization.

    MyVector& operator=(const MyVector& rhs)
    {
        if (this != &rhs)
        {

BUT its not. Self assignment happens so rarely (in fact basically never in real code) that what you are doing is pesimizing the normal flow and as a result will make your code slower. You do need to cope with self assignment but because it is so rare you don't need to worry that it is not the optimal path.

The second issue I have here is that you destroy the local data before you have a copy of the new data ready.

            if (m_pInt != nullptr)
            {
                delete m_pInt;
            }

If something goes wrong in the rest of your code then you will be unable to roll back the state and thus can not provide the strong exception guarantee. When copying an object it should happen in three distict phases.

1. Copy the source into a temporary object.                  This is dangerous as exceptions can happen. So you must do this without changing the state of the current object.
2. Swap the state of the current object with the temporary.  Swapping is supposed to be exception safe. So you can safely change the state of your object.
3. Now you can release the old resources.                    This is unlikely to go wrong; But even if something goes wrong your object is in a good state.

So your Copy assignment should look like this:

MyVector& operator=(const MyVector& rhs)
{
    // Make a copy to temp
    std::size_t tSize = rhs.m_Size;
    int*        tInt  = new int[tSize];
    std::copy(rhs.m_pInt, rhs.m_pInt + rhs.m_Size, tInt);

    // Now swap with your current object state.
    std::swap(tSize, m_Size);
    std::swap(tInt,  m_pInt);

    // now destroy the old data;
    delete [] tInt;

    // Done
    return *this;
}

If you look carefully at those three stages. Stage 1 looks like the constructor and stage 3 looks like the destructor and stage 2 looks like a standard swap function so we can simplify the above to exactly that:

MyVector& operator=(const MyVector& rhs)
{
    MyVector  temp(rhs);        // 1. Copy
    temp.swap(*this);           // 2. Swap

    // Done
    return *this;
}                               // 3. delete done by destructor.

This is called the copy and swap idiom.

Move Assignment

Again the pesimizing test for self assignment.

    MyVector& operator=(MyVector&& rhs)
    {
        if (this != &rhs)

The standard move assignment is to swap the source and the destination. This has a couple of benefits.

You don't call delete (and thus don't invoke the destructor). Thus it is potentially faster.
Because you did not delete the data there is an opportunity for it to be reused.
If the source is going out of scope it will invoke its destructor and destroy your data but it will be done after the completion of your object thus giving you strong exception guarantee. Thus allowing you to make your assignment operator noexcept.

Standard Move Assignment

MyVector& operator=(MyVector&& rhs) noexcept
{
    rhs.swap(*this);
    return *this;
}

I wrote a series of posts about all this.

Vector - Resource Management Allocation
Vector - Resource Management Copy Swap
Vector - Resize
Vector - Simple Optimizations
Vector - the Other Stuff

Re-Write

class MyVector {
    size_t m_Size;
    int*   m_pInt;
public:
    ~MyVector()
    {
        delete[] m_pInt;
    }

    MyVector(int x = 0)
        : m_Size(x)
        , m_pInt(new int[m_Size])
    {
        for (int i = 0; i < m_Size; ++i)
        {
            m_pInt[i] = i;
        }
    }

    void print(std::ostream& str = std::cout) const
    {
        for (int i = 0; i < m_Size; ++i)
        {
            str << m_pInt[i] << "\n";
        }
    }
    friend std::ostream& operator<<(std::ostream& str, MyVector const& data)
    {
        data.print(str);
        return str;
    }

    MyVector(const MyVector& rhs)
        : m_Size(rhs.m_Size)
        , m_pInt(new int[m_Size])

    {
        std::copy(rhs.m_pInt, rhs.m_pInt + rhs.m_Size, m_pInt);
    }

    MyVector(MyVector&& rhs) noexcept
        : m_Size(0)
        , m_pInt(nullptr)
    {
        rhs.swap(*this);
    }

    MyVector& operator=(MyVector const& rhs)
    {
       MyVector  t(rhs);
       t.swap(*this);
       return *this;
    }

    MyVector& operator=(MyVector&& rhs) noexcept
    {
        rhs.swap(*this);
        return *this;
    }

    void swap(MyVector& other) noexcept
    {
        using std::swap;
        swap(m_Size, other.m_Size);
        swap(m_pInt, other.m_pInt);
    }
    friend void swap(MyVector& lhs, MyVector& rhs)
    {
        lhs.swap(rhs);
    }
};


First things first, you can compare your solution with some of the other calculator implementations in Java on this site. :)

Names in Java

The naming convention used in Java is camelCase for field names, and preferably the singular form for class names. The preference is such that you have instance-s of a Customer class, not Customers.

You have an inconsistent approach to your field names (input, Iteration), and since you are getting started in Java, I will suggest sticking to the naming convention so tha it's easier for you to read and understand other Java code using the same convention, in the long run.

Class inheritance

You may have misunderstood the usage of class inheritance given the extent of having two classes (Multiplication, Calculations) extending another (Main) when they don't share a common... state.

First, your Multiplication class name is ill-advised. When I first looked at it, I thought you were going to create sub-classes for all four arithmetic operators. It turns out that Multiplication implements them as four methods. Furthermore, the only relation between this class and the parent class Main is the sharing of a single static field Result (I'll get to this later).

The usual approach for this kind of functionality is to re-think how your arithmetic methods take in two inputs to give you an output. Setting aside the float-or-double question, you should consider having methods like this:

public static float plus(float a, float b) {
    return a + b;
}

Method visibility modifier is public as it is likely to be used outside the class, not because everything defaults to public.
static method as the calculation only depends on the two method arguments, and no other class state.
The use of the two method arguments makes it clear what the inputs are, rather than letting callers of the method guess how they need to pass it in.
Again, the use of the return type also makes it clear where the output is going - back to the caller of this method.

If you still prefer to have these four methods in a standalone class, give your Multiplication class a quick rename (CalculatorUtils?) and you can safely - and should - remove the extends Main declaration: it is simply not needed.

Second, your Calculations class looks... messy. It's messy in the sense that:

It's magically responsible for instantiating your Multiplication class,
It has poorly-named method names, and
It doesn't require anything from the Main class, other than the static methods.

So, once again, you will not need extends Main here. Furthermore, when you have the static methods suggested above from the now-renamed CalculatorUtils class, your switch statement should resemble something more like this:

public static float compute(String operator) {
    // assume that you have a method `getFloatInput()` that returns a float
    switch (operator) {
        case "+":
            return CalculatorUtils.plus(getFloatInput(), getFloatInput());
        case "-":
            return CalculatorUtils.minus(getFloatInput(), getFloatInput());
        case "*":
            return CalculatorUtils.multiply(getFloatInput(), getFloatInput());
        case "/":
            return CalculatorUtils.divide(getFloatInput(), getFloatInput());
        default:
            throw new IllegalArgumentException("Invalid operator.");
    }
}

In fact, you may also want to consider combining both classes together, and exposing the float inputs in the method signature too:

// final is used here to prevent sub-classing, since it's not really required
public final class CalculatorUtils {

    private CalculatorUtils() {
        // private constructor to prevent instantiation, this class
        // is meant to be used solely through its static methods
    }

    // now that we have the compute() method, perhaps we no longer
    // need these methods to be accessible outside of this class
    private static float plus(float a, float b) {
        return a + b;
    }

    // ...

    public static float compute(String operator, float a, float b) {
        switch (operator) {
            case "+":
                return plus(a, b);
            case "-":
                return minus(a, b);
            case "*":
                return multiply(a, b);
            case "/":
                return divide(a, b);
            default:
                throw new IllegalArgumentException("Invalid operator.");
        }
    }
}

Class state vs static fields

The one thing that strikes out as odd to me in your code is the heavy reliance on static fields and methods with void return types. This indicates that while you seem to think you need inheritance here (when you don't, see above section), you have forgotten about how to make effective use of class methods to pass information around explicitly, instead choosing to rely on a global state.

From a beginner's point-of-view, I think the biggest obstacle to using static fields (not methods) throughout is that it makes your own code harder to understand in the long run. The reader has to memorize where these fields appear, and how they are modified throughout the codebase. If I may draw from my earlier example again, compare your Multiplications method:

public void  basicAdd(){
    Result = Result + secondInput;
}

Where are Result and secondInput from, and their type?
How can the method caller retrieve the result of incrementing Result?

With my suggestion:

public static float plus(float a, float b) {
    return a + b;
}

This method takes in two float values.
It returns the result of adding the values together directly to the method caller.

Doing iterations

You have a weird way of iterating through methods. Instead of using loop structures, you have your methods repeatedly calling each other at the end as such (// Here... // And here.):

public class Calculations extends Main{
    public void sortCalc(){
         getCalc = getInput("'+' '-' '*' or '/' or 'Done'");
         calcSwitch(); // Here...
    }

    private void calcSwitch(){
        switch(getCalc){
        case "+":
            getIteration();
            calculation.basicAdd();
            sortCalc(); // And here.
            break;
        // ...
    }
}

The downside of methods calling each other is that it's inefficient since the JVM will be also have to be busy with increasing the call stack. For example, this is how your oddly-named tryCatchMethod() can be improved:

// instead of wrapping a BufferedReader/InputStreamReader over System.in,
// you can also consider something like Scanner scanner = new Scanner(System.in);
// and pass that *one* instance here
private static float getFloatInput(Scanner scanner) {
    while (scanner.hasNextLine()) {
        try {
            return Float.parseFloat(scanner.nextLine());
        } catch (NumberFormatException e) {
            System.err.println("Invalid float input.");
        }
    }
    throw new RuntimeException("No input encountered.");
}

Putting it altogether

Given the relatively simple approach we have here, you probably do not require any class state, since you can easily pass your numeric inputs around well-specified methods to get your results. For example, in your main() method, you only require something like the following (try-with-resources is recommended on the Scanner instance since you appear to be at least on Java 7):

public class Main {

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            float result = getFloatInput(scanner);
            String operator;
            while (!(operator = getOperatorInput(scanner)).equals("Done")) {
                result = CalculatorUtils.compute(operator, result, getFloatInput(scanner));
                // print intermediate result here?
            }
            System.out.println("The result is :" + result);
        }
    }
}


Each token must be;

  non-sequential
  non-guessable
  unique

Without reading into any of the OAuth specifics, if the above is the only criteria to which you must adhere, then I would suggest what you're doing is quite a huge effort to achieve what's already been done with GUID (Globally Unique Identifier).

Java has an implementation of this, a class named UUID:

  ...that represents an immutable
  universally unique identifier (UUID).
  A UUID represents a 128-bit value.

Conveniently, a GUID is also a 32 character string.

Some code I found to utilise this using Java:

UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();

Note that I'm not really qualified to be an authority on this where Java is concerned, though the topic I'm concerning myself with here is very transferable, you will need to determine whether A) a GUID satisfies all criteria of an OAuth token, and B) that the Java implementation works as the rest of the world expects - I can't vouch for that.


Create a template class for same algorithm different type of member variable

I'm not sure I understand exactly what you're going for, but I think your Base_template has way too many parameters. You have:

template <typename Data, typename... Data_arg>
class Base_template {
public:
    Base_template(Data_arg...data_arg): _data(data_arg...) {}
    void set_all() {
        for (int i = 0; i < _data._size; ++i) _data[i] = _val;
    }
protected:
    int _val;
    Data _data;
};

but I think all you want is:

template <typename Data>
class Base_template {
public:
    template<typename... Args>
    Base_template(Args&&... args): _data(std::forward<Args>(args)...) {}
    void set_all() {
        for (int i = 0; i < _data._size; ++i) _data[i] = _val;
    }
protected:
    int _val;
    Data _data;
};

Also, notice in passing that your naming convention of "leading underscore" might lead you into conflict with reserved identifiers if you're not super careful. I prefer to use "trailing underscore" for private member variables, just so that I don't have to think about the complicated reserved-identifier rules at all.


Better pythonic way to pass condition to multiple functions

Your example is a little too example-y for me to know if this is actually right for whatever you're actually doing, but if you have two parallel implementations of a set of behavior within the same set of functions, you might think about moving them into classes:

from abc import ABC, abstractmethod

class CondFile(ABC):

    @abstractmethod
    def get_root_path(self) -> str:
        pass

    @abstractmethod
    def get_filename(self) -> str:
        pass

class CondTrueFile(CondFile):

    def get_root_path(self) -> str:
        return "something"

    def get_filename(self) -> str:
        return "file name A"

class CondFalseFile(CondFile):

    def get_root_path(self) -> str:
        return "something else"

    def get_filename(self) -> str:
        return "file name B"

if is_cond_met:
    cond_file = CondTrueFile()
else:
    cond_file = CondFalseFile()
print(cond_file.get_root_path())
print(cond_file.get_filename())

It really depends what the condition represents, but if it results in completely different behavior across fifteen functions, it's a good clue that it represents a different "kind of" thing that your program is dealing with, i.e. a type, which is in turn a good clue that you want a different class to represent that type in your code.


Valid. But your code is messy. You are taking one step away from the original traditional problem, and that actually becomes a problem form your code.

Your actually better off with the one dimensional arrays then the two dimensional tuples. Tuples may be the wrong data type to use for your problem to resolve itself nicely.

Styling notes:
This:

def dot_product(v1, v2):
    ...

suggest to me that v1 and v2 are vectors, not a list of vectors, but by changing to:

def dot_product1(v1: [()], v2: [()]):
    ...

the obscurity magically disappears.

This method of commenting your code is called annotations and is commonly used in python, I like them a lot.

The

    ...
    return result
if __name__ == "__main__":
    ...

could be more readable if:

    ...
    return result

if __name__ == "__main__":
    ...

An analogue solution which will scale better is

def get_pointers(v: tuple):
    return {key: value for key, value in enumerate(v) if value}

def sparse_vector_dot(a: dict, b: dict):
    result = 0
    for key, value in a.items():
        if key in b:
            result += b[key] * value
    return result

def main():
    a = (2, 4, 0, 0, 0, 6)
    b = (0, 3, 4, 0, 0, 7)
    a, b = get_pointers(a), get_pointers(b)
    print(sparse_vector_dot(a, b))

and the function sparse_vector_dot could be written as:

def sparse_vector_dot_oneliner(a: dict, b: dict):
    return sum(b[key]*value for key, value in a.items() if key in b)

It will scale better since we are never checking what we don't have to check, the only thing we have to check is if there is a corresponding index in the other list (now dict).


React container component to fetch paginated data for a stateless table component

Question 1

  Is this all reasonable?

Absolutely!

  Question 2

  I noticed that the component will re-render when it receives a new
  currentPage and then re-renders again, once the data is loaded. The
  first re-render is not necessary as nothing changes before data is
  actually loaded. Should I just live with this or should I implement
  shouldComponentUpdate() to check if data has changed. Or is that
  potentially even more costly than the re-render itself?

This is normal, and I wouldn't worry about it. In fact, not having to worry about these types of things is a major goal of React.

It's important to realize that re-renders in React only update the DOM when there are changes and only update the relevant DOM nodes. DOM operations are very time consuming, because DOM objects are incredibly heavy objects, and updates have knock-on effects. This is one of the main reasons React doesn't use DOM objects internally. Instead, it uses a virtual DOM. Through a process called reconciliation, React can update the real DOM from the virtual DOM incredibly fast.

In the state where the page changes, but you don't have data yet, React will call render(), very quickly realize there are no changes to the element tree, then stop - this probably happens in roughly a millisecond.

On that note, you do need to be careful when you use Redux - specifically react-redux / connect(). Try to keep mappings of state to props as minimal as possible – don't map an entire object from the Redux tree to a prop for a component if you only need one property of that object. The reason this is important, is because:

Your reducers generate new objects every time they run (if you're using them correctly)
Redux and React use JavaScript's default comparison when deciding if it should update a component
Every object is distinct in JavaScript, even if their structure is identical

So a reducer takes one object, then generates a new object, and even if the properties of these objects are exactly the same, React/Redux will treat it like a change and update components. This is OK for one component, but if you make this a habit your application, you'll be missing out on one of React's biggest features: performance.

// Do this:

const GoodComponent = (props) => `page number: ${props.page}`;

connect(state => {
  page: pagination.page
})(GoodComponent)

// ... not this:

const BadComponent = (props) => `page number: ${props.pagination.page}`;

connect(state => {
  pagination: pagination
})(BadComponent)

  Question 3

  Is using componentDidUpdate() to check if currentPage has changed and
  then re-load the data a good way of controlling the load process?

Absolutely - this is probably why componentDidUpdate() was created.

  Question 4

  Is building the URL this way acceptable?

  const pageParam = currentPage ? "?_page=" + currentPage : "";
  fetch('https://jsonplaceholder.typicode.com/posts/' + pageParam)

It's probably OK for now, although you could use template literals. I generally avoid constructing the query string manually, except for the simplest cases. This is because the second you have multiple query params and some of them are optional, the construction gets tricky – what adds the question mark? how to handle trailing ampersands? trailing question mark?. Instead, use the URL API's searchParams property. Or, find a library that gives you more conveniences, like being able to provide query params as a dictionary/object in fetch()'s second argument.


Makes a navbar for a website with object oriented php

I think you have some reading/research to do as I'm not sure you understand OOP...

What is Main?

Main is setup as a class, used as a namespace in instantiation, then extended(why?).
Generally in the context it seems to be intended to be used App or <AppName> are better options

When to extend

Why do all elements extend Main?

It appears to be solely for it's constructor which it never uses itself. (Extra Baggage in Main)
Main also only contains functions the other elements never need or use (Extra Baggage in the Sub-Objects)

Extending a class makes more sense if the classes extended from it share functionality

What even is an Object? ##

You seem to be using your objects as functions disguised as things.

For example: when you create a navItem:
You create the object
It's controller prints itself to the screen
You capture it in a variable never to be used again. Why?

Who gets to be an Object?

navItem is an object navBar Isn't
navDropdown is an object navDropdownItem isn't


Class for multithreaded insert into database

As mentioned by jcfollower, you have two sections that are deeply indented. These should be extracted into sub-methods. It will make the code easier to follow and not cause the text to bunch up at the right side of the screen.

More importantly, it is currently hard to tell what is actually happening with all the for loops and if clauses. Well named methods will provide context to the reader. When I'm looking at run(), I'm not concerned with how each filed is updated. I just want to know the main tasks that are being done. Then, once I have a high level understanding, I can dive done into the implementation details to check if the updates are done correctly and efficiently1.

Specify the queue read timeout as a constant instead of a magic number. If you find the the value needs to be tuned, it will be easier to find.

self.model_for_update.objects.filter(article__in=products_and_articles['articles'])

Is the double underscore in the argument name intentional? Python has a convention for when double underscores are used and separating words in variable names is very different from the convention.

Does product_bulk_create() put some restriction on articles_for_create such that it must be a list? Unless that is the case, using the set returned by the set subtraction should be sufficient.

products_and_articles is a odd name for a variable. You never have an operation that directly uses the whole dictionary. You are just passing references of the respective lists. Instead, you can replace the dictionary with a tuple and unpack the values directly into variables.

products, articles = self.import_queue.get(block=True, timeout=20)

1 For loops that are nested 3 and 4 deep are flags that there might be an inefficient algorithm.


Refactoring based on OPEN CLOSE PRINCIPLE- C#

You should create an interface from which you can make many implementations, e.g. an ILogger interface with Warning, Error methods etc.
Then you would create an implementation per logging type (one for console, one for SignalR etc). You could then inject the ILogger into any type that requires it (or another approach is to use a static field and resolve the logger through a static log manager type).
You might also want to consider a library such as Common.Logging which already provides an interface and several implementations already available, e.g. NLog, log4net etc.
Another consideration is whether you wish to mix business logic and logging code. Other alternatives are an AOP approach (PostSharp is one option) or semantic logging.


Security

  Is this code correct and secure?

Probably not.

EDIT: I just read your comments about the input being checked elsewhere (which might invalidate my answer somewhat, depending on how you check the user input). You should really check user input right before database interaction. Otherwise it will become unmaintainable really quick (you will always ask yourself if you already checked it, and you will inevitably forget to do it in some places, as you falsely believe you already checked them).

SQL Injection

You are missing the part where you actually retrieve user input, but the code you did post looks pretty open to SQL injection (which in general means that an attacker can for example bypass a login, can steal data from the database, and possibly write to a file/read from a file, change data, etc).

You should really stop using mysql immediately, and you should start using prepared statements (either with mysqli or PDO).

Concrete Attacks

For your concrete query, it might not look like an attacker can do all that much with this injection (the data is not displayed, and the login actually cannot be bypassed). But that is actually not true, as blind SQL injection is possible if the attacker knows a valid school and login id (blind sql injection means that you ask true/false questions, eg "is the first character of the first user in ascii smaller than 100? yes? is it also smaller than 60?", and so on; this does generate quite a bot of requests, but getting the database user or admin is certainly doable in short amount of time). You should be able to test this by injecting $school_login_id = valid id and $admin_login_id = valid id ' and 1=1 # (you might need a valid password as well) and then doing the same thing again with 1=2, which should give you a different result (meaning you can post yes/no questions to the database).

If the database user is allowed to write to a file, that would also be a possible attack vector.

Also, it should be possible to login as any user if the attacker knows the password of a specific user (by database id). An injection could look like this: $school_login_id = desired school name, $admin_login_id = desired user id' or 1=1 limit 1,1 # with the password not of the desired user, but of the first user in the database (this becomes a lot easier if you expose database ids to endusers).

To summarize: If you do not use prepared statements (or at least something) to defend against SQL injections, there will always be a way to exploit it.

Hashing, Comparison, Misc

  given that there are no credit cards or personal details involved, is this robust enough?

For password hashing, bcrypt is generally recommended over simple one-round sha256 hash. Weak hashing might actually be ok for your security requirements, but as bcrypt is actually easier to use in PHP (it manages salts for you), and is more secure, why not use it?

Also, for hash comparisons, you should not use ==, but a timing safe function such as hash_equals to avoid timing attacks.

Also, currently it looks as if your query logs might be in a public directory. If so, that is a really bad idea (exposes database names, etc; invalid logins might be mistypes, also exposes valid logins).

Misc

be consistent with your names. Eg $school_login_id vs S.login_name (is it an integer, as id implies, or a string as name implies?).
your indentation is off, which makes it really hard to see what else belongs to what if.
I would get rid of $return_result. Just return false at the end, and in the middle return $hash_from_entered_pass == $db_pass_hash directly.
global variables generally hint towards bad design.


About long polling

To clarify about long polling, from wikipedia:

  With long polling, the client requests information from the server exactly as in normal polling, except it issues its HTTP/S requests (polls) at a much slower frequency. If the server does not have any information available for the client when the poll is received, instead of sending an empty response, the server holds the request open and waits for response information to become available. Once it does, the server immediately sends an HTTP/S response to the client, completing the open HTTP/S Request. In this way the usual response latency (the time between when the information first becomes available and the next client request) otherwise associated with polling clients is eliminated.

In particular, paraphrasing the key points:

The client issues its requests at a slow frequency: this is not true in your implementation, you poll the server in sequence without an explicit delay in between requests. But maybe you're ok with that.
When the information is not available at the time of the request, the server holds the request open, and responds when the information is ready: this is to implement on the server side, of course, and not visible in the posted code.

About your main questions

  Is it the right approach for the long polling, or do you want to suggest a better approach? Also, a IntentService starts when you turn on the phone to run that code, would be better to use a Service?

An AsyncTask calling itself repeatedly... sounds a bit strange.
Also, the doc says this:

  AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

Although a single polling action is short,
your desired behavior is repeated polling for presumably a long time (you did not include a termination condition).
As such, an IntentService sounds like a better approach:

  In most cases an IntentService is the preferred way to simple background operations.

Code review

Although following the recommendations above you might well reimplement using an IntentService,
the original code has some interesting issues worth reviewing:

The AsyncTask is defined to return a String, but it's not used at all.
You can get rid of that, and then you won't need the EntityUtils.toString call anymore
The code in your post doesn't catch exception,
even though some should be thrown,
for example IOException during HTTP requests.
You should add some error handling for that.
Instead of hardcoding the URL inside the class,
it would be better to make it a parameter (initialize in the constructor).

Something like this:

private class LongPolling extends AsyncTask<String, Void, Void> {
    private final URI uri;

    private LongPolling(URI uri) {
        this.uri = uri;
    }

    @Override
    protected Void doInBackground(String... params) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(uri);
            httpClient.execute(httpPost);
        } catch (IOException e) {
            // server down? maybe you should let the client know!
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        new LongPolling(uri).execute();
    }
}


Credit card validator using Luhn Algorithm

For making your code faster, we can choose more Pythonic ways in some parts of it.
First, let's take a look at convertToList function. The goal of this function is to split digits of a number to a list of int values. I want to follow your algorithm and do this by converting the number to the str and then splitting it.

I want to do this by "List Comprehension":

def convert_to_list(num):
    result = [int(x) for x in str(num)]
    return result

We made some changes here. First of all, I changed the name of the function from camelCase (convertToList) to snake_case (convert_to_list) because according to the Python style guide, it is the better way. You can read more about the Python style guide at PEP8.

Next change is I replaced all your code with a single line list comprehension. The first advantage, we have written less code. Less code means probably fewer bugs.

But the second advantage here is this code is so much faster. How much? I have written a simple script for it; the result is that on average, the second version is 1.7 times faster.

Now let's move on and take another look at addDigits function. I want to choose pythonic way again here:

def sum_of_digits(number):
    num_list = convert_to_list(number)
    return sum(num_list)

Like the previous time, I changed the name. I think this name is clearer and everyone could tell what this code does.

For converting the number to a list of digits, I used convert_to_list function instead of writing the whole code again. We are using functions to avoiding duplication, so I think it's a bad idea to write the same code here. For calculating the sum of digits in a list, I strongly recommend you that always use built-in function sum. It's faster, you don't need to write new code and every Python programmer can tell what you are doing at first glance. This code is somehow 1.2 times faster than previous.

Now let's go to the beginning of your code. We want to parse command line parameters and be sure that the input is correct.

Even though we only call those codes once, I think it is a great favor to the readability of the code to move those lines in a separate function.

from re import search

def get_input_from_cmd(args_list):
    if len(args_list) != 2:
        raise Exception("You should enter a 16-digit number as input argument")
    return args_list[1]

def is_input_valid(input_str):
    return bool(search(r"\d{16}", input_str))

I separated your code into two functions. The first function gets argv list as an input parameter and if its length is equal to 2, returns the second parameter. Else, it will raise an Exception. There are a lot of people out there who are against exceptions and I agree with most of their reasons. But when we want our program to stop when a bad input came in, I think using exceptions is the best way.

The second function simply uss search function of re module. It checks that the input string only contains 16 digits. If that assumption will be true, True will be returned. Otherwise, the False value is what you get.

Now you can change your main function like this:

def main():
    input_string = get_input_from_cmd(sys.argv)
    if is_input_valid(input_string):
        digits_list = convert_to_list(input_string)
        card_checking_sum = card_check(digits_list)
        if card_checking_sum % 10 == 0:
            print('Valid Card!')
        else:
            print('Invalid Card!')
    else:
        print("Invalid Card number")

What we do is if card number is not a 16-digit number, code in the last else will execute. Otherwise, codes in the first if will run. That looks nicer to me.

So now let's go to the last function, the cardCheck.

def card_check(digits_list, count=0):
    result = 0
    if count % 2 == 0:
        digits_list[count] *= 2
        if digits_list[count] >= 10:
            digits_list[count] = sum_of_digits(digits_list[count])
    if count < 15:
        card_check(digits_list, count + 1)
    else:
        return 0
    result += sum(digits_list)
    return result

There were some problems in your code that I tried to fix. First, you don't need to put if conditions in parentheses. In python, don't need means you should not.

Second, if you run the same code in if and else; you should take that part of code away from if statement. That is what I did with card_check(digits_list, count + 1) line. That line was repeated needlessly.

In the end, for logical operations, you should use operators like and and or, not & and |.

Here is the full code. I hope that helps you:

from re import search
import sys

def get_input_from_cmd(args_list):
    if len(args_list) != 2:
        raise Exception("You should enter a 16-digit number as input argument")
    return args_list[1]

def is_input_valid(input_str):
    return bool(search(r"\d{16}", input_str))

def convert_to_list(num):
    result = [int(x) for x in str(num)]
    return result

def sum_of_digits(number):
    num_list = convert_to_list(number)
    return sum(num_list)

def card_check(digits_list, count=0):
    result = 0
    if count % 2 == 0:
        digits_list[count] *= 2
        if digits_list[count] >= 10:
            digits_list[count] = sum_of_digits(digits_list[count])
    if count < 15:
        card_check(digits_list, count + 1)
    else:
        return 0
    result += sum(digits_list)
    return result

def main():
    input_string = get_input_from_cmd(sys.argv)
    if is_input_valid(input_string):
        digits_list = convert_to_list(input_string)
        card_checking_sum = card_check(digits_list)
        if card_checking_sum % 10 == 0:
            print('Valid Card!')
        else:
            print('Invalid Card!')
    else:
        print("Invalid Card number")

if __name__ == '__main__':
        main()


Creating lists of events (pitches, velocities, delta-times, durations) from a MIDI track

Your notion of average tempo makes little sense.  A track with four minutes of ♩=120 followed by a 12-second coda of ♩=60 would have a reported average tempo of 90.  A more reasonable average would be to divide the total number of beats by the elapsed time.

$$\frac{120 \frac{\textrm{beats}}{\textrm{min}} × 4\   \textrm{min} +
         60 \frac{\textrm{beats}}{\textrm{min}} × 0.2\ \textrm{min}}
       {4.2\ \textrm{min}} \approx 117 \frac{\textrm{beats}}{\textrm{min}}
$$


Efficiently creating a menu consisting of multi-level structure

@hjpotter92 makes a good point: mysql_* is deprecated and should be replaced with mysqli_* or PDO. It's probably easier to replace it with the former, but it may help to read this article comparing mysqli and PDO.
$this->areThereKids() is a terrible method name. It's even worse that it returns "yes" or some other value. Refactor this to $this->hasKids() (or better yet, $this->hasChildren()), returning either boolean true or false.

Similarly, $this->getMyKids() could be better named $this->getChildren(), but this is not as egregious as the point above.

or die(mysql_error()) is tolerable in development code, but should be avoided in production code. Instead, prefer to print a user-friendly error or apologetic message, and log the details separately.
You are correct in that your code lends itself naturally to recursion. I'm not interested in writing the recursive function for you, but notice in particular that in every level of nesting,

you use the same template for output.
you have the variables $info and $id.
if there are children, you store them in a variable $children and you iterate through them, using the same template and variables.

I welcome you to try implementing the recursive function on your own, keeping the above three points in mind. When you've done so, you can submit your revised code here for another review!


Whilst your code is thread safe, since you have a global lock protecting the dictionary (and the lock is relatively long lived), it will be a serious bottleneck under concurrent load. The principal scalability limit in concurrent applications is the exclusive resource lock.
The chart below shows throughput with an increasing degree of parallelism on a 16 core VM for concurrent LRU reads and writes. It compares an implementation of LRU that does not have a global lock, to an implementation fundamentally the same as your code (with a global lock).

In this test I set the concurrent dictionary concurrency level = number of threads. I believe the unusual dip at the beginning is caused by false sharing. It's old now, but gallery of processor cache effects has a nice description.
The implementation with better throughput is a thread safe pseudo LRU designed for concurrent workloads. Latency is very close to ConcurrentDictionary, ~10x faster than MemoryCache and hit rate is better than a conventional LRU algorithm (these are the other two factors that will determine performance). A full analysis provided in the github link below.
Usage of the ConcurrentLru looks like this:
int capacity = 666;
var lru = new ConcurrentLru<int, SomeItem>(capacity);

var value = lru.GetOrAdd(1, (k) => new SomeItem(k));

GitHub: https://github.com/bitfaster/BitFaster.Caching
Install-Package BitFaster.Caching

Below is the complete source code for the ClassicLRU tested above. It has shorter span locks and uses ConcurrentDictionary. It's not intended for production use (it may have bugs) - it's just to illustrate that even when taking narrow locks throughput is still bad under concurrent load.
public sealed class ClassicLru<K, V> : ICache<K, V>
{
    private readonly int capacity;
    private readonly ConcurrentDictionary<K, LinkedListNode<LruItem>> dictionary;
    private readonly LinkedList<LruItem> linkedList = new LinkedList<LruItem>();

    private long requestHitCount;
    private long requestTotalCount;

    public ClassicLru(int capacity)
        : this(Defaults.ConcurrencyLevel, capacity, EqualityComparer<K>.Default)
    {
    }

    public ClassicLru(int concurrencyLevel, int capacity, IEqualityComparer<K> comparer)
    {
        if (capacity < 3)
        {
            throw new ArgumentOutOfRangeException("Capacity must be greater than or equal to 3.");
        }

        if (comparer == null)
        {
            throw new ArgumentNullException(nameof(comparer));
        }

        this.capacity = capacity;
        this.dictionary = new ConcurrentDictionary<K, LinkedListNode<LruItem>>(concurrencyLevel, this.capacity + 1, comparer);
    }

    public int Count => this.linkedList.Count;

    public double HitRatio => (double)requestHitCount / (double)requestTotalCount;

    ///<inheritdoc/>
    public bool TryGet(K key, out V value)
    {
        Interlocked.Increment(ref requestTotalCount);

        LinkedListNode<LruItem> node;
        if (dictionary.TryGetValue(key, out node))
        {
            LockAndMoveToEnd(node);
            Interlocked.Increment(ref requestHitCount);
            value = node.Value.Value;
            return true;
        }

        value = default(V);
        return false;
    }

    public V GetOrAdd(K key, Func<K, V> valueFactory)
    {
        if (this.TryGet(key, out var value))
        {
            return value;
        }

        var node = new LinkedListNode<LruItem>(new LruItem(key, valueFactory(key)));

        if (this.dictionary.TryAdd(key, node))
        {
            LinkedListNode<LruItem> first = null;

            lock (this.linkedList)
            {
                if (linkedList.Count >= capacity)
                {
                    first = linkedList.First;
                    linkedList.RemoveFirst();
                }

                linkedList.AddLast(node);
            }

            // Remove from the dictionary outside the lock. This means that the dictionary at this moment
            // contains an item that is not in the linked list. If another thread fetches this item,
            // LockAndMoveToEnd will ignore it, since it is detached. This means we potentially 'lose' an
            // item just as it was about to move to the back of the LRU list and be preserved. The next request
            // for the same key will be a miss. Dictionary and list are eventually consistent.
            // However, all operations inside the lock are extremely fast, so contention is minimized.
            if (first != null)
            {
                dictionary.TryRemove(first.Value.Key, out var removed);

                if (removed.Value.Value is IDisposable d)
                {
                    d.Dispose();
                }
            }

            return node.Value.Value;
        }

        return this.GetOrAdd(key, valueFactory);
    }

    public bool TryRemove(K key)
    {
        if (dictionary.TryRemove(key, out var node))
        {
            // If the node has already been removed from the list, ignore.
            // E.g. thread A reads x from the dictionary. Thread B adds a new item, removes x from
            // the List & Dictionary. Now thread A will try to move x to the end of the list.
            if (node.List != null)
            {
                lock (this.linkedList)
                {
                    if (node.List != null)
                    {
                        linkedList.Remove(node);
                    }
                }
            }

            if (node.Value.Value is IDisposable d)
            {
                d.Dispose();
            }

            return true;
        }

        return false;
    }

    // Thead A reads x from the dictionary. Thread B adds a new item. Thread A moves x to the end. Thread B now removes the new first Node (removal is atomic on both data structures).
    private void LockAndMoveToEnd(LinkedListNode<LruItem> node)
    {
        // If the node has already been removed from the list, ignore.
        // E.g. thread A reads x from the dictionary. Thread B adds a new item, removes x from
        // the List & Dictionary. Now thread A will try to move x to the end of the list.
        if (node.List == null)
        {
            return;
        }

        lock (this.linkedList)
        {
            if (node.List == null)
            {
                return;
            }

            linkedList.Remove(node);
            linkedList.AddLast(node);
        }
    }

    private class LruItem
    {
        public LruItem(K k, V v)
        {
            Key = k;
            Value = v;
        }

        public K Key { get; }

        public V Value { get; }
    }
}


# This constant is more or less an overestimate for the range in which
# n primes exist.  Generally 100 primes exist well within 100 * CONST numbers.
CONST = 20

def primeEval(limit):

Python convention says that functions should named lowercase_with_underscores

    ''' This function yields primes using the
    Sieve of Eratosthenes.

    '''
    if limit:

What is this for? You could be trying to avoid erroring out when limit=0, but it seems to me that you still error at for limit=1.

        opRange = [True] * limit

As with functions, lowercase_with_underscore

        opRange[0] = opRange[1] = False

        for (ind, primeCheck) in enumerate(opRange):

You don't need the parens around ind, primeCheck

            if primeCheck:
                yield ind
                for i in range(ind*ind, limit, ind):
                    opRange[i] = False

def listToNthPrime(termin):
    ''' Returns a list of primes up to the nth
    prime.
    '''
    primeList = []
    for i in primeEval(termin * CONST):
        primeList.append(i)
        if len(primeList) >= termin:
            break
    return primeList

You are actually probably losing out by attempting to stop the generator once you pass the number you wanted. You could write this as:

 return list(primeEval(termin * CONST))[:termin]

Chances are that you gain more by having the loop be in the loop function than you gain by stopping early.

def nthPrime(termin):
    ''' Returns the value of the nth prime.

    '''
    primeList = []
    for i in primeEval(termin * CONST):
        primeList.append(i)
        if len(primeList) >= termin:
            break
    return primeList[-1]

def listToN(termin):
    ''' Returns a list of primes up to the
    number termin.
    '''
    return list(primeEval(termin))

def lastToN(termin):
    ''' Returns the prime which is both less than n
    and nearest to n.

    '''
    return list(primeEval(termin))[-1]

All of your functions will recalculate all the primes. For any sort of practical use you'll want to avoid that and keep the primes you've calculated.


Counting inversions in C++ via mergesort and vectors

What kind of efficiency?

You ask for efficiency, but don't clarify whether you want programmer or processor efficiency. And, at least sometimes, the two can both be improved simultaneously by leveraging the right pre-existing tools, so it's worth considering programmer efficiency.

Programmer efficiency comes in at least three general categories:

Writing less code:

I would be strongly tempted to confirm whether this can be written to leverage std::sort with a custom type that implements a counter in its overload to std::swap. If you can transform the problem like this, you don't have to worry about coding a merge sort correctly, and should have less code.
Writing clearer code:

The arguments to mergeAndCount are named vec, p, q, and r, and have no comments that clarify the meaning of p, q, and r (inversion's arguments p and r suffer similarly). Furthermore mergeAndCount's local variables are named L and R. What do these mean? The parameters appear to be local indices for special spots in the vector; perhaps they could be named accordingly.

As an extension of "naming things is important", consider also renaming inversion to use a verb instead of a noun. Something like invert is typically better than inversion; something that indicates what it's doing could be better still. Perhaps sortAndCount?

Sometimes avoiding raw loops can help. For example, the loops that fill L and R could be written with std::copy. But better yet, you could construct them in place with the range constructor:

vector<int> L(&vec[p], &vec[q + 1]);
vector<int> R(&vec[q + 1], &vec[r + 1]);

Two side comments here: your use of a final index rather than one past final (closed range instead of open range) conflicts with the standard library. If main called inversion with .size() instead of .size() - 1, and everything else was updated to match, a number of + 1 and/or - 1 items should disappear, starting with the three + 1 instances in my little code excerpt.

Second, I'm uncertain what I think of the use of a sentinel as opposed to verifying the index location. Doesn't it have a side effect that would harm lists with that number? While the current problem definition excludes use of the sentinel, problems have a tendency of changing over time; attempts to reuse code may result in using code that isn't suited for the new problem.
Making it harder to screw up:

The indices you pass into inversion and mergeAndCount represent very important values that never change. You should consider marking them const in order to avoid losing the ends of your ranges.

On the flip side, processor efficiency comes from many things that often compete with programmer efficiency. Here are a couple that could be relevant.

Avoiding allocations:

Often allocating in a loop is a source of run-time inefficiency. Note, for example, that std::merge requires input and output ranges, rather than allocating its own helper ranges internally. This allows std::sort to allocate them once and reuse them as necessary. (This comment conflicts with the above suggestion to use the range constructor.)
Memory access patterns:

Scanning through memory linearly is often the fastest way to access it. Your code does a pretty good job of this already, so without profiling there's little I can offer here.


Counting adjacent swaps to sort an array with 3 different values

The code in the post runs in linear time, so we can't hope to improve the asymptotic complexity, but we might be able to make some piecewise optimizations. Let's start by making a random test case:

>>> import random
>>> CASE = ''.join(random.choice('012') for _ in range(10**6))

Timing the performance on this test case establishes a baseline for any improvements.

>>> from timeit import timeit
>>> timeit(lambda:excursion(CASE), number=1)
1.1623761800583452

The expression int(str[i])) appears twice, so let's remember it in a local variable:

def excursion2(str):
    digits = [0, 0, 0]
    result = 0
    for i in range(len(str)):
        digit = int(str[i])
        for j in range(digit + 1, 3):
            result += digits[j]
        digits[digit] += 1
    return result

This saves about 25% of the runtime:

>>> timeit(lambda:excursion2(CASE), number=1)
0.867930110078305

The code only uses the index i to look up the corresponding character of str. So instead of iterating over the indexes, iterate over the characters themselves:

def excursion3(str):
    digits = [0, 0, 0]
    result = 0
    for c in str:
        digit = int(c)
        for j in range(digit + 1, 3):
            result += digits[j]
        digits[digit] += 1
    return result

This saves about 3%:

>>> timeit(lambda:excursion3(CASE), number=1)
0.8365003759972751

We can save an assignment statement by using map to apply the function int to the characters of str:

def excursion4(str):
    digits = [0, 0, 0]
    result = 0
    for digit in map(int, str):
        for j in range(digit + 1, 3):
            result += digits[j]
        digits[digit] += 1
    return result

This saves about 4%:

>>> timeit(lambda:excursion4(CASE), number=1)
0.7819818791467696

We could cache the range objects, to avoid rebuilding them on each loop:

def excursion5(str):
    n = 3
    digits = [0] * n
    ranges = [range(i + 1, n) for i in range(n)]
    result = 0
    for digit in map(int, str):
        for j in ranges[digit]:
            result += digits[j]
        digits[digit] += 1
    return result

This saves about 25%:

>>> timeit(lambda:excursion5(CASE), number=1)
0.497486931970343

The cumulative impact of these changes reduced the overall runtime by about 60%. Is that good enough to pass the time limit?


List splitting for RLE compression algorithm

First of all I must tell you that Python makes astonishing easy to write a Run-length encoding:

>>> src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5]
>>> from itertools import groupby
>>>
>>> [(k, sum(1 for _ in g)) for k,g in groupby(src)]
[(1, 2), (2, 1), (3, 2), (4, 1), (2, 1), (1, 1), (3, 2), (4, 1), (3, 5), (4, 1), (5, 1)]

Take a look at how itertools.groupby() to see how a generator will be a good choice for this kind of task

But that doesn't mean that it wasn't a bad idea try to implement it yourself. So let's take a deeper look at your code :)

The best use of global is usually the one that doesn't use global at all

The use of the global keyword among beginners is almost always a sign of trying to program using some other language's mindset. Usually, if a function need to know the value of somthing, pass that something along as an argument.

In your case, what you need, is a function that loops through your list holding the value of isRepeat.

Something like this:

def parse(seq):
    is_repeat = False
    old = None
    for num in seq:
        is_repeat = num == old    # will be True or False
        if is_repeat:
            # ...

I didn't go too far since, as you may have already noticed, the is_repeat flag is a bit useless now, so we'll get rid of that later.

You may have also noted that I called isReapeat is_repeat, I did that to follow some naming style guide (see PEP8 for more info).

Cleared this, let's get at your statement:

  In the first step, I need to split my source list to sequences of repeating and non-repeating elements.

Ok, to split a sequence we'll have to parse it item by item, so while we'll be at it why don't already count how many times an item occurs?

The wrong step was to build a testRepeat function, such function should act on 2 items at the time, but that will lose the "view" of the whole sequence one item after the other. Well ok, a recursive solution could also be found, but I can't go through all the possible solutions.

So, to do achive our goal one could:

parse the list item by item.
see if an item is the same as the previous one.
if it is count += 1.
else store that item with its count.

This might be the code:

def rle(seq):
    result = []
    old = seq[0]
    count = 1
    for num in seq[1:]:
        if num == old:
            count += 1
        else:
            result.append((old, count))   # appending a tuple
            count = 1      # resetting the counting
            old = num
    result.append((old, count))    # appending the last counting
    return result

There could still be room for improvement (also it doesn't handle empty list like hdima noticed), but I just wanted to show an easy example and premature optimization is the root of (most) evil. (Also, there's groupby waiting to be used.)

Notes

It's very common to fall in some of the mistakes you did. Keep trying and you'll get better. Keep also in mind some of the following:

Think hard about the your design.
Do you really need an out function? Couldn't you just place the code there?
Do you really want to not print at all, if you get an empty list? I would really like to see what my code is returning, so I wouldn't block its output.
Don't write cryptic code, write readable one.
What are a, b and pr. A variable name should be something that reflect what it holds.
The same could be said for sequence, if sequece is the resulting sequence call it result or something like that.
Whorship The Zen of Python as an almighty guide!


I don't see why you use a HashMap (or any Map) at all.

What I'd do is:

Get all the homes
Filter all the homes to only get those which are unvisited
Get the home that is closest

The home that you get will either be visible, or it won't be visible. If it is not visible, there won't be any other visible homes either.

Combining this with @Vogel's suggestion of using Set the code would go something like this:

Set<Home> visitedHomes = me.getVisitedHomes();
Set<Home> allHomes = getHomes();
Optional<Home> result = allHomes.stream().parallel()
    .filter(home -> !visitedHomes.contains(home))
    .min(Comparator.comparingInt(home -> range(me, home)))
    .map(result -> range(me, result) <= VISIBLE_ZONE ? result : null);

And then you can choose between either returning the optional:

return result;

or returning null if there is no match:

return result.orElse(null);


Add spaces to improve readability:

head = NULL;
while (tmp)
if (this != &F)

Member functions that do not change any of the class members should be declared with the const specifier:

bool is_empty() const;
bool is_leaf() const;

Some of your while loops could be rewritten as for loops.  For example, the loop in the Node copy constructor could be rewritten as

for (adj* tmp = F.head; tmp != NULL; tmp = tmp->next)
    push(tmp->data);

Should a pop with an empty list be tolerated?  Currently you silently ignore the problem by returning a -1.  Would throwing an exception (to report the error) be better?  Or at least a std::assert(false); before the return, so you can detect the problem in a debug build.  Also, you don't need the else there, since the body of the if will return.

You have no error checking.  In particular, add_edge will happily try to add an edge to a node that doesn't exist, resulting in Undefined Behavior and (if you're lucky) a crash.  (The same applies to Graph::operator[].  You could add an assert check, or an at method that would check the bounds, similar to how std::vector operates.)

Your Graph copy constructor does not copy nodes[0].

Why are you using raw memory for Graph's nodes?  You should use std::vector or some form of smart pointer.