Basic web app that returns a JSON of information

The first problem is the function todi. I'm assuming a better name for it would be to_dict. If that is the case it does not make sense, that it sometimes returns the string "{}", sometimes "()" and sometimes an actual dictionary. I think this would be equivalent/better:

def to_dict(st):
    st = st.strip("/?")
    if not st:
        return dict()
    return dict(urllib.parse.parse_qsl(st))

This strips of any "/" or "?" from the beginning or end of the string and returns an empty dictionary if the string is empty.

Your function adminhandle should take the parameters it needs as parameters, not retrieve them on its own from data. It can also be slightly simplified by using the fact that lists are mutable, so you can just write result[0] = True instead of del result[0]; result.append(True):

def adminhandle(adminaccess, command):
    result = [False, ""]
    if adminaccess is not None:
        rawupass = (admin_salt+adminaccess).encode('ascii')
        hashupass = hashlib.sha512(rawupass).hexdigest()

        if hashupass == realpass:
            #access granted!
            result[0] = True
            if command == 'listdir':
                result[1] = str(os.listdir(os.getcwd()))
    return result

x is also a really bad name. At least name it data or something telling the reader what it actually is.

    data = to_dict(request.uri.decode('ascii')[1:])

Your placeholder variable valid is also not necessary. As is writing out.update({'success': valid}). out['success'] = valid is sufficient. I would also use the fact that dictionaries have a dict.get method, that returns None if the key does not exist.

    out = {'success': False}
    adminaccess, command = data.get('adminaccess'), data.get('command')
    out['ADMIN'], out['CMDRES'] = adminhandle(adminaccess, command)
    if not out['CMDRES']:
        del out['CMDRES']
    if data.get('key') == 'chess':
        out['my_name'] = 'Bob'
        out['success'] = True
    return json.dumps(out).encode('UTF-8')


Is this a good way to create a Javascript object?

If you want to access the createQuestion function you could simply do the following

this.createQuestion = function(index){
    // your code
};

You can create public and private variables in a object. The easiest example I can give for this is using the following code.

function someObject(publicInput, privateInput) {

    this.public = publicInput;

    var private = privateInput;

    this.getPrivate = function(){
        return private;
    }
}

var newObject = new someObject(true, false);

console.log(newObject.public); // returns true
console.log(newObject.private); // returns undefined
console.log(newObject.getPrivate()); // returns false

As you can see the private variable can only be accessed from inside the object, which is why I've added a getPrivate() function to return this variable.


Longest increasing subsequence algorithm

The parameter x doesn't have to be a Vec, it could be a slice instead (&[i32]). However, if you had used a non-Copy item type (i32 is Copy), then in order to return individual items from the input Vec, you'd either have to clone the items or move them out of the Vec (using remove).
You've implemented binary search by hand, but the Rust standard library provides a very flexible implementation via slice::binary_search_by.

I present you my own implementation of the algorithm, based on a slightly different C++ implementation, which is why there are so many differences compared to your version. I wrote this about one year ago, but sadly, I no longer use it. Note a few things though that are not necessarily relevant to the code review:

This is a very generic function: the selector parameter is used to extract a particular field from each item in the slice. I was using this function on a slice of objects and I was interested in finding increasing values of a particular field of these objects.
The function returns indices into the slice, not the values themselves. I needed to know the indices of the items in the longest increasing subsequence because I had to do something else with the items that were not in the subsequence (without destroying the original sequence), and using indices was the easiest way to do that. If I wanted to return the values without consuming the original sequence, I could have returned a Vec of references to the items instead (Vec<&T>).
Single letter variable names don't really help to understand the algorithm. Since I was using this algorithm for practical purposes, I took the time to understand and document it. If this is just an exercise to learn idiomatic Rust, I suppose this kind of detail doesn't matter much.
I like your use of a for loop on a reversed range iterator at the end. I should have done that myself!

/// Finds one of the [longest increasing subsequences][1]
/// from the subsequence created by applying `selector` on each item in `items`.
/// The result is a vector of indices within `items`
/// corresponding to one of the longest increasing subsequences.
///
/// [1]: https://en.wikipedia.org/wiki/Longest_increasing_subsequence
pub fn lis<T, I: Ord, F: Fn(&T) -> I>(items: &[T], selector: F) -> Vec<usize> {
    // This algorithm is adapted from
    // http://www.algorithmist.com/index.php?title=Longest_Increasing_Subsequence.cpp&oldid=13595

    let mut result = Vec::new();

    // If `items` is empty, then the result is also empty.
    if items.is_empty() {
        return result;
    }

    // This vector stores, for each item,
    // the index of the largest item prior to itself that is smaller than itself.
    // We'll use this vector at the end to build the final result.
    let mut previous_chain = vec![0; items.len()];

    // Initially, we assume that the first item is part of the result.
    // We will replace this index later if that's not the case.
    result.push(0);

    for i in 1..items.len() {
        // If the next item is greater than the last item of the current longest subsequence,
        // push its index at the end of the result and continue.
        if selector(&items[*result.last().unwrap()]) < selector(&items[i]) {
            previous_chain[i] = *result.last().unwrap();
            result.push(i);
            continue;
        }

        // Perform a binary search to find the index of an item in `result` to overwrite.
        // We want to overwrite an index that refers to the smallest item that is larger than `items[i]`.
        // If there is no such item, then we do nothing.
        let comparator = |&result_index| {
            use std::cmp::Ordering;

            // We don't return Ordering::Equal when we find an equal value,
            // because we want to find the index of the first equal value.
            if selector(&items[result_index]) < selector(&items[i]) {
                Ordering::Less
            } else {
                Ordering::Greater
            }
        };

        let next_element_index = match result.binary_search_by(comparator) {
            Ok(index) | Err(index) => index,
        };

        if selector(&items[i]) < selector(&items[result[next_element_index]]) {
            if next_element_index > 0 {
                previous_chain[i] = result[next_element_index - 1];
            }

            result[next_element_index] = i;
        }
    }

    // The last item in `result` is correct,
    // but we might have started overwriting earlier items
    // with what could have been a longer subsequence.
    // Walk back `previous_chain` to restore the proper subsequence.
    let mut u = result.len();
    let mut v = *result.last().unwrap();
    while u != 0 {
        u -= 1;
        result[u] = v;
        v = previous_chain[v];
    }

    result
}


Unit test code for a private median-of-three function, using reflection

As I've said in my comments, I'm not a huge fan of testing private methods.  It couples the tests very closely to the implementation of your class which makes even simple refactorings much harder than they need to be.  That said, lets have a look at your test.

Naming

medianEasyTest tells me nothing really about what the test is expecting.  median is the name of the method you're calling.  EasyTest tells me nothing about what you're passing, or what you're expecting back.  This doesn't make the intention of the test easy to read.

Exceptions

You're catching exceptions in your test and more than that, whilst you're logging them, you're swallowing the exceptions.  I really don't like that.  If your code throws an exception, you should let the exception escape the test and fail it.  Having the test fail on assertEquals(7, sample[0]); when it's actually failed because it threw an IllegalAccessException is just confusing.

Setup

If you're going to be running multiple tests against the same private methods, then it makes sense to do a lot of the prep work either in a method called explicitly, or in a Before method on the test class (notice that I'm not catching any exceptions.  If they happen, because your class structure changes you want it to fail:

@Before
public void setupPrivateCalls() {
   Class[] args = new Class[3];
   args[0] = int[].class;
   args[1] = Integer.TYPE;
   args[2] = Integer.TYPE;

   medianMethod = LibraryCounter.class.getDeclaredMethod("median", args);
   medianMethod.setAccessible(true);
}

Method medianMethod;

Double checking

You're checking that sample hasn't been updated at the end of your test.  Do you really need to do that?

Putting it together

Putting all of that together, you end up with an actual test method that looks more like this:

public void testMedianIs8From789() {
     System.out.println("median");
     int[] sample = {7,8,9};

     int result  = (int)medianMethod.invoke(null, sample, 0, sample.length-1);
     assertEquals(8, result);
 }

Exceptions from privates

This is probably subjective, but I don't like the way your private method is throwing an exception:

private static int median(int[] sample, int start, int end) {
    if(sample.length < 3) {
        throw new IllegalArgumentException("arrays of length three or greater");
    }

If your private throws that exception, it's because something under your classes control (one of it's public methods) has failed to supply the right data.  Validation should be performed at the public interface to the class, you shouldn't need to perform it again in your privates.


Firstly, I would consider switching off error suppression, and add in Exception handling. You could in this example add in a condition to check if each file exists before including it, for instance:

if ($sp_link[4] == 'profile' && @$sp_link[5] == '' && file_exists('profile.php')) {
    include_once 'profile.php';
}

It looks like you're using the query only to return a page title, and only in one instance. Is this correct? If so, amend you query to only return the data that you want, rather than returning the whole dataset from any particular table, for instance, if you only want the title tuple, change it to this:

$sql ='SELECT `title` FROM `posts` WHERE `post_id`=? AND `post_name`=?';
$stmt=$pdo->prepare($sql);
$stmt->execute([$sp_link[5], $sp_link[6]]);
$post=$stmt->fetch(PDO::FETCH_ASSOC);

To improve this further, you could turn this block of PHP into a function or method. Here's how one might achieve this aim:

function simpleSelect($fields = '*', $table = 'posts', $postId = '', $postName = '', $stmt = null){
    if(is_array($fields)){
        $fields = implode(',', $fields);
    }
    $sql = "SELECT `{$fileds}` FROM `{$table}` WHERE `post_id`=? AND `post_name`=?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$postId, $postName]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

Now the top of your code starting from $sql ='SELECT * from posts WHERE post_id=? AND post_name=?'; and ending with $post=$stmt->fetch(); becomes this:

$post = simpleSelect('title', 'posts', $sp_link[5], $sp_link[6], $stmt);

If you need to select multiple fields from the posts table, then you could do this (imagining that you want title and name fields returned):

$post = simpleSelect(['title', 'name'], 'posts', $sp_link[5], $sp_link[6], $stmt);

Finally, consider moving to an object-orientated approach. Exception handling and OO programming will be covered elsewhere.


Multiple joins for fields that need the same data. SQL Server 2008 R2

Classic de-normalized data. I've seen this often in healthcare. You can create a function to do this for you. It's unlikely to be faster but will save your some typing. You'd have to test each to see which is quicker. But the bottom line is there isn't a "great" improvement method.

create function dbo.get_icd_code (@icd varchar(16))
returns varchar(256)
as
begin
    declare @return varchar(256)
    select @return = DESCRIPTION
    from ICD_DESCRIPTIONS
    where ICD_CODE = @icd
    return @return
end

Then call it...

SELECT
    ICD_CODE1,
    dbo.get_icd_code(ICD_CODE1)
    ICD_CODE2,
    dbo.get_icd_code(ICD_CODE2)
    ICD_CODE3,
    dbo.get_icd_code(ICD_CODE3)
FROM ICD_CODES

Another way to speed it up is to stage your data first since there are so many ICD10 codes, but you'll need to provide the entire query for me to determine if this will work--primarily what other tables you are joining to and limiting from.

Lastly, you could try to un-pivot your data, join to the description field once, and then either keep it in this vertical fashion or pivot it back up. Again, hard to benchmark this against the multiple joins without being in your environment.


Length of the longest consecutive run of 1s in its binary representation

Code alignment.
I still think this style of indentation is poor. It is particularly ill suited to large code bases where you have literally hundreds of thousands of lines of code to maintain.
Its about reading the code and our inherently lazy brain. You scroll through the code looking for a problem scanning the lines and then you have code way to the right. Its not good.
I would write it as
function findMaxNumberOfConsecOnes(dec) {
    const countConsec = (ac, x) => [
        ac[0] < ac[1] ? ac[1] : ac[0], // or Math.max(...ac)
        x === "1" ? ac[1] + 1 : 0
    ];

    return [...(dec >>> 0).toString(2)]
        .reduce(countConsec, [0, 0])[0]; // Returning number rather than array
}

Note that I added  () around the comma separated group and then the second ternary. Not because it is needed, but when you are checking code the IDE will highlight matching braces (I have mine set to bright bold red) saving time and effort when looking for typos in compound expressions..
Bug?
The functional solutions return differently (an array) from the imperative solution (a number). My guess is you forgot to extract the max from the array.
Number V String
Numbers always win.
I assume by the >>> 0 you are expecting negative values and that the MSB (most significant bit) the sign bit, is counted.
Strings are always the slowest way to deal with numbers. You do get an automatic reduction in the number of bits to count as toString(2) drops the leading zeros so it has one handy benefit.
Comparing your solutions
In terms of performance the imperative solution is the quickest at around 20% faster than the other two (tested on a random set of signed int32). This is almost a given as functional sacrifices performance in hope of less bugs.
Using numbers only
By avoiding the use of strings you avoid the memory allocation overhead and the slow string compare tests.
The following example is up to an order of magnitude faster than your imperative solution and can also avoid stepping over the leading bits of negative values.

size = Math.log2(Math.abs(num)) + 1 | 0 get the number of bits to count
const leading = num < 0 ? 32 - size : 0 If negative gets the number of leading bits
return Math.max(count + leading, max) add any leading bits to the count and check for max

The rest is straight forward.
function countBitSeq(num) {
    var max = 0, count = 0, size;
    size = Math.log2(Math.abs(num)) + 1 | 0;
    const leading = num < 0 ? 32 - size : 0;
    while (size --) {
        max = Math.max((num & 1 ? ++count : count = 0), max);
        num >>= 1;
    }
    return Math.max(count + leading, max);
}


Checking against a specific sequence in python

Specification

I'm having trouble understanding the problem. I think you roll two dice at once, and the results must be distinct and adjacent to each other and to the previous roll.

Comments

Your question includes some explanation before the program:

  I'm modeling a simple dice game that a friend and I invented.

  On any one turn of the game, you must roll a specific combination to stay in the game.

  The particular rule I'm trying to model is this:

  Given a previous roll (where the dice are contiguous) make another contiguous roll either above the previous roll or before it. 6 and 1 are considered contiguous. Outside of being contiguous the order of the dice does not matter...

This should be part of the program! It could be a docstring at the beginning of the file.

  arguments:

  prev = previous/ existing roll

  curr = current roll to check

  sides = number of sides of the dice

These should also be part of the program! They should be part of chkStk's docstring, or better yet, included in the argument names. prev and curr could be called previous_roll and current_roll.

srt returns its argument in order, unless it contains both bounds, in which case it's reversed. This is surprising, so it requires an explanation in a comment or docstring.

Names

All three function names are inscrutably short.

srt sorts its argument (which should be a two-element list) in a cyclic order. So it could be called cyclic_order.

srt's argument a is a 2-die roll (i.e. a pair), so it should be called pair or roll.

cmp checks whether its argument is a contiguous ascending sequence (in the same cyclic order). So it could be called contiguous or is_contiguous or is_ascending or even in_order.

cmp's argument a is a list of (1-die) rolls, so it should be called rolls.

chkStk checks whether curr is a valid roll after prev, so it should be called something like valid_roll or is_valid_roll or `

(It's confusing to have roll mean a pair of 1-die rolls, so maybe the whole program should switch to something consistent, such as "roll" for one die and "pair" for two dice.)

Small simplifications

True if boolean_expression else False can be simplified to just boolean_expression.

[debatable] (min(a), max(a)) == (1, sides) is short, but most people are accustomed to reading min(a) == 1 and max(a) == sides.

Even better: since 1 and sides are the minimum and maximum values possible, you can skip the min and max and just check whether the values are present: 1 in a and sides in a.

list(x for x in foo) can be simplified to just list(foo).

Simpler ways

In cmp, instead of building a sequence in cyclic order and comparing to it, it might be simpler to check that each successive pair is in cyclic order.

There are easier ways to solve this problem.

If my restatement of the problem above ("the results must be adjacent to each other and to the previous roll") is correct, it can be easily turned into a program. You can simply check each part (possibly in a helper function):

whether two dice of a pair are adjacent to each other
whether two pairs are adjacent to each other

You can do both of these without any list operations.

Tests

Instead of printing out results for you to check, your test cases can check them for you! The simplest way to do this is with assert:

assert chkStk([5, 6], [1, 2], 6)
assert not chkStk([5, 6], [1, 4], 6)
assert not chkStk([6, 1], [2, 1], 6), 'overlapping pairs should fail'

This won't print anything unless the test fails. You can include an optional error message.


Is any further optimization possible? (Codeforces)

Firstly you need to put all the global statements into a function because of Python code runs faster in a function compared to global scope.

You don't need the arr variable. You can just use

x[i], y[i] = map(int, raw_input().split())

instead of using the two lines. map uses the function(1st argument) on each of the outputs from the second argument.

After placing the global statements into a function then instead of passing i, j, k you would need to pass the values directly.

I'll look up the algorithm and see if there are other changes that can be made.


Static to Instance method trampolining with templates

I will maintain my list of improvements in this answer.

There is a more succinct way to expose the mechanism to the consumer:

class Final : Base<Final>
{
    register_method<&Final::Foo>( "foo" ); //, static_cast<PHandler>( &Handler<&Final::Foo> ) );
    register_method<&Final::Bar>( "bar" ); //, static_cast<PHandler>( &Handler<&Final::Bar> ) );
    :

class Base
{
    :
    template<PFunc func>
    static void register_method( string name ) {
        methods()[name] = &Handler<func>;
    }
    :

This has extra advantage in that it avoids the following nasty issue:

  Note: (Eelis on IRC) gcc is known not to be able to resolve addresses
  of function template specializations passed to functions. You can work
  around it either by declaring separate variables for the function
  pointers, or using a dirty cast (or a nice cast like
  boost::implicit_cast)

It doubles the number of templated functions getting generated: now 2 are generated for each method instead of one. But at a small price, it is much cleaner to the consumer!

Also function pointer typedef-s could be rewritten:

//typedef void (T::*PFunc)(void);
//typedef void (*PHandler)(void*);

using PFunc = void (T::*)(void);
using PHandler = void(*)(void);

http://ideone.com/ZFQb1f


This was posted just a short while ago on StackOverflow.com

Firstly, if this is legacy code that has existed in production for a long time, then even if you can make it semantically better, you have to really weigh up the gains against the losses. Changing code is a cost, can introduce bugs even when the new code appears to be a lot better, and has to be justified. That the existing code uses a lot of arrays does not mean it has any bugs, nor would the "improvements" give you better performance in any way.

However, on the basis of giving this code a review I will do so.

Basically, start off by getting rid of all the arrays and calls to new[] and delete[] and use std::string (which is used there in one place so it is obviously known to the programmer).

Ensure your IniPersistInf class is const-correct so takes if it takes a string that it only reads, it uses const char * or const std::string & rather than char *.

buffer in IniValue appears to be for writing into, so for this one you might use std::vector<char>. In such a case, to get the pointer out of it, use &buffer[0] when you pass it to the IniPersistIf methods.


Naming

Your Card class is currently composed of 3 fields, which represent its suit, its rank and its color:

String cardSuit, cardRank, cardColor;

Note that in the sentence above, the term used where "suit", "rank" and "color" and not "cardSuit", "cardRank" and "cardColor". What this means is that you should have

String suit, rank, color;

There is no need to repeat the class name in the fields composing it. The name given to each field should best represent what it stores. If we take the example of cardSuit then this field really represent the suit (of this card).

Consider also the case of accessing such field, you would have someCard.cardSuit with your current naming: this introduces a repetition and a long name; it is clearer to have someCard.suit.

Controlling access to the fields

When desiging a class, you should also decide on which access to give to each members. For example, a public variable will be accessible by everybody but a private variable will only be visible inside your own class.

When you are declaring the fields as

String cardSuit, cardRank, cardColor;

they actually use the default access, which means every class in the same package as of the Card class will be able to access them. This is most likely not what you want here: these are internal fields and it would be preferable to keep them private. It ensures that only modifications made inside the Card class are allowed, which goes line in line with the OOP principle: encapsulating your state without leaving the chance of others to mess it up.

So, instead, you should have:

private String cardSuit, cardRank, cardColor;

Then there is the matter of the constructor. Currently, the constructor doesn't have an access modifier also, which means it can be accessed by classes in the same package (just like above). This also means that the only classes that will be able to construct Card instances are only classes present in the same package.

Such a restriction is probably not what you want: you want everyone to be able to constructor a Card instance. So, in this case, make the constructor public:

public Card() {
    // ...
}

Constants

Instance fields are specific to each instance of a class. So when you declare

// Setting two arrays with the suits and ranks options
String[] suits = {"hearts", "spades", "diamonds", "clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King"};

you actually declare a suits and ranks array with the same content for each card instance. However, all the possible values for the suits and the ranks are not specific to any card instance. In fact, it applies for every card and it will always be the same.

In this case, it is preferable to use a constant variable; that is to say a variable defined at a single place, that every instance will share, and that cannot be modified. The typical pattern is to declare them private static final, with a name in uppercase:

private static final String[] SUITS = {"hearts", "spades", "diamonds", "clubs"};
private static final String[] RANKS = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

Scope of variables

To get a random suit and a random rank, you currently generate two integers as instance members of the Card class:

int randomSuits = generator.nextInt(SUITS.length);
int randomRanks = generator.nextInt(RANKS.length);

Card() {
    cardSuit = SUITS[randomSuits];
    cardRank = RANKS[randomRanks];
    // ...
}

But note this is the only place where you are using those variables.

This is generally not a good idea: it means that you just created two variables that can be used and referenced anywhere in your class, but you only need them in a specific, particular piece of code. The scope of a variable should be as minimal as possible: only declare variable where they are needed.

In this case, they are only needed inside the constructor, so declare them here:

Card() {
    int randomSuits = generator.nextInt(SUITS.length);
    int randomRanks = generator.nextInt(RANKS.length);
    cardSuit = SUITS[randomSuits];
    cardRank = RANKS[randomRanks];
    // ...
}

and, when you do that, you realize that maybe you don't even need to store them at all: they are used only once, so this would be even more easier to read:

Card() {
    cardSuit = SUITS[generator.nextInt(SUITS.length)];
    cardRank = RANKS[generator.nextInt(RANKS.length)];
    // ...
}

Accessors

Accessors, or getter / setter, is the typical way to expose your private fields to the outside world. They are typically named get followed by the name of the field.

In your class, you have

public void getSuit() {
    System.out.println(cardSuit);
}

public void getRank() {
    System.out.println(cardRank);
}

public void getColor() {
    System.out.println(cardColor);
}

but those are not getter. They do not return the value of the field. They print it instead.

Make them real getters with:

public String getSuit() {
    return cardSuit;
}

public String getRank() {
    return cardRank;
}

public String getColor() {
    return cardColor;
}

There implication is not that the Card class now has a way to let the outside world know the value of the suit, the rank and the color of a card. So it is up to the calling code to print the result with:

Card card1 = new Card();
System.out.println(card1.getSuit());
System.out.println(card1.getRank());
System.out.println(card1.getColor());

Random integers

Instances of Random should be reused. Currently, each card instance will create its own Random field with

Random generator = new Random();

It is preferable to have a single Random object that is shared. In this case, we can make it constant:

private static final Random GENERATOR = new Random();

This way, the same Random will be used for all cards.

Putting it all together

By putting all this into code, one could have:

public class Card {

    private static final Random GENERATOR = new Random();

    // Setting two arrays with the suits and ranks options
    private static final String[] SUITS = { "hearts", "spades", "diamonds", "clubs" };
    private static final String[] RANKS = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };

    // Setting variables
    private String suit, rank, color;

    public Card() {
        suit = SUITS[GENERATOR.nextInt(SUITS.length)];
        rank = RANKS[GENERATOR.nextInt(RANKS.length)];
        // Setting the color of the card in dependence of the suit
        if (suit.equals("hearts") || suit.equals("diamonds")) {
            color = "red";
        } else {
            color = "black";
        }
    }

    public String getSuit() {
        return suit;
    }

    public String getRank() {
        return rank;
    }

    public String getColor() {
        return color;
    }
}


Serve folder content using PHP route (SSI) (dynamic includes)

Thanks for your example.  It kind of validates my concern on how you are thinking about routing.

I like that you are thinking about the routing problem and trying to move away from legacy ways of having each URL going directly to a physical file for processing.  I would however challenge you to take this a step further, as what you have now really only gets partially away from the legacy web application, a script-for-every controller/action line of thinking, in that you still have scripts that you are redirecting to rather then using your router to instantiate an appropriate controller object in order to satisfy the request.

Most modern frameworks that utilize a front-controller routing pattern like you are trying to achieve have gone the route of auto-loading a controller (ideally auto-loaded in a PSR-4 compliant way) to handle the request passed to it by the router, not having the router just include some specific script file.

So you might see a pattern like:

$controller = Router::getController($request);
$controller->execute();

That's it.  The router is basically used on a single line in your main execution path.

Here all the information about the HTTP request (including URI) could be injected into a controller object, which then takes over application control.  In this case, the router needs to know absolutely nothing about what dependencies that controller has. It typically just needs to know how to map the
 request (oftentimes just the first segment of the URI) to a controller to be instantiated and hand off the request information and application control over to the controller.

In your case, your router actually does the following:

It parses the request (something better handled in its own class such that a request object can be passed around as a dependency to consuming code).
It uses information from the request to map the request to an action to be performed (the only thing a router should truly do).
It has to understand where dependencies for a particular action are located in the filesystem.
It actually loads/executes those dependencies.

If you are striving to adhere to the single responsibility principle, you will quickly understand that the router has too much responsibility in your application. It should own just routing the request to an appropriate controller and then get out of the way.


Copy a stream to a file using Universal .NET

I will first focus on your nested using statements, as that can be very problematic. As you can read on the help page of CA2202 (CA2202: Do not dispose objects multiple times) the suggested way to resolve this is the following:

  To resolve this issue, use a try/finally block instead of the outer using statement. In the finally block, make sure that the stream resource is not null.

So let's map this to your code. You nest four different using statements, which is extremely problematic. Not only can this result in failures, it makes the code unnecessarily hard to read and comprehend. Refactor it to make use of the try-finally pattern. At most use one using statement
Additionaly I am unsure about your use of Dispatcher.RunAsync. Is there a specific reason for it? You are inside of an async method, meaning you don't have to wrap every method call awkwardly like that. Instead just call the commented-out line of code (and you should remove commented-out code in general).
The use of the var keyword seems strange to me. Why do you use it in this statement:

using(var streamToRead = inputStream.AsStreamForRead())

but not in this:

using(Stream streamToWrite = File.OpenWrite(fileToWrite))

I would generally discourage use of the var keyword if you don't explicitly state the type you define in a declaration. That means this line is okay:

var buffer = new byte[chunkSize];

But you should refactor the rest of your code to explicitly define the types of the variables.
Is there a specific reason to define some variables towards the top of the method and others at the place of use? Also why are they not defined at the very beginning of your method? You should decide on one approach. I prefer defining them right before they are used. This would e.g. mean moving int count = 0 down:

int count = 0;
int size;
while((size = await streamToRead.ReadAsync(buffer, 0, chunkSize, cts).ConfigureAwait(false)) > 0)


Read text file filled with numbers and tranfer to an array

Bug

If the array length is not a multiplier of the number of threads, you'll miss the remainder! Quick example:

public static void printRange(int length, int n) {
    int range = length / n;
    for (int index = 0; index < n; index ++){
        int start = index * range;
        int end = start + range;
        System.out.printf("[%s, %s)%n", start, end);
    }
}

// Output for printRange(10, 3):
[0, 3)
[3, 6)
[6, 9)

// Output for printRange(10, 6):
[0, 1)
[1, 2)
[2, 3)
[3, 4)
[4, 5)
[5, 6)

As you can see, you'll miss the 10th element for printRange(10, 3), and up to half the array for printRange(10, 6).

edit: A simplistic approach is to spin a new Thread to handle the remaining elements, but as you can see from the second example, you will end up a relatively high number of five elements for it, whereas the first five threads are only processing (and returning) one element. An alternative approach is to add an extra element per Thread so that you have more threads doing slightly more work, than one single thread doing most of the work.

Multi-threading

The preferred way of doing multi-threading since Java 5 is to use an ExecutorService to help you manage the lifecycle of threads. You should read up more on Oracle's tutorial to understand how they are used.

In addition, since you want each thread to compute and return a result for you, you should be looking at the Callable interface. Implementations override the call() method to return an appropriate result.

try-with-resources

If you are on Java 7 and above, you should use try-with-resources for efficient handling of the underlying I/O resource:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        // ...
    }
}

Hard-coding array length

int[] array = new int[100000];

What happens if your file has more than this number of elements? Actually, you also seem to be processing your file twice, once using the BufferedReader approach, and the second using a Scanner. Is this expected?

edit:

Getting the max value

Your current implementation forgets to actually compare the max of each partition with each other to arrive at the desired result.

  Is this meant to be more like an academic exercise on multi-threading? - myself

The reason why I'm asking is that while it looks like you're looking more at a map-reduce approach to your problem, it may not even be necessary in the first place. Processing 100,000 integers (based on your int[] declaration) or less in a single thread is relatively fast enough on any modern hardware capable of running the JVM. If you are however trying to compare billions of numbers and/or given a (strangely low) memory constraint, then that's when multi-threading will help. However, your question will be quite different at that stage.

Getting the max value (part 2)

From Java 8 onwards, there are two approaches of running tasks asynchronously:

ExecutorService to create Futures, and then getting the results from each of them.
Chaining CompletableFutures (Java 8 onwards).

The code below demonstrates both:

public class AsyncMax {

    private static final int MAX = 10;

    public static void main(String[] args) {
        System.out.println("Using ExecutorService:");
        ExecutorService service = Executors.newWorkStealingPool();
        List<Future<Integer>> esResults = IntStream.range(0, MAX).parallel()
                .mapToObj(i -> service.submit(() -> produce(i).get()))
                .collect(Collectors.toList());
        esResults.stream()
                .map(f -> get(f))
                .max(Comparator.naturalOrder())
                .ifPresent(System.out::println);
        service.shutdown();
        System.out.println("Using CompletableFuture:");
        CompletableFuture<List<Integer>> cfResults = IntStream.range(0, MAX).parallel()
                .mapToObj(i -> produce(i))
                .map(CompletableFuture::supplyAsync)
                .collect(allOf());
        cfResults.thenApply(results -> results.stream().max(Comparator.naturalOrder()))
                .join()
                .ifPresent(System.out::println);
    }
}

For both approaches, IntStream.range(0, MAX).parallel() is used to parallelize the production of MAX integers, via the produce(int) method (shown below). The intermediary esResults and cfResults variables are created solely to highlight where the asynchronous tasks will 'end', to be followed by how the results are collected. One can certainly daisy-chain the method calls completely.

ExecutorService:

Start an ExecutorService implementation, the Java 8 newWorkStealingPool() is an example here.
submit() a Callable<Integer> that returns an Integer upon completion.
Collect the results to a List<Future<Integer>>, i.e. a List of Futures that return Integers.
Stream the List by get()-ting (method shown below) each resulting Integer.
From the Stream<Integer>, call max(Comparator.naturalOrder()) to get the maximum value, and then print it via ifPresent(Consumer).
Last, shutdown() the ExecutorService.

CompletableFuture:

Pass each Supplier<Integer> from produce(int) to CompletableFuture.supplyAsync(Supplier).
Collect each CompletableFuture<Integer> into a resulting CompletableFuture<List<Integer>> via a custom allOf() Collector (method shown below).
From that CompletableFuture, thenApply() it to a Function<List<Integer>, Integer> that derives the maximum value from the List<Integer>.
join() to get the result and print it via ifPresent(Consumer).

Supporting methods:

This produces the given int after sleep()-ing for some time:

private static Supplier<Integer> produce(int i) {
    return () -> {
        try {
            Thread.sleep((int) ((1 + Math.random()) * (MAX - i) * 500));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
        System.out.printf("Returning [%s] from Thread[%s]%n",
                i, Thread.currentThread().getName());
        return i;
    };
}

This is a Stream-friendly way of get()-ing from a Future, by catching checked Exceptions first:

private static <T> T get(Future<T> future) {
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}

This is a Collector implementation for waiting on all CompletableFutures to finish, before returning the List of results (inspired by this article):

private static <T> Collector<CompletableFuture<T>, ?,
        CompletableFuture<List<T>>> allOf() {
    return Collector.of(ArrayList<CompletableFuture<T>>::new,
            (a, t) -> a.add(t), (a, b) -> { a.addAll(b); return a; },
            a -> CompletableFuture.allOf(
                        a.toArray(new CompletableFuture[a.size()]))
                    .thenApply(v -> a.stream().map(CompletableFuture::join)
                            .collect(Collectors.toList())));
}

Conclusion:

Instead of thinking solely on having to synchronize write access on a resulting array, both the ExecutorService or CompletableFuture approaches are more declarative, and IMO the latter more so that the former. This is achieved by letting us express how to generate our asynchronous tasks, followed by what needs to be done after gathering the results. :)


A function to split an string of alphabets and numbers into arrays and sort them respectively

You can use RegEx to extract the sequence of alphabets or numbers.
To match alphabets/number, use character class in Regular expression as below

/[A-Z]+|[0-9]+/

to match all occurrences, use g(global) flag.

After extracting sequences, use Array#reduce with Array#sort & Array#join to get the sorted string.

const str1 = 'AYUKB17053UI903TBC';
const str2 = 'ABKUY01357IU039BCT';

console.log(str1
  .match(/[A-Z]+|[0-9]+/g)
  .reduce((a, c) => a + [...c].sort().join(''), '')
    === str2
);


Design
Lets start by saying this is a C solution to the problem. You need to think more about classes encapsulation and protecting the tree from random coders to make sure your enviranrts remain protected.
Something like:
class BSTTree
{
    struct node { /* As you had */ };

    node*   root;
    public:
        // Constructors/Destructors and assignment here.

        void insert(int value);
        void delete(int value);
        void inorder(std::function<void(int)> action) const;
        int minimum() const;
};

Notice how we hide root to make sure only the methods you write can manipulate the tree. Nobody else can come along and tinker with it. This means if your code is correct then the enviranrts can not be changed.
Also you have not dealt with any of the issues around memory management. So you need to think about this. Who owns each node how are you going to delete them safely. Also  look up the rule of three before you write your class (implement that are the rule of zero).
Also you should probably avoid NULL it modern C++ it has been replaced by nullptr. The advantage of nullptr is that it has a well defined type that is not convertible to an integer type.
Code Review
Sure this works:
node* minValue(node* tnode){
    if(tnode->left!=NULL){
        return minValue(tnode->left);
    }
    else{
        return tnode;
    }
}

Should you return a node? The function says min value. SO why not return the minimum value. Also you don't want to expose the implementation details and returning a node exposes these.
But is recursion the best way to handle this? Since you are simply traversing along a chain a simple loop seems much more effecient:
int minValue()
{
    if (root == nullptr) {
        throw std::runtime_exception("Blaaa");
    }
    node* last = root;
    for(;last->left; last = last->left) {
        /* Do nothing in the body */
    }
    return last->value;
}

The inorder() traversal works.
//Inorder traversal
void inorder(node *tnode){
    if(tnode->left!=NULL){
        inorder(tnode->left);
    }
    cout<<tnode->value;
    if(tnode->right!=NULL){
        inorder(tnode->right);
    }
}

But testing the left and right values before calling makes the code more difficult to read. More traditionally you test to see if the node is null before you start and simply return. Also you simply print the value. Why not pass a function that is called for each value that makes the traversal much ore interesting.
void inorder(std::function<void(int)> action) {
    doInorder(action, root);
}
void doInorder(std::function<void(int)> action, Node* node) {
    if (node == nullptr) {
        return;
    }
    doInorder(action, node->left);
    action(node->vallue);
    doInorder(action, node->right);
}

Then you can call the in-order with a function that prints each value.
tree.inorder([](int v){std::cout << v << " ";});

The insert function is basically correct.
//insert function
node* insert(int val,node *tnode){
    node *temp=tnode;
    if(temp==NULL){
        temp= new node;
        temp->value=val;
        temp->left=NULL;
        temp->right=NULL;
    }
    else if(val<temp->value){
        temp->left=insert(val,temp->left);
    }
    else if(val>temp->value){
        temp->right=insert(val,temp->right);
    }
    return temp;
}

The only difference I would do is make the new a single line.
temp= new node{val, nullptr, nullptr};

The delete node looks great.


Updating HTML table (Userlist) with Node.js

Your code looks quite clear, and I see only some possible improvements.
Regarding your questions:

I don't think it'd better to split into fetchRoomList and updateRoomList separate functions: there are a few common vars that should be computed twice; additionally it'd prevent increasing performance like I suggest below (by traversing HTML tree less times).
using pure JS instead of jQuery would obviously increase performance a bit, but IMO it doesn't worth the negative impact on readability.

Then I can suggest what follows:

caching jQuery traversal:

currently you're looking:

for .room-X once for each room
for .lobby-container .room-list tbody once for each room to add a
 (when creating row)
for .lobby-container .room-list tbody .XXX, where XXX is .room-players (once), then .room-btn .btn (twice).

So to create C rows and update U rows you spend 2xC + 4xU "big" traversals for each room.
Instead you can:

first get var $rooms = $('.lobby-container .room-list tbody'); once for all
then look for $room = $(#${id}, $rooms); once for each room
and use $rooms.prepend() when creating row or $('XXX', $room) when updating room (these are only "little" traversals, since inside of $rooms).

this way you spend only 1 "big" traversal, plus 0xC + 3xU "little" traversals.
Note that room-X is unique so to be more strictly significant you might change the class into id.

less important: you also can cache r.id (used several times)
factorizing operations when creating room:

depending on r.players.length >= r.slots you execute different but analogue operations on the room, using twice the same jQuery traversal
instead you can get the condition var isFull = r.players.length >= r.slots;, then use it in each operation, all operations being attached to the same unique traversal
this way you actually spend only 1 "big" traversal, plus 0xC + 2xU "little" traversal

Last point, I suggest using tagged strings for row creation, which at the same time reduces code and improves readability. You'll notice I also choosed to omit the closing tags
 and 	 (optional in HTML5).

Here is the whole refactored function:

socket.on( 'updateRoomsList', function (room_list) {
  var $rooms = $('.lobby-container .room-list tbody');
  for (var i = room_list.length - 1; i >= 0; i -= 1) {
    var r = room_list[i],
        id = `room-${r.id}`,
        $room = $(`#${id}`, $rooms);
    if (!$rooms.length) {
      // Create row
      $rooms.prepend(`

  ${r.id}
  ${r.name}
  ${r.players.length}/${r.slots}
  <tdclass="room-button">

      JOIN

        `);
    } else {
      // Update row
      $('.room-players', $room).text(`${r.players.length}/${r.slots}`);
      var isFull = r.players.length >= r.slots;
      $('.room-button .btn', $room)
        .text(isFull ? 'FULL' : 'JOIN')
        .toggleClass('btn-warning disabled', isFull)
        .toggleClass('btn-success', !isFull);
    }
  }
}


Arrays as Arguments

When you write this:

void MultiplyTwoMatrixes(float aMatrix[9], float bMatrix[9], float product[9])

That is exactly equivalent to:

void MultiplyTwoMatrixes(float*, float*, float*);

That is, there's no size checking on any of the inputs whatsoever - I could call your function with three arrays of size 3, 1, and 72. Would compile fine. Which is a problem!

Encapsulation and Operators

We want type safety. That suggests a Matrix class. For simplicity, let's just make it 2d:

template <typename T, int Rows, int Cols>
struct Matrix;

And then we can write a multiply operator:

template <typename T, int R1, int C1, int C2>
Matrix<T, R1, C2> operator*(const Matrix<T, R1, C1>& lhs, const Matrix<T, C1, C2>& rhs);

Notice that this already handles dimensional analysis for you. You just have to write the internals, which isn't complicated. And then you would be able to write your rotation function naturally:

Matrix<float, 3, 3> xyzResult = xRot * yRot * zRot;

Type-safe and more readable!

newMatrix

I don't understand the construction of newMatrix. So I can't really offer a better solution? You're not setting lots of indices of newMatrix, for one thing...


Trying for an efficient and readable heap-sort implementation

Sort your includes. That way, you can keep track even if there are more of them.

Writing a test-program is a good idea. Though print the seed-value, and allow overriding from the command-line for reproducibility.
In line with that, add a method to test whether a range is ordered, print that result and use it for the exit-code too.

I would expect a function named print_vector() to, you know, print a vector. Not an iterator-range from a vector. Also, encoding the type of an argument in the function-name hurts usability, especially in generic code.

fill_vector() is a curious interface. I would expect get_random_data() which returns the vector.

Know your operators. ++i, i <= num_of_elems is equivalent to ++i <= num_elements.
Anyway, that should be a for-loop, or you could omit i and just count the argument down to zero.

Kudos for using constexpr to avoid preprocessor-cnstants where not needed. Still, ALL_CAPS_AND_UNDERSCORES identifiers are generally reserved for preprocessor-macros. They warn/assure everyone that preprocessor-rules apply. Fix the naming too.

The C++ headers <cxxx> modelled on the C headers <xxx.h> only guarantee to put their symbols into ::std. Don't assume they are also in the global namespace.

max_heap() will often try to create pointers far beyond the passed range. Creating such a pointer invokes undefined behavior.
For simple and correct code, better use indices.


There are several things you can do to improve this code.

First of all the code above isn't a valid C++ code. To run it you need to add:

#include <string>
#include <iostream>
#include <Windows.h>

int main()
{
    ... // your code posted above
}

Please next time you ask a question post the full code.

Then your Menu:

std::cout << "-CONSTRUCTION MENU-" << std::endl << std::endl;

std::cout << "1. Barrack" << std::endl << std::endl;

std::cout << "Build: ";

Consider writing it like this:

std::cout << "-CONSTRUCTION MENU-\n\n"
<< "1. Barrack\n\n"
<< "Build: ";

\n should be used instead of std::endl. The reason is std::endl
not only gives you a new line, it also does an expensive buffer
flushing operation which is rarely necessary.
No need to call std::cout several times after each other. Statements
can be chained.

Then your Percentage display:

std::string sentence[10] = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" };

for (int index = 0; sentence[index] != sentence[9]; index++)
{
    ...// statements inside
}

Several things are wrong here:

You are using a plain C array to hold the sentence variables. This is
very bad because a C array does not know about its size. Instead you
use the magic number '9' to finish iterating over the strings.
Please study the default C++ containers std::array or
std::vector. In this case I would go for array since you don't want
to add more values at run time.
The size is wrong. You declared space for 10 elements but only put
in 9.
sentence is a very bad name. You don't store sentences. Consider
using percentages instead.

Now we can write this instead:

std::array<std::string, 9> percentages = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" };

for (const auto& sentence : sentences)
{
    ...// statements inside
}

So the world is OK now? Not at all. You shouldn't use an array for numbers in the first place. Consider building the numbers in a loop instead:

for (int i = 1; i <= 9; ++i) {
    std::cout << std::to_string(i) << '%' << "\b\b";
    Sleep(150);
}

I removed the std::flush here since I don't see its purpose.

As a side hint it is a good practice to use ++i instead of i++. If you use objects later instead of ints you save an expensive copy.

Now we come to another dark chapter of your snippet. Your program is mixed with non-portable statements:

Sleep(150);

Consider using std facilities here:

#include <chrono>
#include <thread>

...

std::this_thread::sleep_for(std::chrono::milliseconds(150));

The big advantage here is that this is portable now.

The next candidate is:

system("pause");

Since you just want the program to wait with a message at the end you can do this:

std::cout << "Press any key...";
std::cin.get();

The last statement we get to is this:

system("cls");

No easy answer here. The fact is that the standard does not provide a portable solution here. You could wrap the statement in a function and make it portable for different platforms like this:

void clear_screen()
{
#if defined _WIN32
    std::system("cls");
#elif defined __unix__
    std::system("clear");
#elif defined (__APPLE__)
    std::system("clear");
#endif
}

We should also replace the

#include <windows.h>

with

#include <cstdlib>

So now also on Linux / MAC the clear should work.

As a last word. A function should only do one thing. You should separate the program in well defined parts. Here is my reworked solution with all the improvements already mentioned, dividing the program into parts:

#include <array>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>

void clear_screen()
{
#if defined _WIN32
    std::system("cls");
#elif defined (__unix__)
    std::system("clear");
#elif defined (__APPLE__)
    std::system("clear");
#endif
}

std::string get_user_choice()
{
    std::string choice;
    std::cout << "-CONSTRUCTION MENU-\n\n"
        << "1. Barrack\n\n"
        << "Build: ";
    std::cin >> choice;
    return choice;
}

void print_progress(int start, int end)
{
    for (auto i = start; i <= end; ++i) {
        std::cout << std::to_string(i) << '%' << "\b\b";
        std::this_thread::sleep_for(std::chrono::milliseconds(150));
    }
}

void print_building_completed()
{
    clear_screen();
    std::cout << "Building done\n";
    std::cout << "Press any key...";
    std::cin.get();
}

int main()
{
    auto building = get_user_choice();
    if (building == "1" || building == "Barrack" || building == "barrack"){
        print_progress(0, 100);
        print_building_completed();
    }
}


I don't understand the purpose of substr($3, 1) — isn't that the same as $3?

AWK alone can do the work of grep, tail, and negation.  I would write it this way:

synclient TouchpadOff=$(synclient | awk '/TouchpadOff/ { off=int($3) }
                                         END           { print !off }')


For faster searching and since you're searching by different properties, one way would be a different dictionary for each property you want to search for. The indexing property is the key and the value can be the tablerowinfo object or if indexes may be duplicated a list of tablerowinfoinfo objects.

Dictionary<NodeEntry, TableRowInfo> nodeEntryIndex;
Dictionary<int, TableRowInfo> rowNumberIndex;
Dictionary<object, TableRowInfo> rowDataIndex;

Assuming you've implemented Add and Remove methods, simply add/remove the appropriate entries to the dictionaries, in those methods.

The Find method would look something like this:

internal TableRowInfo Find(NodeEntry nodeEntry)
{
    if (nodeEntryIndex.ContainsKey(nodeEntry))
    {
        return nodeEntryIndex[nodeEntry];
    }
    return null;
}

One suggestion.  When you inherit from a List like this, you expose all the members you've inherited from the list, outside the class.  If you're going to provide your own version for all of them that's fine.  However if you're only going to implement a subset of them then you might want to consider not inheriting but having a List as a private property to store the collection.  This gives you much more flexibility in choosing what gets exposed outside the class.

Another suggestion.  Instead of using object as the rowData type, the DataRow Class would probably be better suited for that.  This increase the robustness of your class.


One-time pad encryption using letter shifting

Your function avoid is quite unnecessary and also confusing. I would expect avoid('@') to return True. When you store the letters as a global constant and as set, you should gain some speed (both because it does not have to be reconstructed again and again and because membership testing is very fast for a set. I replaced your function with letter not in letters_avoid.

Whenever you are doing string addition in Python, you are probably doing something wrong. This is because strings are immutable so for every addition a new string has to be created and the content of the strings to be added needs to be copied. This is quite slow. Rather, use a list to accumulate the letters of new_word and str.join them at the end.

When returning a tuple, the () are implicit. You can just write return a, b.

When iterating over words, you should just directly iterate over it, instead of its indices.

Using str.lower cuts down the double comparison if user == 'Done' or user == 'done' to if user.lower() == 'done':.

You should call your code with a if __name__ == '__main__': guard to allow importing your functions from another script without executing the whole script.

Final code:

import random

letters_avoid = set(' ,!?¿,*+-%/@1234567890')

def rotate_letter(letter, number):
    if letter == ' ':
        return letter
    if letter.islower():
        start = ord('a')
    elif not letter.islower():
        start = ord('A')

    normal_shift = ord(letter) - start
    new_letter = start + (normal_shift + number) % 26
    return chr(new_letter)

def rotate_word(word):
    new_word = []
    random_series = []
    for letter in word:
        if letter not in letters_avoid:
            random_number = random.randint(1, 26)
            new_word.append(rotate_letter(letter, random_number))
            random_series.append(random_number)
        else:
            new_word.append(letter)
    return "".join(new_word), random_series

def shift(words):
    encrypted_words = []
    random_shifts = []
    for word in words:
        new_word, random_series = rotate_word(word)
        encrypted_words.append(new_word)
        random_shifts.append(random_series)
    return encrypted_words, random_shifts

def get_input():
    words = []
    while True:
        user = input('Input words to encrypt. Done when ready \n')
        if user.lower() == 'done':
            return words
        words.append(user)

def start():
    words = get_input()
    encrypted_words, random_shifts = shift(words)
    print('UNENCRYPTED WORDS', words)
    print('ENCRYPTED WORDS', encrypted_words)
    print('RANDOM SHIFTS', random_shifts)

if __name__ == "__main__":
    start()


Normalizing data in Excel table column with multiple values

Ok, so this ended up being a little bit longer/more complicated than I hoped. I will do my best to explain so that you can follow along. Please ask questions if you get lost or confused!
Code first, then explanations:
Option Explicit

Private Type TRecord
    To As String
    From As String
    Subject As String
    ReceivedDate As Date
    InFolder As String
    Size As String
    Weekday As String
    RecordDate As Date
    Month As String
    Year As String
    Time As String
    InOut As String
End Type

Sub New_Fix_Table()
    ' Be sure to add 'Option Explicit' at the top of your modules. This prevents undeclared variables from slipping through.

    ' Never use underscores in names. They have special meaning to the interpreter.
    ' table_size = Range("Table1").Rows.Count

    ' ## Not Needed due to UBound/LBound ##
    ' Dim tableSize As Long
    ' Be sure to also properly qualify you range references.
    ' TableSize = ActiveWorkbook.Range("Table1").Rows.Count - Without proper qualification, your Range is really ActiveWorkbook.Range
    ' tableSize = ThisWorkbook.Range("Table1").Rows.Count
    ' ## ##

    'Goes through Table1 in "To" column and fixes the recipients

    Dim i As Long

    ' For loops such as these, I prefer for loops
    ' Do While i <= table_size

    ' I strongly prefer arrays for this purpose. If it was my own project, I even would use classes, but one step at a time for now.

    ' Change this to point to the correct worksheet.
    Dim inputSheet As Worksheet
    Set inputSheet = ThisWorkbook.Worksheets("TargetSheet")

    ' If your data is in a table, then you can use this method instead of referring to the range.
    Dim tableData As Variant
    tableData = inputSheet.ListObjects(1).Range.value

    ' Now, here is a trick I use when processing table data in a much more efficient manner.
    ' This does require a reference to Microsoft Scripting Runtime
    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = GetHeaderIndices(tableData)

    ' Now we have a dictionary where we can use a key and return the index position of that key

    ' This is where it gets a little bit tricky. If we encounter a row with multiple emails, we need to duplicate the records.
    ' Otherwise, we want to keep the records as is. For this task, collections to the rescue!

    ' Having declared a Record Type, I can now use the Type as a container for my data (without needing a class)
    Dim record As TRecord

    ' The records collection will contain the created records
    Dim records As Collection
    Set records = New Collection

    Dim i As Long
    ' We loop through arrays using LBound and Ubound (lower bound, upper bound). The '1' denotes rows, whereas '2' would denote columns.
    ' I add 1 to the lower bound so I can skip the header row.
    For i = LBound(tableData, 1) + 1 To UBound(tableData, 1)
        ' Set all the properties of the record.
        record.From = tableData(i, headerIndices("From"))
        record.Subject = tableData(i, headerIndices("Subject"))
        record.ReceivedDate = tableData(i, headerIndices("Received_Date"))
        record.InFolder = tableData(i, headerIndices("In_Folder"))
        record.Size = tableData(i, headerIndices("Size"))
        record.Weekday = tableData(i, headerIndices("Weekday"))
        record.RecordDate = tableData(i, headerIndices("Date"))
        record.Month = tableData(i, headerIndices("Month"))
        record.Year = tableData(i, headerIndices("Year"))
        record.Time = tableData(i, headerIndices("Time"))
        record.InOut = tableData(i, headerIndices("In/out"))

        ' Split the addresses. If there are multiple addresses we dont need to rewrite the record, we just need to adjust the To field.
        Dim splitAddresses As Variant
        If InStr(tableData(i, headerIndices("To")), ";") > 0 Then
            splitAddresses = Split(tableData(i, headerIndices("To")), ";")

            Dim j As Long
            For j = LBound(splitAddresses) To UBound(splitAddresses)
                If Len(splitAddresses(i)) > 1 Then
                    record.To = splitAddresses(i)
                    records.Add record
                End If
            Next
        Else
            record.To = tableData(i, headerIndices("To"))
            records.Add record
        End If
    Next

    ' Now we have a colleciton of all of the records we need. Now, we need to translate those back into an array.
    Dim outputData As Variant

    ' The row is 0 based so we can add headers, but the headerIndices dictionary is already 1-based, so we leave the columns 1 based.
    ' Admittedly, I would avoid a mis-match of bases for re-dimming an array, I am only doing it this way to prevent confusion.
    ReDim outputData(0 To records.Count, 1 To headerIndices.Count)

    ' An array with the same base-dimensions would be one of the two following:
    ' ReDim outputData(0 To records.Count, 0 To headerIndices.Count - 1)
    ' ReDim outputData(1 To records.Count + 1, 1 To headerIndices.Count)
    ' You would then need to adjust the actual filling of the array as well.

    i = LBound(outputData, 2)

    Dim header As Variant
    ' Loop through all of the stored headers
    For Each header In headerIndices.Keys
        ' The LBound here dynamically points to the header row.
        outputData(LBound(outputData, 1), i) = header
    Next

    ' This way we can dynamically fill in the array.
    Set headerIndices = GetHeaderIndices(outputData)

    i = LBound(outputData, 2) + 1
    For Each record In records
        outputData(i, headerIndices("To")) = record.To
        outputData(i, headerIndices("From")) = record.From
        outputData(i, headerIndices("Subject")) = record.Subject
        outputData(i, headerIndices("Received_Date")) = record.ReceivedDate
        outputData(i, headerIndices("In_Folder")) = record.InFolder
        outputData(i, headerIndices("Size")) = record.Size
        outputData(i, headerIndices("Weekday")) = record.Weekday
        outputData(i, headerIndices("Date")) = record.RecordDate
        outputData(i, headerIndices("Month")) = record.Month
        outputData(i, headerIndices("Year")) = record.Year
        outputData(i, headerIndices("Time")) = record.Time
        outputData(i, headerIndices("In/out")) = record.InOut
    Next

    ' Now we just have to put the output data somewhere. Let's reuse the sheet we pulled from.
    OutputArray outputData, inputSheet, "Output_Data"
End Sub

Public Function GetHeaderIndices(ByVal InputData As Variant) As Scripting.Dictionary
    If IsEmpty(InputData) Then Exit Function

    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = New Scripting.Dictionary

    headerIndices.CompareMode = TextCompare

    Dim i As Long
    For i = LBound(InputData, 2) To UBound(InputData, 2)
        If Not headerIndices.Exists(Trim(InputData(LBound(InputData, 1), i))) Then _
           headerIndices.Add Trim(InputData(LBound(InputData, 1), i)), i
    Next

    Set GetHeaderIndices = headerIndices
End Function

Public Sub OutputArray(ByVal InputArray As Variant, ByVal InputWorksheet As Worksheet, ByVal TableName As String)
    Dim AddLengthH As Long
    Dim AddLengthW As Long

    If NumberOfArrayDimensions(InputArray) = 2 Then
        If LBound(InputArray, 1) = 0 Then AddLengthH = 1
        If LBound(InputArray, 2) = 0 Then AddLengthW = 1

        Dim r As Range
        If Not InputWorksheet Is Nothing Then
            With InputWorksheet
                .Cells.Clear
                Set r = .Range("A1").Resize(UBound(InputArray, 1) + AddLengthH, UBound(InputArray, 2) + AddLengthW)
                r.value = InputArray
                .ListObjects.Add(xlSrcRange, r, , xlYes).Name = TableName

                With .ListObjects(1).Sort
                    .header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With
            End With
        End If
    End If
End Sub

Initial Notes
The first thing that struck me about your code was that you literally have no variable declarations. Lines like :
cell_value = ...

Are pretty much the same as :
Dim cell_value as Variant
cell_value = ...

The only difference between the two is that the second is at least explicit about wanting a variant. The first is implicit.
First bit of advice avoid implicit commands as much as possible. The reason for this is quite simple, there is a tendency to think that the computer is magically doing something it shouldnt be, but really you told it to do exactly what it is doing and as a result, you have a bug that can be nearly invisible.
Consider for example :
myRange = Range("SomeRange")

This declares a myRange (which the reader expects to be a Range) and converts the range to an array. This in itself is confusing, but, even worse, I can still do :
Set myRange = Range("SomeRange")

And it is now a range reference (the only difference being the Set keyword). While it is easy to read the code and determine what is happening for us, you will inevitably lose a bug in there that you will have to search for.
Option Explicit to the Rescue!
Option Explicit is one of the best things in VBA. It is truly simple, but it makes the simplest of bugs super simple to prevent (and even simpler to find). With Option Explicit at the top of a module, the compiler will throw an error when a variable isnt declared.
' This won't compile. Note the minor (but potentially difficult to find) spelling error between Very and Vary.
Dim SomeVeryLongVariableName as Long
SomeVaryLongVariableName = 10

To make Option Explicit a breeze to use:

Open the Developer Window
Press CTRL+T and then CTRL+O.
Check the box for Require Variable Declaration.
While you're in there, I recommend going to the general tab and selecting Break in Class Module under error trapping.

Qualifying References
One of the most common mistakes someone new to VBA will make is doing:
SomeVariable = Range("SomeRange")

' or

SomeVariable = Range("SomeRange").Value

There are two problems with the first version. The problem that is solved by the second version is that we specify the property we are accessing. The default property of a Range is .Value so we don't need .Value, but it is discouraged to implicitly access .Value.
The second issue is that we rely implicitly on ActiveSheet.Range("SomeRange"). This is a silent killer. I refuse to work with the Active Anything unless I absolutely must and even then, I prefer not to. It is always best to specifically call the object you are working with.
' This is literally better than not using a worksheet reference at all
Dim Foo as Worksheet
Set Foo = ActiveSheet

...many lines later...

DoSomething Foo

Why is this little change better? It is using the active sheet! While not ideal, it at least ensures that Foo points to the same worksheet unless we explicitly change the worksheet it is pointing to. It is stronger than the ActiveSheet reference.
Even better would be:
Dim Foo as Worksheet
Set Foo = ThisWorkbook.WorkSheets("SomeFoo")

The ThisWorkbook object is the workbook that is running the code, and by using a string argument as a call to the collection we can return the specific worksheet back.
Working on the Worksheet
Now lets get into the meat of the problem. Your code is slow because you are operating on the worksheet. Its that simple. A hundred calls to the Worksheet.Range will be slower than a hundred calls to Data(x, y). An array is faster, and is easier to use.
Even worse is when you not only access the cells by a range reference, but when you do :
EntireRow.Delete

Now you've really upset the worksheet. It has to update calculations, it has to resize stuff, fix formatting (if in a table), check number formatting, etc. It is a costly operation. If you're deleting a lot of rows...avoid it at all cost.
Enter the world of arrays. Not only are they fast but they are easy. Worksheet.Cells(1, 1) becomes Data(1, 1). Once you load in the data to the array (Data) you can manipulate, access, delete the values all you want. The worksheet doesn't care. It doesnt see what is happening to the same data it was previously responsible for.
Putting It Together
I am not going to go through the code line by line, particularly because I already provided in-line comments to help make the code a bit easier to read. This will be a broad explanation of what the code does.

First, it loads in all the data from a ListObject (excel Table)
into an array. That's the easy part.
Once we have the data, we need to know the indices of the headers.
This makes manipulating the data much easier. It also allows you to
move columns around all you want without breaking the code (just
ensure the names are still there).
Using a custom Type we can store all of the data in a defined
structure. A Type is similar to a Struct in other languages. In
essence, it is a variable that has properties, but that isnt an
object. Thus, it cannot be New'ed up.
Loop through all of the rows, and create new records for cells with
multiple addresses. Since the Type cannot be New'ed, it will
retain old values. This means we dont need to re-create the entire
record for each new row. We just need to change the new values,
then add it to the collection.
Once the collection is loaded with records, we can translate them
into a new array that is appropriately sized. No need to add/remove
rows. It is just the right size at creation.
The OutputArray method will take an array and a worksheet and it
will clear the cells on that worksheet, put the array onto the
worksheet, and then turn that output into a table. Point it where
you want the output to go, and it will do the rest.

I didn't test the code on my end (I didnt want to bother creating a test table), but I imagine it should run in a matter of seconds.
Note : Microsoft Scripting Runtime
To use the code as is, you will need to add a reference to the Microsoft Scripting Runtime Library. There are plenty of resources for adding references, but ask if you get lost.
RubberDuck. Use It. Love It. Prof-It
I tend to be shameless about my plugs for Rubberduck, largely because the head of the tool, Mat's Mug, is unabashed in his attempts to convert everyone on SO to using RD. That said, it is an amazing tool, especially for beginners, and it would make most of the above comments stupidly easy to implement. Honestly, it would.
Check it out here: http://rubberduckvba.com/.
Wrapping Up
Let me know how the code above works for you, and do your best to use it as an example for future projects. If you manage to implement even half of those suggestions you'll save yourself potentially months of costly learning experiences through failed projects. Best of luck!
EDIT: Use this code instead to fix the error from above. The error is caused by adding a custom-type to a collection (I have never used Types outside of a class before so I didn't think of the error in advance). This approach is slightly more advanced, but it shouldnt be too complex.
In a Class Module named 'Record'
Option Explicit

Private Type TRecord
    ToField As String
    FromField As String
    Subject As String
    ReceivedDate As Date
    InFolder As String
    Size As String
    WeekDay As String
    RecordDate As Date
    Month As String
    Year As String
    Time As String
    InOut As String
End Type

Private this As TRecord

Public Property Get ToField() As String
    ToField = this.ToField
End Property
Public Property Get FromField() As String
    FromField = this.FromField
End Property
Public Property Get Subject() As String
    Subject = this.Subject
End Property
Public Property Get ReceivedDate() As Date
    ReceivedDate = this.ReceivedDate
End Property
Public Property Get InFolder() As String
    InFolder = this.InFolder
End Property
Public Property Get Size() As String
    Size = this.Size
End Property
Public Property Get WeekDay() As String
    WeekDay = this.WeekDay
End Property
Public Property Get RecordDate() As Date
    RecordDate = this.RecordDate
End Property
Public Property Get Month() As String
    Month = this.Month
End Property
Public Property Get Year() As String
    Year = this.Year
End Property
Public Property Get Time() As String
    Time = this.Time
End Property
Public Property Get InOut() As String
    InOut = this.InOut
End Property

Public Property Let ToField(value As String)
    this.ToField = value
End Property
Public Property Let FromField(value As String)
    this.FromField = value
End Property
Public Property Let Subject(value As String)
    this.Subject = value
End Property
Public Property Let ReceivedDate(value As Date)
    this.ReceivedDate = value
End Property
Public Property Let InFolder(value As String)
    this.InFolder = value
End Property
Public Property Let Size(value As String)
    this.Size = value
End Property
Public Property Let WeekDay(value As String)
    this.WeekDay = value
End Property
Public Property Let RecordDate(value As Date)
    this.RecordDate = value
End Property
Public Property Let Month(value As String)
    this.Month = value
End Property
Public Property Let Year(value As String)
    this.Year = value
End Property
Public Property Let Time(value As String)
    this.Time = value
End Property
Public Property Let InOut(value As String)
    this.InOut = value
End Property

This class uses a code pattern I learned from Mat's Mug. Declare the Type for the class as a Private Type, then declare a private this that refers to that type. As a result, you have an organized Type to hold your variables, and you get intellisense.
Once you do that, you just need to open up the property accessors. In this case, I made everything public. This isnt good practice, but I am avoiding teaching you too much at once (I would prefer not to use a class as is, but it is the best approach at this point).
This Code Goes in Your Module
Option Explicit

Sub New_Fix_Table()
    ' Be sure to add 'Option Explicit' at the top of your modules. This prevents undeclared variables from slipping through.

    ' Never use underscores in names. They have special meaning to the interpreter.
    ' table_size = Range("Table1").Rows.Count

    ' ## Not Needed due to UBound/LBound ##
    ' Dim tableSize As Long
    ' Be sure to also properly qualify you range references.
    ' TableSize = ActiveWorkbook.Range("Table1").Rows.Count - Without proper qualification, your Range is really ActiveWorkbook.Range
    ' tableSize = ThisWorkbook.Range("Table1").Rows.Count
    ' ## ##

    'Goes through Table1 in "To" column and fixes the recipients

    ' For loops such as these, I prefer for loops
    ' Do While i <= table_size

    ' I strongly prefer arrays for this purpose. If it was my own project, I even would use classes, but one step at a time for now.

    ' Change this to point to the correct worksheet.
    Dim inputSheet As Worksheet
    Set inputSheet = ThisWorkbook.Worksheets("TargetSheet")

    ' If your data is in a table, then you can use this method instead of referring to the range.
    Dim tableData As Variant
    tableData = inputSheet.ListObjects(1).Range.value

    ' Now, here is a trick I use when processing table data in a much more efficient manner.
    ' This does require a reference to Microsoft Scripting Runtime
    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = GetHeaderIndices(tableData)

    ' Now we have a dictionary where we can use a key and return the index position of that key

    ' This is where it gets a little bit tricky. If we encounter a row with multiple emails, we need to duplicate the records.
    ' Otherwise, we want to keep the records as is. For this task, collections to the rescue!

    ' Having declared a Record Type, I can now use the Type as a container for my data (without needing a class)
    Dim initialRecord As record

    ' The records collection will contain the created records
    Dim records As Collection
    Set records = New Collection

    Dim i As Long
    ' We loop through arrays using LBound and Ubound (lower bound, upper bound). The '1' denotes rows, whereas '2' would denote columns.
    ' I add 1 to the lower bound so I can skip the header row.
    For i = LBound(tableData, 1) + 1 To UBound(tableData, 1)
        Set initialRecord = New record
        ' Set all the properties of the record.
        initialRecord.FromField = tableData(i, headerIndices("From"))
        initialRecord.Subject = tableData(i, headerIndices("Subject"))
        initialRecord.ReceivedDate = tableData(i, headerIndices("Received_Date"))
        initialRecord.InFolder = tableData(i, headerIndices("In_Folder"))
        initialRecord.Size = tableData(i, headerIndices("Size"))
        initialRecord.WeekDay = tableData(i, headerIndices("Weekday"))
        initialRecord.RecordDate = tableData(i, headerIndices("Date"))
        initialRecord.Month = tableData(i, headerIndices("Month"))
        initialRecord.Year = tableData(i, headerIndices("Year"))
        initialRecord.Time = tableData(i, headerIndices("Time"))
        initialRecord.InOut = tableData(i, headerIndices("In/out"))

        ' Split the addresses. If there are multiple addresses we dont need to rewrite the record, we just need to adjust the To field.
        Dim splitAddresses As Variant
        If InStr(tableData(i, headerIndices("To")), ";") > 0 Then
            splitAddresses = Split(tableData(i, headerIndices("To")), ";")

            Dim j As Long
            For j = LBound(splitAddresses) To UBound(splitAddresses)
                If Len(splitAddresses(i)) > 1 Then
                    Dim splitRecord As record
                    Set splitRecord = New record
                    ' Because of how objects are passed around, you cant copy a class through assignment. You must duplicate the properties manually into a new class.
                    splitRecord.FromField = initialRecord.FromField
                    splitRecord.Subject = initialRecord.Subject
                    splitRecord.ReceivedDate = initialRecord.ReceivedDate
                    splitRecord.InFolder = initialRecord.InFolder
                    splitRecord.Size = initialRecord.Size
                    splitRecord.WeekDay = initialRecord.WeekDay
                    splitRecord.RecordDate = initialRecord.RecordDate
                    splitRecord.Month = initialRecord.Month
                    splitRecord.Year = initialRecord.Year
                    splitRecord.Time = initialRecord.Time
                    splitRecord.InOut = initialRecord.InOut

                    initialRecord.ToField = splitAddresses(i)
                    records.Add splitRecord
                End If
            Next
        Else
            initialRecord.ToField = tableData(i, headerIndices("To"))
            records.Add initialRecord
        End If
    Next

    ' Now we have a colleciton of all of the records we need. Now, we need to translate those back into an array.
    Dim outputData As Variant

    ' The row is 0 based so we can add headers, but the headerIndices dictionary is already 1-based, so we leave the columns 1 based.
    ' Admittedly, I would avoid a mis-match of bases for re-dimming an array, I am only doing it this way to prevent confusion.
    ReDim outputData(0 To records.Count, 1 To headerIndices.Count)

    ' An array with the same base-dimensions would be one of the two following:
    ' ReDim outputData(0 To records.Count, 0 To headerIndices.Count - 1)
    ' ReDim outputData(1 To records.Count + 1, 1 To headerIndices.Count)
    ' You would then need to adjust the actual filling of the array as well.

    i = LBound(outputData, 2)

    Dim header As Variant
    ' Loop through all of the stored headers
    For Each header In headerIndices.Keys
        ' The LBound here dynamically points to the header row.
        outputData(LBound(outputData, 1), i) = header
    Next

    ' This way we can dynamically fill in the array.
    Set headerIndices = GetHeaderIndices(outputData)

    i = LBound(outputData, 2) + 1

    Dim outputRecord As record
    For Each initialRecord In records
        outputData(i, headerIndices("To")) = outputRecord.ToField
        outputData(i, headerIndices("From")) = outputRecord.FromField
        outputData(i, headerIndices("Subject")) = outputRecord.Subject
        outputData(i, headerIndices("Received_Date")) = outputRecord.ReceivedDate
        outputData(i, headerIndices("In_Folder")) = outputRecord.InFolder
        outputData(i, headerIndices("Size")) = outputRecord.Size
        outputData(i, headerIndices("Weekday")) = outputRecord.WeekDay
        outputData(i, headerIndices("Date")) = outputRecord.RecordDate
        outputData(i, headerIndices("Month")) = outputRecord.Month
        outputData(i, headerIndices("Year")) = outputRecord.Year
        outputData(i, headerIndices("Time")) = outputRecord.Time
        outputData(i, headerIndices("In/out")) = outputRecord.InOut
    Next

    ' Now we just have to put the output data somewhere. Let's reuse the sheet we pulled from.
    OutputArray outputData, inputSheet, "Output_Data"
End Sub

Public Function GetHeaderIndices(ByVal InputData As Variant) As Scripting.Dictionary
    If IsEmpty(InputData) Then Exit Function

    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = New Scripting.Dictionary

    headerIndices.CompareMode = TextCompare

    Dim i As Long
    For i = LBound(InputData, 2) To UBound(InputData, 2)
        If Not headerIndices.Exists(Trim(InputData(LBound(InputData, 1), i))) Then _
           headerIndices.Add Trim(InputData(LBound(InputData, 1), i)), i
    Next

    Set GetHeaderIndices = headerIndices
End Function

Public Sub OutputArray(ByVal InputArray As Variant, ByVal InputWorksheet As Worksheet, ByVal TableName As String)
    Dim AddLengthH As Long
    Dim AddLengthW As Long

    If NumberOfArrayDimensions(InputArray) = 2 Then
        If LBound(InputArray, 1) = 0 Then AddLengthH = 1
        If LBound(InputArray, 2) = 0 Then AddLengthW = 1

        Dim r As Range
        If Not InputWorksheet Is Nothing Then
            With InputWorksheet
                .Cells.Clear
                Set r = .Range("A1").Resize(UBound(InputArray, 1) + AddLengthH, UBound(InputArray, 2) + AddLengthW)
                r.value = InputArray
                .ListObjects.Add(xlSrcRange, r, , xlYes).Name = TableName

                With .ListObjects(1).Sort
                    .header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With
            End With
        End If
    End If
End Sub

The only main difference is that now we are using an object instead of a type, and we must manually copy the object any time we want to create a new one (whereas, with the Type, we just changed the To field).


INSERT INTO #Person
(
    First_Name,
    Last_Name,
    Two_Char_Nationality,
    InsertedAt
)
SELECT
    tab.p.value('FirstName[1]', 'NVARCHAR(100)'),
    tab.p.value('Surname[1]', 'NVARCHAR(100)'),
    tab.p.value('(Nationality/IsoAlpha2)[1]', 'VARCHAR(2)'),
    GETDATE()
FROM
    @data.nodes('/Person') tab(p);

SELECT or Query nodes in hierarchial or nested XML


I'll start with a list of observations:

Hardly any comments.  There are several places where it would be nice if you added some comments to explain how the main logic works for someone who has not seen the code before.
A bunch of global variables and ones using very generic names - lots of opportunities for clashes.  I'd suggest either using a function closure to isolate your variables or make them properties of one global object or eliminate the need for them.
There is NO need for a selector like this: "#map #col2".  It should just be "#col2".
A bunch of places where you're evaluating the same selector more than once.  For example, in the animateTurn function, you evaluate $("#map .next-ball") multiple times when you could just chain.  This:

$("#map .next-ball").removeClass("player"+(3-currentPlayer));
$("#map .next-ball").addClass("player"+currentPlayer);

could be changed to this:

$("#map .next-ball").removeClass("player"+(3-currentPlayer))
    .addClass("player"+currentPlayer);

Or, in the whole function this:

function animateTurn(col, row) {
    animationInProgress = 1;
    $("#map #col"+col+" .next-ball").addClass("animation-in-progress");

    $("#map #col"+col+" .next-ball").animate({
        top: '+='+(52*(row+1)-1)
    }, {
        duration: Math.round((row+1)*500/h),
        complete: function() {
            $("#map #col"+col+" div:nth-child("+(row+2)+")").html("");
            $("#map #col"+col+" .next-ball").css("top", "0px");
            $("#map .animation-in-progress").removeClass("animation-in-progress");
            $("#map .next-ball").removeClass("player"+(3-currentPlayer));
            $("#map .next-ball").addClass("player"+currentPlayer);
            animationInProgress = 0;
        }
    });
}

could be changed to this to use chaining and avoid re-evaluating the same selector multiple times:

function animateTurn(col, row) {
    animationInProgress = 1;
    $("#map #col"+col+" .next-ball").addClass("animation-in-progress")
        .animate({top: '+='+(52*(row+1)-1)}, {
            duration: Math.round((row+1)*500/h),
            complete: function() {
                $("#col"+col+" div:nth-child("+(row+2)+")").html("");
                $("#col"+col+" .next-ball").css("top", "0px");
                $("#map .animation-in-progress").removeClass("animation-in-progress");
                $("#map .next-ball").removeClass("player"+(3-currentPlayer))
                    .addClass("player"+currentPlayer);
                animationInProgress = 0;
            }
        });
}

I generally find it cleaner to use eventListeners rather than onclick handlers because you don't have to worry about multiple listeners stomping on each other.
You have a bunch of constants in the code that aren't very self documenting.  There's a 500 and a 52 which I have no idea where they came from or when they would have to be changed if the game was modified.
Is there a reason that the HTML for the game is generated via javascript rather than specified separately?  Usually, it's advantageous for the presentation of the app to be separate from the code for the app and for the code to adapt to whatever the presentation is.  This allows separate people to work on the visual aspects of the app vs. the logic of the app and allows you to change one without affecting the other.


React app for movie search, making AJAX call with input value from another component

So the way you would accomplish this in my experience is to move your state up your component tree to a higher level where each component that requires access to that state can have it via props that you pass in.

So for example your SearchForm component could accept all the values and functions it requires via props. It needs a prop to handle the change of the search input as the user types, a prop to handle the submit as the user clicks the submit button and a prop to show the search input value in the input box.

So, for example:

<SearchForm
    searchInput={this.state.searchInput}
    handleChange={(event) => this.setState({ searchInput: event.target.value })}
    handleSubmit={() => this.searchForMovie(this.state.searchInput)}
/>

That means your SearchForm could become something more like:

const SearchForm = (props) => (
  <form onSubmit={props.handleSubmit}>
    <label>
      Name:
      <input
        className="movieName"
        type="text"
        value={props.searchInput}
        onChange={props.handleChange}
      />
    </label>
    <input type="submit" value="Submit" />
    <h1>{props.searchInput}</h1>
  </form>
);

All your state lives in your App component and now you can use that state to pass on as props to any other child components that may need it.

Some observations/suggestions:

As you can see above there is a searchForMovie() function, I would extract the logic from your componentDidMount hook to a function like this so you can call it whenever needed with the search input you desire
Also consider some error handling on your axios.get() function call as if anything goes wrong with the request you won't know about it because the promise will swallow that (can be confusing when debugging)
The above does not consider any performance optimisations and the amount of renders/rerenders on a large app may be problematic, but my guess is that would be premature for your app and important is first that you get it to work
For your App class I would advise against extending any other class aside from React.Component as that is all you require (if I understand your question correctly)
Also, if you are using this in your class methods you will need to remember to bind them in your constructor to avoid hitting the unknown function error, i.e. this.searchForMovie = this.searchForMovie.bind(this);


Questions & Responses: Let me tell you about you

Indenting is the first part of common practice that you should consider when sharing your code with anyone. Here is your code, which I have put though the 'standard' indenting function of Eclipse:

import java.util.Scanner;

public class LMComplex {
    Scanner name = new Scanner(System.in);
    Scanner age = new Scanner(System.in);
    Scanner gender = new Scanner(System.in);
    Scanner height = new Scanner(System.in);
    String usrname;
    String usrage;
    String usrgender;
    Double usrheight;

    public void main() {
        System.out.println("Enter your name: ");
        usrname = name.nextLine();
        System.out.println("Enter your age(Numbers): ");
        usrage = age.nextLine();
        System.out.println("Enter your gender(male/female): ");
        usrgender = gender.nextLine();
        System.out.println("Enter your height(feet.inches . 5 feet 5 inches = 5.5): ");
        usrheight = height.nextDouble();
        Double rusrheight = Math.ceil(usrheight);
        if (rusrheight > usrheight)
        {
            rusrheight = rusrheight - 1;
        }
        else
        {

        }
        Double rusrheightininches = usrheight - rusrheight;
        if (rusrheightininches >= 0.10 && rusrheightininches < 0.12)
        {
            rusrheightininches = rusrheightininches * 100;
        } else {
            rusrheightininches = rusrheightininches * 10;
        }
        Double rusrheightinincheschecker = rusrheightininches;
        rusrheightininches = Math.ceil(rusrheightininches);
        if (rusrheightininches > rusrheightinincheschecker)
        {
            rusrheightininches = rusrheightininches - 1;
        }
        else
        {

        }
        System.out.println("Hii " + usrname + ". I am Cartic, a basic textual virtual personal assistant. I do know that you are " + usrage
                + " years old. You are a " + usrgender + " and are " + rusrheight + " feet " + rusrheightininches + " inch(es) tall");
    }
}

Now, it is much easier to see the structure.

Java code-style guidelines put the { opening brace on the same line as the control statement, so, for example, the code:

        if (rusrheightininches >= 0.10 && rusrheightininches < 0.12)
        {
            rusrheightininches = rusrheightininches * 100;
        } else {
            rusrheightininches = rusrheightininches * 10;
        }

should be:

        if (rusrheightininches >= 0.10 && rusrheightininches < 0.12) {
            rusrheightininches = rusrheightininches * 100;
        } else {
            rusrheightininches = rusrheightininches * 10;
        }

Also, in the previous if statement you  have an empty else block.... you can just remove it:

        if (rusrheight > usrheight)
        {
            rusrheight = rusrheight - 1;
        }
        else
        {

        }

becomes:

        if (rusrheight > usrheight) {
            rusrheight = rusrheight - 1;
        }

As for your variables, they are nice descriptive names, but, in Java, it is common to use what is called 'camelCase', where the first letter is lower-case, and the subsequent first-word-letters are Capitalized.

Also, while it is often convenient to shorten long parts of variables, the abbreviation of 'user' to 'usr' is not saving you much.....

So, for example, your variables :

String usrname;
String usrage;
String usrgender;
Double usrheight;

would be

String userName;
String userAge;
String userGender;
Double userHeight;

I would recommend that you use an IDE (Eclipse/IntelliJ/Netbeans) to help you get these things right. There is some debate about whether new programmers should use an IDE or not, because they make some things really easy and you may miss understanding some of the basic requirements of the language.... but, I believe that the IDE's allow you to focus on the stuff that is more important, like the code content.