Distinct

In a properly designed database, this DISTINCT should not be needed:

  (SELECT COUNT(DISTINCT `ORDER_ID`)
   FROM `ORDERS`

If multiple different orders can have the same ORDER_ID, we're gonna have a bad time.

Aliases

c, d, r... these are bad table aliases. Why? Because Mr. Maintainer has to go through your entire query to know what those mean, as they are not self-evident. Your table names are pretty short, but if you really need to shorten them further... perhaps something like crier, deliv, coord would be better.

Join syntax

This USING command:

FROM `COURIERS` AS c
LEFT JOIN `DELIVERIES` AS d USING (`COURIER_ID`)

USING is not standard SQL syntax, when it comes to joins. Sure, it can be a nice shorthand in MySQL, but generally it is preferred to use standard SQL syntax (usually more verbose) instead of depending on syntactic sugar provided by a particular build or version of a language. Like this:

FROM `COURIERS` AS c
LEFT JOIN `DELIVERIES` AS d
ON c.`COURIER_ID` = d.`COURIER_ID`

Performance

It's a bit difficult to assess performance hiccups if not presented with the execution plan, or a sample dataset to reproduce the issue. If I had to guess, I would say you have too many subqueries in your CASE statements.

CASE statements are great and very fast when you use constants to compare; but when you use variable values, such as what you are doing... well... it's pretty slow. You're asking the SQL engine to run each subquery for each record essentially. It may find a way to optimize that's halfway efficient, but I believe you would be better using a set-based approach. Example:

WHERE (CASE WHEN
         (SELECT MAX(`START_DATE`)
          FROM `DELIVERIES`
          WHERE `COURIER_ID` = c.`COURIER_ID`) IS NULL THEN d.`START_DATE` IS NULL ELSE -- etc.

Instead:

-- this goes before your CASE statement
INSERT INTO TEMP TABLE DeliveryDates
    SELECT IFNULL(
        MAX( d.`START_DATE`, NULL )
    )
WHERE d.`COURIER_ID` = c.`COURIER_ID`

Then:

WHERE (CASE WHEN
         (SELECT `START_DATE`
            FROM DeliveryDates) IS NULL THEN d.`START_DATE` IS NULL
        ELSE d.`START_DATE`


Filewatcher compiler for watching different files

Sort your imports alphabetically. Make it easier to find.  - Core libs first, then 3rd party.

import multiprocessing
import threading
import os
import time

Constants are typically in all caps.

file_lock = threading.Lock()
update_interval = 0.1

If you have some TODOs, a common practice is to use code tags.

# FIXME:
# TODO:

It's not a must standard, but it is something that is easily recognizable.

class FileMethods(object):
    def a_import(self):
        # do some sort of file manipulation

Ditto on the docstring. Include a desc of your attributes as well.

class FileObject(FileMethods):
    def __init__(self, full_name, compiler):

I would change

self.concat_name = name + '-concat' + exstention

self.concat_name = ''.join([name, '-concat', extension]) # Assuming extension was a typo.

I don't see this method being used anywhere. You also have an if statement further down
in your code. I would remove this if your not using it. Also, I probably wouldn't create a method for this unless I had to write this out more than 2 times. I only see one instance in your code.

def exists(self):
    return os.path.isfile(self.full_name)

Is this script meant to run interactively? If so, I would suggest adding an interactive flag.

So you can run this in automated fashion (maybe with a config file), or a -i so I can be prompted for input. Also, I would change your print statements to the nicer print statements. They
also add more flexibility. Consider using argparse for this.

print '%s updated' % self.file_name

print '{} updated'.format(self.file_name)

Docstrings

def sub_mod_check(self):

Ditto on the print statements:

Use .format

        print 'Adding %s with %s as compiler' % (obj.file_name, obj.compiler)
    else:
        print 'File does not exists'

Consider using a main function or method to wrap your logic into when calling your script.

if __name__ == '__main__':
    iw = threading.Thread(target=input_watcher)
   s fw = threading.Thread(target=file_watcher)

if __name__ == '__main__':
    main()


To avoid repetitive code, make the Log class do only one of the three things it currently does, and create three instances instead:

class Log(object):
    def __init__(self, name):
        self.name = name
        self.data = {}

    def add_item(self, key, status, item_name, score):
        key = '%s %i' % (self.name, key)
        if key not in self.data:
            self.data[key] = {"Comp": defaultdict(int),
                         "Miss": defaultdict(int),
                         "Post": defaultdict(int),
                         "Add": defaultdict(int),
                         "Score": 0}

        self.data[key][status][item_name] += 1
        self.data[key]['Score'] = score

def update_views(log_file):
    daily_log = Log('Day')
    weekly_log = Log('Week')
    monthly_log = Log('Month')
    ...


Not bogobogosort
The way you implemented your bogobogosort, it is actually faster than bogosort because of a few reasons:

After you successfully bogosort k elements, you immediately check whether k+1 elements are sorted.  This means that if on a previous shuffle, you happened to shuffle m elements all in order, then after you sort the first two elements you will immediately reach m.
For example, suppose you reach 5 cards and then fail.  You shuffle 5 cards and then start over at 2.  If those 5 cards happen to be in sorted order, you will immediately reach 6 as soon as you put the first 2 cards in order.

Because of point #1, your bogobogosort is actually faster than the bogosort because it only needs to sort n-1 cards instead of n.  After it sorts n-1 cards, it checks the order of n cards and may fail.  But in failing, it reshuffles n cards so that each time it sorts n-1 cards it has a 1/n chance of eventually succeeding.  So the total number of cards shuffled is on the order of (n-1) * (n-1)! * n which simplifies to (n-1) * n!, compared to the bogosort which shuffles n * n! cards.
I believe that the same principle applies at each step, so the time is even less than (n-1) * n!.  I'm not sure of the exact math but from running your program it appears that the bogobogosort runs in approximately the same time as the bogosort with one fewer cards.  I.e. Your_bogobogosort(n) = bogosort(n-1).

A proper bogobogosort
I rewrote your bogobogosort function to be like this:
unsigned long bogobogosort(int *data, size_t n) {
    unsigned long c = 0;
    size_t b = 2;

    while (1) {
        if (sorted(data, b)) {
            if (b == n)
                break;
            b++;
        } else {
            b = 2;
        }
        c += b;
        shuffle(data, b);
    }
    return c;
}

The key difference here is that after each success where it increments b, it reshuffles the deck to prevent point #1 above from happening..  With this change, I get output like this:
% ./a.out 6
    bogosort shuffled         1044 cards in 0.000013 seconds.
bogobogosort shuffled     54464568 cards in 0.500339 seconds.


Heap insertion and deletion Implementation using Python

Integer division
Are you using Python 3?  If so, there is the integer division operator: //.  Instead of:
    p_index = int((i-1)/2)

you can write:
    p_index = (i - 1) // 2

Unnecessary variable
In your insert function, where do you use n?
    n = len(arr)
    ...
    i = n # last position

Seems like you can get rid of the n variable, and just initialize i = len(arr)
Wrong variable
In delete, where do you use n?
You might say it is used in several places.  I'd disagree.  I'd say it is never used; you only use n-1.
What is n-1?  It is the last index of the array:
    last = len(arr) - 1

    ...

    if lc_index > last:
        ...
    if lc_index == last and rc_index > last:
        ...

Unnecessary test:
Consider:
    lc_index = 2*i + 1
    rc_index = 2*i + 2

Note that we could rewrite that last statement as
    rc_index = lc_index + 1

Now consider:
    if lc_index == last and rc_index > last:
        ...

Substitute for rc_index ...
    if lc_index == last and lc_index + 1 > last:
        ...

If the first part of that test is True, the second part will always be True; if the first part is false, the second part will never be evaluated.  So you just need:
    if lc_index == last:
        ...

Left or right?
The code for the left & right children look identical, save for the index being used.
Instead of:
        if arr[lc_index] > arr[rc_index]:
            arr[i], arr[lc_index] = arr[lc_index], arr[i]
            i = lc_index
        else:
            arr[i], arr[rc_index] = arr[rc_index], arr[i]
            i = rc_index

You could select the correct left or right index to use:
        child_index = lc_index if arr[lc_index] > arr[rc_index] else rc_index

Then you don't need two copies of the remaining code:
        arr[i], arr[child_index] = arr[child_index], arr[i]
        i = child_index

Last element
 arr[0], arr[len(arr)-1] = arr[len(arr)-1], arr[0]

The arr[len(arr)-1] references the last element of arr, by determining the length of the array, and subtracting one to compute the zero-based index.
Using arr[-1] also references the last element of the array, using Python's negative indexing feature.  This allows a much simpler statement:
 arr[0], arr[-1] = arr[-1], arr[0]


I think it's looking pretty good so far!

A few things,

I would make the Node class private. This is an implementation detail and nobody using your list should need to know or worry about it. I would also remove any public facing methods that return a Node over a T. If you want them internally you can make them private. (The built in Java LinkedList uses a private Node class but we don't need to worry about it)

You could remove a lot of boiler plate getters and setters by making the Node class private. You can access the fields directly within your SinglyLinkedList class.

When someone passes in a bad index, I would prefer and IndexOutOfBoundsException over IllegalArgumentException. (this is what java.util.Lists do afterall)

As well as this, I'd also like to see a more descriptive exception message. Maybe say which index was used, and what the current size is of the list.

You've overridden equals and hashCode in your node class which is usually a good thing to do in general, but here you don't really need it. However you may like to keep it if you end up adding additional functionality that may rely on it.

I think special casing index 0 is perfectly fine. 2 distinct things happen depending on it being the first element or any subsequent one.

A nice toString method would also be good here, you could just use a StringBuilder or StringJoiner to do this easily.


Recursively walk directories with a callback function

First, use a docstring instead of a comment:

"""Recursively walk a directory."""
function [ . . . ]

Using a docstring allows Julia's built-in help features to work with your function.

Next, I would recommend putting the function argument first:

function dirwalk(fn::Function, path::AbstractString)

Why? This allows dirwalk to be used with Julia's do block syntax:

dirwalk("path/to/file") do p
    # do stuff with p, the path
end

which is often nicer than using anonymous function syntax.

Now for the function itself, you don't need a temporary variable to store content. This:

for c in readdir(path)

is shorter and reads just as well. Inside the loop, things generally look fine (except the order of dirwalk could be reversed). Note that your implementation ignores symlinks, which are neither directories nor regular files.

As for style, the Julia style guide recommends 4-space indenting. Some projects use 2-space indenting, however, and that is a personal decision.

Finally, you might be interested in the walkdir function.


javascript - consolidate multiple null/undefined checks

.getElementsByClassName() returns an HTMLCollection, not a single element. You can use bracket notation [n] to get an element at index n of the collection returned.

One if statement can be used to evalaute !itemData.isDynamicRecommendation. One if..else..if can be used to evaluate itemTemplateQty[0] && itemTemplateQty[0].value <= 0 or itemTemplateIDQty[0] && itemTemplateIDQty[0].value <= 0.

To convert the string .value to an integer you can use + operator preceding +itemTemplateQty[0].value.value or alternatively use .valueAsNumber.

let itemData = 5;
let isDynamicRecommendation = false;

let itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];
let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];
let quantity = 1;
if (!isDynamicRecommendation) {
  if (itemTemplateQty && itemTemplateQty.value <= 0) {
    quantity = +itemTemplateQty.value;
  } else if (itemTemplateIDQty && itemTemplateIDQty.value <= 0) {
    quantity = +itemTemplateIDQty.value;
  }
}

console.log({quantity});


Compare sequence & maps headers in fasta file

Obvious things: use strict and warnings. Use three argument form of open, use lexical file handles, check the success of open or use autodie.

When I run the program, Seq6 is not reported in the output. That's because the outer loop exhausts File2, not File1.

#!/usr/bin/perl
use warnings;
use strict;

my $start_run = time;
my %hash;
my $previous;

open my $SBJ, '<', 'File1.fasta' or die 'File not found';
while (<$SBJ>) {
    chomp;
    if (/^\w+/) {
        $hash{$previous} = $_;
    } else {
        $previous = $_;
    }
}
close $SBJ;

my %dash;
undef $previous;
open my $QUERY, '<', 'File2.fasta' or die 'File not found';
while (<$QUERY>) {
    chomp;
    if (/^\w+/) {
        $dash{$previous} = $_;
    } else {
        $previous = $_;
    }
}
close $QUERY;

open my $OUT, '>', 'Output.txt' or die $!;
my @new_array;
for my $temp (keys %hash) {
    for my $key (keys %dash) {
        if($hash{$temp} eq $dash{$key}) {
            push @new_array, $key;
        }
    }
    if (@new_array > 0) {
        print {$OUT} "$temp\t@new_array\n";
    } else {
        print {$OUT} "$temp\tNot found\n";
    }
    @new_array = ();
}
close $OUT or die $!;

my $end_run = time;
my $run_time = $end_run - $start_run;
print "Job took $run_time seconds\n";

If performance is a problem, you can try trading memory for speed: Hash by the sequences, not by their names:

#!/usr/bin/perl
use warnings;
use strict;

my $start_run = time;
my %hash;

open my $SBJ, '<', 'File1.fasta' or die 'File not found';
my $id;
while (<$SBJ>) {
    chomp;
    if (/^>/) {
        $id = $_;
    } else {
        $hash{$_} = $id;
    }
}
close $SBJ;

my %dash;
undef $id;
open my $QUERY, '<', 'File2.fasta' or die 'File not found';
while (<$QUERY>) {
    chomp;
    if (/^>/) {
        $id = $_;
    } else {
        $dash{$_} = $id;
    }
}
close $QUERY;

open my $OUT, '>', 'Output.txt' or die $!;
for my $seq1 (keys %hash) {
    if (exists $dash{$seq1}) {
        print {$OUT} "$hash{$seq1}\t$dash{$seq1}\n";
    } else {
        print {$OUT} "$hash{$seq1}\tNot found\n";
    }
}
close $OUT or die $!;

my $end_run = time;
my $run_time = $end_run - $start_run;
print "Job took $run_time seconds\n";

Reading the files is exactly the same code with just the hash name different. I'd refactor it into a subroutine to keep the code DRY (Don't Repeat Yourself):

sub read_fasta {
    my $filename = shift;
    my ($id, %hash);
    open my $FH, '<', $filename or die "Can't open $filename: $!";
    while (<$FH>) {
        chomp;
        if (/^>/) {
            $id = $_;
        } else {
            $hash{$_} = $id;
        }
    }
    return %hash
}

my %hash = read_fasta('File1.fasta');
my %dash = read_fasta('File2.fasta');


Improve a script to generally check status of several git repos

Yes there is a better way of filling an array. You can use globbing inside of array parens. Also I suggest being explicit about what you do in bash and use declare -a to declare arrays and later on declare for other variables

declare -a repos=(~/repos/* ~/.vim ~/dot_files ~/bin)

In case of adding stuff to an array, after it got created:

repos+=("more stuff" here)

Maybe you want to name you iterating variable more verbose, instead of d repodir or something.

Your first if contains a continue so you can emphasize on this one and just go on with no else. Also don't miss the double quotes in case of directory names with spaces in them. Also you should check for -d since you cd into it.

if [ -d "$d" ]; then
  echo "No repo at $d"
  continue
fi
cd "$d"

[ ! -z "`cmd`" ] is more verbose than it needs to be. You can just do [ "`cmd`" ].

Read the "Arrays" chapter in the bash manpage.

I attach my test file for this answer which also shows functions and some refactoring which allows to discard this ok variable.

#!/bin/bash
main() {
    local -a repos=(* /foo/bar)
    echo -e "repos: ${repos[@]}"
    for path in "${repos[@]}"; do
      check_repo "$path"
    done
}

check_repo() {
    local path="$1"
    local name="`basename "$path"`"
    local report=""
    if [ ! -d "$path" ]; then
      echo -e "$name\n not a directory: $path"
      return
    fi
    cd "$path"
    if [ "`echo foo 2> /dev/null`" ]; then
        report+="\n oh oh"
    fi
    cd - > /dev/null
    if [ -z "$report" ]; then
        report+="\n OK"
    fi
    echo -e "$name$report"
}

main


It is a good practice for Airflow. Moreover, Airflow positioning it as one of their "killer-features". It is good to create dynamic tasks in DAG, it is pretty OK to create dynamically created DAGs. One thing I recommend you to think about is that it is not good to create hundreds and thousands of one-time-running tasks because it will lead to:

Filling your Airflow database with huge amount of garbage data
Inability to analyze DAGs visually. Here is the example of Airflow tree tab of tasks like these:

Here is the sample code for dynamic DAG creation:

from datetime import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator

def create_dag(dag_id, schedule, dag_number, default_args):

    def hello_world_py(*args):
        print('Hello World')
        print('This is DAG: {}'.format(str(dag_number)))

    dag = DAG(dag_id,
              schedule_interval=schedule,
              default_args=default_args)

    with dag:
        t1 = PythonOperator(
            task_id='hello_world',
            python_callable=hello_world_py,
            dag_number=dag_number)

    return dag

# build a dag for each number in range(10)
for n in range(1, 10):
    dag_id = 'hello_world_{}'.format(str(n))

    default_args = {'owner': 'airflow',
                    'start_date': datetime(2018, 1, 1)
                    }

    schedule = '@daily'

    dag_number = n

    globals()[dag_id] = create_dag(dag_id,
                                  schedule,
                                  dag_number,
                                  default_args)

You can read more about it here.


Finding number pairs where the sum of their divisors are each other

Mike is correct that you are repeating the sum multiple times for each value. A simple array with the stored sum will make a huge difference.

On the other hand, you are also doing a huge amount of unnecessary work in here:

def diviseurs_propres(n):
    t = [1]
    for i in range(2,n):
        if n%i == 0:
            t.extend([i])
    return t

def somme_diviseurs_propres(n):
    t = diviseurs_propres(n)
    S = sum(list(t))
    return S

There is no need to store the actual values in an array, it can be simplified to just:

def somme_diviseurs_propres(n):
    sum = 1
    for i in range(2, n):
        if n % i == 0:
            sum += i
    return sum

With a little bit of math, you can significantly reduce the number of iterations by iterating to the square-root of the value:

def somme_diviseurs_propres(n):
    sum = 1
    root = int(math.ceil(math.sqrt(n)))
    for i in range(2, root):
        if n % i == 0:
            sum += i + (n / i)
    if root > 1 and root * root == n:
        sum += root
    return sum

The way the above code works, is each time you have a value \$a\$ that is a factor of \$n\$, then there must be a value \$n / a\$ that is also an factor.

Thus, for large values of \$n\$, like 1000000, you only need to iterate from 2 to 1000 (exclusive) to sum the factors. Now, because 1000000 is an exact square, the root is an actual integer too, and the last if-statement above adds in the value 1000 to the sum.

In addition to the above, you can also rearrange the double-loops so that the inner loop is limited by the outer loop, and then add the pairs twice to the results. This changes the order of the results, but not the actual content.... Finally, your use of extend should be replaced with append...

def trouveur(n):
    t = []
    for i in range(0, n+1):
        for p in range(0, i):
            if somme_diviseurs_propres(i) == p and i == somme_diviseurs_propres(p):
                t.append(p) and t.append(i)
                t.append(i) and t.append(p)
    return t

Now, there's a bug in there, I believe. The code:

t.extend([p]) and t.extend([i])

does not add the second value i. You only add the i on the second time through, when i == p and p == i .... Your code above is equivalent to just:

t.extend([p])

Using a dictionary

As an update, I have considered a second soltuion, that should significantly reduce the amount of iteration in the inner loops, at the expense of lookups in a dictionary.

The dictionary maps the sum-of-factors to the values that have that sum. For example, the sum of factors for 6 and 25 are both 6. (sum of factors of 6 are 3 + 2 + 1, and for 25 it is 5 + 1). The mapping looks like:

6 -> [6, 25]

Using that mapping, we can look for sums that have cross-references... We can loop through just the sums of the factors, and for each sum, in their set of input values, see if those values exist as sums of other values. If they do, then see if the original sum is one of them.... This makes sense if you see an example:

220 -> [284]
284 -> [220]

the top value shows that the sum of factors for 284 is 220, and the sum of factors for 220, is 284.

Taking the first value, we know the sum of factors, and we take all the values that sum to that (in this case, just 284), and check whether 284 happens to be the sum of some other value's factors. Then we check to see whether one of those other values is 220.

def trouveur(n):
    sommeMap = {}
    for i in range(1, n + 1):
        s = somme_diviseurs_propres(i)
        if s in sommeMap:
            sommeMap[s].append(i)
        else:
            sommeMap[s] = [i]

    t = []
    for i,ps in sommeMap.items():
        for p in ps:
            if i < p and p in sommeMap and i in sommeMap[p]:
                t.append(i)
                t.append(p)
    return t

Performance results:

Your initial code, with a limit of 500

Result: [284, 220]

real    0m4.851s
user    0m4.840s
sys     0m0.012s

Using Mike's suggestion of saving away the sums:

def trouveur(n):
    somme = []
    t = []
    for i in range(0,n+1):
        somme.append(somme_diviseurs_propres(i))

    for i in range(0,n+1):
        for p in range(0,n+1):
            if p != i and somme[i] == p and i == somme[p]:
             t.extend([p]) and t.extend([i])
    return t

This produces the times:

Result: [284, 220]

real    0m0.064s
user    0m0.056s
sys     0m0.008s

Including the changes I suggest

no arrays for the sum of factors
change the loops
separate the i and p appends

Code:

import math

def somme_diviseurs_propres(n):
    sum = 1
    root = int(math.ceil(math.sqrt(n)))
    for i in range(2, root):
        if n % i == 0:
            sum += i + (n / i)
    if root > 1 and root * root == n:
        sum += root
    return sum

def trouveur(n):
    somme = []
    t = []
    for i in range(0, n + 1):
        somme.append(somme_diviseurs_propres(i))

    for i in range(0, n + 1):
        for p in range(0, i):
            if somme[i] == p and i == somme[p]:
                t.append(p)
                t.append(i)
    return t

print "Result: {}".format(trouveur(500))

and results:

Result: [220, 284]

real    0m0.028s
user    0m0.016s
sys     0m0.008s

Note that it is now possible to run the code up to 10000 as well....

Result: [220, 284, 1184, 1210, 2620, 2924, 5020, 5564, 6232, 6368]

real    0m2.453s
user    0m2.444s
sys     0m0.004s

Using dict (sommeMap)

Result: [220, 284]

real    0m0.024s
user    0m0.016s
sys     0m0.008s

and for 10,000 it runs in:

Result: [220, 284, 1184, 1210, 2620, 2924, 5020, 5564, 6232, 6368]

real    0m0.092s
user    0m0.088s
sys     0m0.000s

Which is significantly faster, and we can extend that even further now, to say 1,000,000 values:

Result: [[220, 284], [1184, 1210], [2620, 2924], [5020, 5564], [6232, 6368],
    [10744, 10856], [12285, 14595], [17296, 18416], [63020, 76084], [66928, 66992],
    [67095, 71145], [69615, 87633], [79750, 88730], [100485, 124155], [122265, 139815],
    [122368, 123152], [141664, 153176], [142310, 168730], [171856, 176336],
    [176272, 180848], [185368, 203432], [196724, 202444], [280540, 365084],
    [308620, 389924], [319550, 430402], [356408, 399592], [437456, 455344],
    [469028, 486178], [503056, 514736], [522405, 525915], [600392, 669688],
    [609928, 686072], [624184, 691256], [635624, 712216], [643336, 652664],
    [667964, 783556], [726104, 796696], [802725, 863835], [879712, 901424],
    [898216, 980984]]

real    0m55.310s
user    0m55.135s
sys     0m0.164s

Code Drop

This is the final version of the code I have. The code above has gone through a number of iterations, and was inconsistent in places:

import math

def somme_diviseurs_propres(n):
    sum = 1
    root = int(math.ceil(math.sqrt(n)))
    for i in range(2, root):
        if n % i == 0:
            sum += i + (n / i)
    if root > 1 and root * root == n:
        sum += root
    return sum

def trouveur(n):
    sommeMap = {}
    t = []
    for i in range(1, n + 1):
        s = somme_diviseurs_propres(i)
        if s in sommeMap:
            sommeMap[s].append(i)
        else:
            sommeMap[s] = [i]

    for i, ps in sommeMap.items():
        for p in ps:
            if i < p and p in sommeMap and i in sommeMap[p]:
                t.append([i, p])
    return t

print "Result: {}".format(trouveur(100000))


A special case length < 3 seems like a bug. A string aa is a palindrome, and one could successfully argue that a single-letter string is also a palindrome.
A boolean isPalindrome is redundant, and forces the code to test the effectively same condition twice. An early return is perfectly fine here.
A traditional idiomatic (and arguably more performant) way to iterate forward is *first++. Similarly, an idiom for iterating backwards is *--last (that also avoids subtracting 1 beforehand):

    last = possiblePalindrome.end();
    while (first < last) {
        if (*first++ != *--last) {
            return false;
        }
    }
    return true;

The naming is very inconsistent. I don't see the reason to spell palindrome in 3 different ways. A capitalization in iSPalendrome is also strange.


Given suffix array and a pattern, search if given pattern exists

Since you have a hidden implementation requirement that the suffix be sorted (i.e. binary search), you should sort the array before assigning it to the member variable.

Your compare implementation differs from that of the String class in that it returns 0 if str starts with pattern. Why not code it that way?

private int compare(String str, String pattern) {
     return str.startsWith(pattern) ? 0 : str.compareTo(pattern);
}


The number one problem here is that you concatenate translated letters on to your string one at a time.  Since strings are immutable in .NET (and most right thinking languages), this means for the first translated character your program allocates space for a new string of length 1 (copying the previous 0-char string), for the second character it allocates space for a new string of length 2 (copying the previous 1-char string), for the third character it allocates space for a new string of length 3 (copying the previous 2-char string), and so on.  The end result is that for an input n characters long, your program will allocate 1 + 2 + 3 + ... + n = \$O(n^2)\$ space and, similarly, perform \$O(n^2)\$ operations!  A better structure is to use a .NET StringBuilder which is designed precisely for this piecemeal kind of string construction.  Using a StringBuilder your program will allocate \$O(n)\$ space and perform \$O(n)\$ operations -- that's a big saving when your input is of any non-trivial length.


Constructing a class from a line in a parameter file

The approach to doing this is two-fold. Firstly, you'll want to modify your classes to have a constructor taking an std::istringstream& as an argument. The second part will be to make a map of strings to constructor functions. So let's assume our (skeleton) classes look something like:

class Potential
{
public:

    virtual ~Potential() { }

    virtual void print() const = 0;

};

class NFW
  : public Potential
{
private:

    double rho0;
    double rs;

public:

    NFW(std::istringstream& iss)
    {
        iss >> rho0 >> rs;
    }

    virtual ~NFW() = default;

    virtual void print() const override
    {
        std::cout << "NFW: rho0: " << rho0 << ", rs: " << rs << "\n";
    }
};

class MiyamotoNagai
  : public Potential
{
private:

    double m, a, b;

public:

    MiyamotoNagai(std::istringstream& iss)
    {
        iss >> m >> a >> b;
    }

    virtual ~MiyamotoNagai() = default;

    virtual void print() const override
    {
        std::cout << "MiyamotoNagai m: " << m << ", a: " << a
                  << ", b: " << b << "\n";
    }
};

We then define the type our map will hold: it will hold a function that will return a std::shared_ptr<Potential>, and will take a std::istringstream& as an argument:

using function_t = std::function<std::shared_ptr<Potential>(std::istringstream&)>;

Using this, our map becomes:

std::unordered_map<std::string, function_t> register_map;

To add to this, we just need some very simple lambda functions that forward to the corresponding constructor:

register_map["NFW"] = [](std::istringstream& iss) { return std::make_shared<NFW>(iss); };
register_map["MiyamotoNagai"] = [](std::istringstream& iss) { return std::make_shared<MiyamotoNagai>(iss); };

The function to actually create our Potential subclass then looks like:

std::shared_ptr<Potential> create_potential(std::istringstream& iss)
{
    std::string potential_type;
    iss >> potential_type;
    auto it = register_map.find(potential_type);
    if(it == register_map.end()) {
        throw ParseError("Unknown Potential " + potential_type);
    }
    return it->second(iss);
}

With this, each constructor will need to do its own checking and error handling (which I've omitted above). As written, this better adheres to the open-closed principle (code should be open for extension, closed for modification), as the only thing you should have to touch when you create another subclass is adding another call to register_class[...].

A test example:

int main()
{
    register_map["NFW"] = [](std::istringstream& iss) { return std::make_shared<NFW>(iss); };
    register_map["MiyamotoNagai"] = [](std::istringstream& iss) { return std::make_shared<MiyamotoNagai>(iss); };
    std::istringstream iss("NFW 5 4");
    auto test = create_potential(iss);
    test->print();
}

As a final point, make absolutely sure this needs a shared_ptr over a unique_ptr. Without context it is impossible to tell, but you should always reach for unique_ptr first, and shared_ptr only if it is absolutely necessary; it may be in this case, but it is still something to very carefully think about.


I'm going to leave the ms-access specifics to more proficient ms-access reviewers, as I'm not all that familiar with DAO and Access VBA.
If possible, switch to SQL Server ADODB.

DEADC0DE
Unless I'm missing something, you're inlining the SQL statements and Dim strSQL As String is an unused declaration.
These can be hard to spot without an add-in though. MZ-Tools has a review source code feature that can find unused variables and procedures; Rubberduck has a code inspections feature that can find that too, and a number of other code issues (disclaimer: I own and maintain rubberduck, see tag info).

UX Issue?
DoCmd.Hourglass True

You're turning the hourglass on, but you never turn it back off. I would expect this:
Exit_ClientSelection_AfterUpdate:
    DoCmd.Hourglass False
    Exit Sub

The error handler is problematic:
MsgBox "Error " & Err.Number & ": " & Err.Description & " in " & _
    VBE.ActiveCodePane.CodeModule, vbOKOnly, "Error"

This cannot reliably be reporting the source of the error, unless there's only 1 module in your VBA project. Proof:
Module1
Public Sub Boom()
    MsgBox VBE.ActiveCodePane.CodeModule
End Sub

Module2
Public Sub DoSomething()
    Module1.Boom
End Sub

If Module2 is the opened module when you run DoSomething, the message will say Module2, not Module1 where the "error" would have happened.
And it requires adding a reference to the VBIDE extensibility library in your VBAProject, which requires special security handling. Not ideal.


Instead of temporarily changing directories, you can call realpath to get the absolute path to a directory. There is also readlink which does similar job.

To generate the files array:

files=("$@"); unset "files[-1]"

The rest looks okay to me. However, keep your usage of ; consistent. If you are using it, put them in each statement; otherwise skip it altogether.


it's a bit hard to comment on your question as it's really very general.
You say that the device should receive commands as fast as possible and with very few data and than you ask "Does it overload the server? Is it fast enough for the client?", but you don't mention what kind of operations would be actually performed and in what way. The process of receiving and parsing command is usually much faster than the process of executing parsed command.

As for the code itself, the client side looks a bit like reinventing the wheel - why don't you try jQuery?
As for the server code (content.php), it's hard to tell what it does other than it obviously tries to read a file from disk serveral times, but even if succeeds - it still does nothing...

Maybe if you'd ask more specific questions, I could be more of a help.


Unit testing where you depend on implementation of another method

It's usually hard to test a setter without a getter and vice versa. Back Door Manipulation in xUnit Test Patterns discuss this in detail.

Some smells from the same book/site:

Eager Test: A single test verifies too much functionality.
Missing Assertion Message: A test fails. Upon examining the output of the Test Runner, we cannot determine exactly which assertion had failed.

I'd create at least three tests from the one above:

@Test
public void testInsert() {
    gapBuffer.insert('a')
    assertEquals(gapBuffer.getText(), "a")
}

@Test
public void testInsertTwice() {
    gapBuffer.insert('a')
    gapBuffer.insert('c')
    assertEquals(gapBuffer.getText(), "ac")
}

@Test
public void testMoveCursorToAndInsert() {
    gapBuffer.insert("acd")
    gapBuffer.moveCursorTo(1)
    gapBuffer.insert('d')
    assertEquals(gapBuffer.getText(), "abcd")
}

It helps Defect Localization.


The first thing I noticed is that you've defined methods such as word_occurrences, which do nothing but set instance variables (@word_occurrences, etc.). This is a bit redundant, and it would be better to do one of two things:

Define all of your instance variables under the initialize method. or
Take out the @word_occurrences ||= part of the method definition.

I think from a performance standpoint, it might be better to take the first approach, since you don't want to have to calculate word_occurrences every time you call it as a method. I also noticed that you only use @words and @filter once, and that's to define filtered_words, so you can make things simple by just defining @words to be what filtered_words is currently. See below:

def initialize(text, filter)
  @words = text.split.reject {|word| filter.split.include? word.downcase}
  @occurrences = @words.each_with_object(Hash.new(0)) {|word, result| result[word] += 1}
  @lengths = @words.each_with_object({}) {|word, result| result[word] ||= word.length}
end

I've made @words the new filtered_words, shortened word_occurrences to just @occurrences (and made it an instance variable so that we're only evaluating it once, upon initialization of the instance), and added another instance variable @lengths, which represents a part of your longest_words function, a hash of each word and how long it is.

Also, notice that I simplified your use of inject to create a hash of word occurrences and word lengths, by using the handy each_with_object function instead.

I also changed = to ||= for the part where you're building up a hash of word lengths. I believe this will be better for performance, as you're not re-calculating the word length for words you already have.

You mentioned duplication between longest_words and highest_occurring_words -- you could solve this by pulling out the part you reused into a private function, which I would call highest_ranking:

private

def highest_ranking(entries)
  # Takes a hashmap of the form {"foo" => 100, "bar" => 45} and returns an array
  # containing the entries (array-ified) with the highest number as a value.
  entries.group_by{|word, occs| occs}.sort.last.last
end

I simplified max_by{|key, value| key}.last to just sort.last.last -- it turns out that Enumerable#sort knows how to properly handle sorting by keys, so getting the highest one is just a matter of sorting the hash and grabbing the last item in the resulting array. (The extra last is there for the same reason the last is there in your function -- to drop the number of occurrences and just return the key/value entries in the result array)

Now that you have this useful helper function, finding the highest occurring words and longest words is simple:

public

def highest_occurring_words
  highest_ranking @occurrences
end

def longest_words
  highest_ranking @lengths
end

Finally, I would refactor your html_list function like this:

def html_list
  list = word_occurrences.sort_by {|word, occs| occs}.reverse.map do |word, occs|
    "
#{word}: #{occs}
"
  end.join("\n")
  "
\n" + list + "\n
"
end

Instead of starting with list as "" and iterating through each word/occurrences pair to add onto it a little at a time, you can take a functional approach and use map to turn each word/occurrences pair into a string like "
antibubbles: 4
", then use join to turn the resulting array into one long string with "\n" inserted in between each list item. I also inserted two spaces before each list item so that they appear indented in the HTML. :)


HackerRank - Left Rotation in JavaScript

Review

Since you are building the array yourself, as opposed to you get a source array from a consumer of your method, I don't think you should create a new array, but rather just adapt the source array. This way, you could avoid slice and concat altogether.
The number of rotations is an integer. However, reading the description behind the link tells use it's clamped between 1 <= rotations <= nd. There is a slight optimization here. If rotations = nd you don't have to do anything, since a rotation is circular. An elegant way to check this is to normalize rotations as rotations = rotations % nd; assuming you have already checked rotations againsts the clamped range. if rotations = 0, don't rotate.
There's another optimization if nd < 2, then any rotation is the source itself.


Using third party library named "nsetools" for fetching stock data

You never use stocks, so I removed it. It would also help if your qty actually had the exact same keys as you need for nse.get_quote (namely lowercase names), so I did that as well.

In addition, you can convert your whole code into one generator, which you can then sum over:

from nsetools import Nse
nse = Nse()

def get_closing(stock):
    return nse.get_quote(stock)['closePrice']

stock_qty = {"ADANIPORTS": 20,
             "HINDALCO": 20,
             "ONGC": 20,
             "SBIN": 20 }

stock_gen = (get_closing(stock) * qty for stock, qty in stock_qty.items())
current_value = sum(stock_gen)

If you already have stocks, you could just do:

stocks = {
    "ADANIPORTS" : 284.95,
    "HINDALCO"   : 152.30,
    "ONGC"       : 279.70,
    "SBIN"       : 259.70
}

#stock name and quantity of stocks
qty = {
    "ADANIPORTS" : 20,
    "HINDALCO"   : 20,
    "ONGC"       : 20,
    "SBIN"       : 20
}
current_value = sum(val * qty[stock] for stock, val in stocks.items())


Error handling in controller (MVC structure)

I advice you forego if checks completely and go for try-catch blocks, and have your verifiers throw exceptions on error. So, you do something like this:

try {
     LoyaltyDomModel::loyaltyVerification($post_data);
     LoyaltyDomModel::setVerify(Yii::$app->user->identity, $post_data);

     return  ['body'=>'successfull','status' => true];
} catch (LoyaltyVerificationException $e) {
     return ['body' => $e->getMessage(), 'status' => 'error']
} catch (UserUpdateException $e) {
     return ['body' => $e->getMessage(), 'fields' => $e->getFields(), /* you can pass custom info to exceptions, right? */, 'status' => 'error'];
}

Also, it's not a good idea to return bool in one case ('status' = true) and string in another ('status' = 'error');


You might already know this but you can add a library class called 'template' it allows you to make a kind of a masterpage where you can load all different php files, for example your header - content - footer or anything else, seperately into one page.

Your controller will look like this for example:

 public function example() {
        $partials = array('header' => 'header', 'navigation' => 'navigation', 'content' => 'content');
        $this->template->load('masterpage.php', $partials);
    }

Read more at http://ellislab.com/codeigniter%20/user-guide/libraries/parser.html

It's really use to use once you know how it's done.

For example you could use for every page the same navigation but another index and header.

The masterpage looks like this:

<!DOCTYPE html>

<?php echo $navigation; ?>
<?php echo $header; ?>
<?php echo $content; ?>

The last thing you need to do is search for the library file on the net upload it and autoload the library in your configs, file: autoload or just in the constructor of your controller. I recommend autoloading the template library because you normally use it at every end of a controller to make the full view.


Many interfaces and lots of inheritance vs few interfaces and less inheritance?

Zealous nitpicking...

am I being too zealous in trying to reduce the base class and interface inheritances

Careful with wording here: a type inherits from a base class, and implements an interface. Interfaces aren't inherited, they're implemented. Subtle, but important distinction.

My two cents...
Looking at the base class in the first snippet:

public class DbService<TEntity> :
    Service<TRepository>,
    IDbQueryableService<TEntity>,
    IQueryableService<TEntity> {}

Can you spot the code smell?
What's the difference between these two interfaces?

    IDbQueryableService<TEntity>
    IQueryableService<TEntity>

You're not listing any of these interfaces, but just from the names one can tell that IQueryableService<TEntity> and IDbQueryableService<TEntity> probably overlap in functionality: they're both queryable services.
Leaky abstractions
What you have here is a leaky abstraction: you're making an abstraction (/interface), but the implementation is leaking into the abstraction - whether the data is coming from a database, from a web service, or from text files, shouldn't matter; you want an abstraction for something that can be queried... and IQueryableService<TEntity> seems to accomplish that. IDbQueryableService<TEntity> is leaking a database implementation of an IQueryableService<TEntity>.
IDbQueryableService<TEntity> is redundant and should be removed.
Same goes for IDbGettableService<TEntity>, which is leaking a database implementation of IGettableService<TEntity, TKey>, at least so it seems from the interfaces' names.
Consistency in design
Where's IDbRemovableService<TEntity>? Where's IDbAddableService<TEntity>? Where's IDbUpdatableService<TEntity>? Why aren't these operations paired with a non-IDbSomething interface like the queryable and gettable stuff?

I would have lots of other questions about why you need to have a TEntityListItem (among other things), but there's really not enough context in your question to pursue any further without assuming what your implementations do, and what methods your interfaces expose.
I suggest you post another question with your actual code, so reviewers can actually go over your code and make sound recommendations. Just reviewing class names and interfaces without even having the interface members, is pretty hard.
I would venture to say that I highly doubt you need that many generic type parameters, but without knowing more about your code all I can do is say "I don't like this"; whether it's a private API or publicly exposed to client code doesn't matter: it's code that you need to maintain and understand, now and in the future - I don't care what Visual Studio thinks the "maintainability index" is (especially when anything between 20 and 100 is "green"). Having 12 different interfaces that, together, seem to be doing what a single repository could do, doesn't feel right. In fact, the first impression I got was "boy this is over-engineered". And I'm sure the impression wouldn't go away by looking at your actual code.


Interesting little plot twist in a Java program.

First up, tryNow() is dead code, it's not used, get rid of it, it makes the rest of the class harder to understand by putting red-herrings in the code.

If it is really used somewhere else in your code (it is public static), then it should be moved out of this class in to a more usefully named location.... and it has other issues too, which I will ignore... except for .... never extend Thread directly, use Runnable ....

Next up, you should ensure you are using Java 9.x or newer, and then use the more convenient ProcessHandle API for getting your current processID

This reduces the code:

static int obtainPid() throws CantKillMeException {
    try {
        java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
        java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);
        sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
        java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);
        int pid = (Integer) pid_method.invoke(mgmt);
        return pid;
    } catch (IllegalAccessException | java.lang.reflect.InvocationTargetException | NoSuchMethodException |
NoSuchFieldException e) {
        throw new CantKillMeException("Cant obtain pid", e);
    }
}

to just:

static int obtainPid() throws CantKillMeException {
    try {
       return ProcessHandle.current().pid();
    } catch (SecurityException e) {
        throw new CantKillMeException("Cant obtain pid", e);
    }
}

Although you don't want to do a System.exit(0) I would still plan it as a backup...

You have

static void executeCommand(String command) throws CantKillMeException {
    try {
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();
    } catch (java.io.IOException | InterruptedException e) {
        throw new CantKillMeException("Cant execute command " + command, e);
    }
  }

which anticipates exceptions on something that should terminate the process....

I would instead log the exception (actually, catch any Throwable), and exit.... within a finally-block - I would do that in the now() method:

public static void now() throws CantKillMeException {
    try {
        int pid = obtainPid();
        String command = getCommand(pid);
        executeCommand(command);
    } catch (Throwable t) {
        System.out.println(t);
    } finally {
        System.exit(1);
    }
}

You can choose a different (improved) logging mechanism.


Implementation of generic unordered list in java

Does this list interface have enough methods/behavior?

Yes, it is enough. If you want to extend it consider implementing java.util.Collection interface.

Why do I have to type cast from next() while returning data?
When I am testing this class I have to do this Iterator itr = ((UnorderedList) ul).iterator(); why?

Those two questions are related. You need a cast to UnorderedList since you didn't put iterator() function in your List interface. And cast for next() is required since you used (UnorderedList) ul instead of (UnorderedList<Integer>) ul.
If MAX_SIZE is a constant it should have final modifier and shouldn't be changed in UnorderedList(int capacity). You might use nodeElements.length instead.
Node class looks pointless, there is nothing wrong with using T[] nodeElements or  better Object[] nodeElements, since generic arrays are tricky to construct.
You also shouldn't catch IndexOutOfBoundsException when you can just check if index is valid before accessing it.


Counting the number of ways to decode a string

First off, as mentioned in the comments the variable and function name(s) could be a bit more descriptive. decode is fine, but helper should be renamed to something like count_decodings. k could be len or substring_length. I disagree with the comments about data though- we know nothing about the string being passed, so the only more apt name would be lowercase string, which at first glance may get confused with the type.

Moving on to structure, you can actually revise your algorithm to do away with k, and make the substring logic simpler. Assume the string that is passed is the entire string- no offset. Then call your function recursively on a substring of the input string.

private static int helper(String data, int[] memo) {
    if (data.length() == 0)
        return 1;
    if (data.charAt(0) == '0')
        return 0;
    if (memo[data.length()] != 0) {
        return memo[data.length()];
    }

    int result = helper(data.substring(1), memo);
    if (data.length() > 1 && Integer.parseInt(data.substring(0, 2)) <= 26) {
       result += helper(data.substring(2), memo);
    }
    memo[data.length()] = result;
    return result;
}

As you can see, this results in far less index juggling, and is far easier for someone else to read. When I was writing this answer there were at least two other answers trying to figure out the correct way to juggle these indices to make the algorithm work, and both were since deleted by their authors because they were too error prone / couldn't get it working quite right. If that doesn't say something about the maintainability and readability of index juggling, I don't know what does.

Lastly, I'd like to speculate that the algorithm could possibly be sped up by minimizing the conversions between strings and integers. You could possibly replace

data.substring(0, 2)) <= 26

with

data.substring(0, 2).compareTo("26") < 1

-which would save the conversion, but at the cost of confusion and bad form (comparing numerical values as strings). Alternatively, you could convert data to an integer once, and then do floored division and modular reduction by 10 to get your digits and "substrings". These would only provide constant speedups at best, however.


Checking whether strings are permutations of each other in Swift

First some general remarks:

There is no need to terminate statements with a semicolon in Swift.
The condition in an if-statement does not require parentheses, e.g.

if debug { ... }

You should be consistent about whether to start else on a new line
or not, I prefer

if condition {
    // ...
} else {
    // ...
}

Many of your variables are not mutated and should be declared as
constants, e.g.

let line = readLine()!

The overall structure can be improved. Why is the first input line
read at the top of the program, and the remaining lines at the bottom?
I would do the complete input parsing in the "main" part of the
program, which would then look like this:

let numTestCases = Int(readLine()!)!
for _ in 1...numTestCases {
    let strings = readLine()!.components(separatedBy: " ")
    if checkEqual(first: strings[0], second: strings[1]) {
        print("YES")
    } else{
        print("NO")
    }
}

(I have omitted the "debug" feature for simplicity.)

About the createDictionary() function: A loop like

for index in 0...charCount-1 {
    // ... do something with `arrayOfCharacters[index]` ...
}

can always be simplified using enumeration:

for char in arrayOfCharacters {
    // ... do something with `char` ...
}

But actually you don't have to create an array with all characters at all: You can pass the string itself to the function, and enumerate
its characters:

func createDictionary(from string: String) -> [Character:Int] {
    var dict = ...
    for char in string.characters {
        // insert or update `dict[char]` ...
    }
    return dict
}

The nil-coalescing operator ?? can be used to simplify the
"insert or update". Also it might be advantageous to create the
dictionary with the required capacity, in order to avoid rehashing.

The function would then look like this:

func createDictionary(from string: String) -> [Character:Int] {
    var dict: [Character: Int] = Dictionary(minimumCapacity: 26)
    for char in string.characters {
        dict[char] = (dict[char] ?? 0) + 1
    }
    return dict
}

About the func checkEqual() function:

A better name might be checkPermutation().
The var flag is not really needed because you always "early return" if the comparison fails.
There is no need to assign empty dictionaries to var dictionaryOne/Two
first because they are overwritten later.
You also don't have to compare the strings lengths because they are
always equal according to the problem statement.
The

for char in "abcdefghijklmnopqrstuvwxyz".characters { ... }

loop is superfluous, it suffices to compare the dictionaries

if dictionaryOne != dictionaryTwo { ... }

Putting it all together, that function reduces to

func checkPermutation(first: String, second: String) -> Bool {

    let dictionaryOne = createDictionary(from: first)
    let dictionaryTwo = createDictionary(from: second)
    return dictionaryOne == dictionaryTwo
}

Some syntactic sugar: If you replace the global function by
an extension method of String:

extension String {
    func isPermutation(of other: String) -> Bool {
        // ...
    }
}

then the check can be more expressively done as

if strings[0].isPermutation(of: strings[1]) { ... }

For further performance improvement, note that the strings consist
of lowercase letters only, i.e. there are only 26 possible characters.
Therefore you can use a fixed-size array instead to count the number
of occurrences of each letter in the strings. Array subscripting is
much faster than dictionary lookups.

In order to compute a number (from 0 to 25) from each lowercase letter,
it is more convenient to enumerate the unicodeScalars of the string.
This leads to the following implementation:

extension String {
    func characterCounts() -> [Int] {
        let letterA: UnicodeScalar = "a"
        var counts = Array(repeating: 0, count: 26)
        for ucs in self.unicodeScalars {
            let offset = ucs.value - letterA.value
            assert(offset >= 0 && offset < 26, "only lowercase letter 'a'...'z' allowed")
            counts[Int(offset)] += 1
        }
        return counts

    }

    func isPermutation(of other: String) -> Bool {
        let counts1 = self.characterCounts()
        let counts2 = other.characterCounts()
        return counts1 == counts2
    }
}

let numTestCases = Int(readLine()!)!
for _ in 1...numTestCases {
    let strings = readLine()!.components(separatedBy: " ")
    if strings[0].isPermutation(of: strings[1]) {
        print("YES")
    } else{
        print("NO")
    }
}


Overall this seems pretty good. The calculations look correct (given sensible input) and the code is easy to follow.

Here are some suggestions for making this even better:

Cope with the user entering an empty string.

If I select a shape, and then press “enter” immediately when asked for a dimension, I get a nasty traceback printed to the console:

This program will calculate/narea of some geometric shapes for you
Shapes available are squares, triangles, circles, and trapezoid
Enter square, rectangle, triangle, circle, or trapezoid
What area would you like to calculate? square
Give length of side:
Traceback (most recent call last):
  File "areas.py", line 54, in <module>
    area_calc_logic(raw_input("What area would you like to calculate? "))
  File "areas.py", line 29, in area_calc_logic
    a_side = float(raw_input("Give length of side: "))
ValueError: could not convert string to float:

If you add a bit of debugging code around that, you see it’s trying to process float('') and choking. You should probably ask the user for the dimension again.
Handle negative dimensions.

For example, if I tell you my triangle has base -5 and height 14, you tell me that the area is -35. That seems a bit odd – isn’t area always positive?

It’s not immediately obvious how you should handle negative quantities from the user – perhaps just call abs() on their input? – but the current approach isn’t very good.
Move the area_user_logic into an if __name__ == '__main__' block.

This just means tweaking the end of the program as follows:

if __name__ == '__main__':
    print "This program will calculate/narea of some geometric shapes for you"
    print "Shapes available are squares, triangles, circles, and trapezoid"
    print "Enter square, rectangle, triangle, circle, or trapezoid"
    area_calc_logic(raw_input("What area would you like to calculate? "))

This means that the interactive session only runs when you call the script directly. If I import the file into another file, I don’t get the interactive session, just the functions you’ve defined.

This helps make your code more reusable. See What does if __name__ == '__main' do? on SO for more details.
Cope with weirdly cased input.

I claim my intention is perfectly clear here, but your program rejects it:

This program will calculate/narea of some geometric shapes for you
Shapes available are squares, triangles, circles, and trapezoid
Enter square, rectangle, triangle, circle, or trapezoid
What area would you like to calculate? Triangle
Error, Re-enter input:

It would be good to lowercase user input before checking – that makes it a bit more friendly to malformed user input.
Print an integer area if possible.

Here’s a sample run from your program:

This program will calculate/narea of some geometric shapes for you
Shapes available are squares, triangles, circles, and trapezoid
Enter square, rectangle, triangle, circle, or trapezoid
What area would you like to calculate? square
Give length of side: 3
9.0

From my perspective, I’ve entered an integer, and numerically the area is an integer. It’s a bit odd that you returned it as a float. You could use the float.is_integer method to detect if an area has integral value, and print a slightly cleaner output.
The else branch could cause a recursion bug.

If somebody enters bogus input 999 times, they’ll hit Python’s max recursion depth. Admittedly they’d need to be quite patient – I tried it, and got bored holding down “Enter” – but hey, would be nice to avoid.

You could refactor the code into a while True: loop. Something like (pseudo-code):

while True:
    ask_for_shape_name()
    if shape_name_is_valid():
        ask_for_dimensions()
        print_area_given_shape_and_dimensions()
    else:
        error_message()

as a bonus, this approach could allow me to calculate many areas at once, rather than restarting the script every time.
Python 3 support isn’t tricky for this script.

There are only two changes that affect this code:

print is a function, not a statement. That means you write print("hello world") instead of print "hello world". If you want to use this in Python 2 – which will help you write scripts than run under 2 or 3 – add this line to the top of your script:

from __future__ import print_function

It forces your Python 2 scripts to use print() as a function.
In Python 2, there’s a distinction between raw_input(), which returns user input as a string, and input(), which eval()'s the input first.

The latter is quite dangerous, so in Python 3 raw_input() was renamed to input(), and the old input() was dropped. To get the old behaviour, you have to do eval(input()), which makes the danger more explicit.


Create a matrix with all elements having the value of the shortest path to a given position

Some suggestions:

Use variable names that tells the reader what they are.
Dont do using namespace std; in the global namespace.
Always check that <stream> >> variable actually worked or else your program will run with uninitialized variables and cause undefined behaviour if they are read.
Use an unsigned type when dealing with subscripting.
If you use a hardcoded array size, check that the values entered by the user actually fits in the array.
Don't use a hardcoded array size when the required size is unknown at compile time.
Use 0-based arrays instead of 1-based.

When it comes to the actual algorithm, it seems like that the shortest path from any point is
 abs(point.row - reference.row) + abs(point.column - reference.column)
which would give code like this:

#include <cstdlib>
#include <iostream>
#include <limits>
#include <vector>

// a helper type to keep the reference point
class point_t {
public:
    point_t() : point_t(0, 0) {}
    point_t(unsigned Row, unsigned Col) : row(Row), col(Col) {}

    // a function to calculate the distance to another point
    unsigned distance_to(const point_t& p) const {
        return static_cast<unsigned>(
            std::abs(static_cast<int>(row) - static_cast<int>(p.row)) +
            std::abs(static_cast<int>(col) - static_cast<int>(p.col)));
    }

    // reading the point from an istream
    friend std::istream& operator>>(std::istream& is, point_t& p) {
        return is >> p.row >> p.col;
    }

private:
    unsigned row;
    unsigned col;
};

int main() {
    unsigned rows;
    unsigned cols;
    point_t ref;

    if(std::cin >> rows >> cols >> ref) {
        // check that it's not too big
        if(rows > std::numeric_limits<int>::max() ||
           cols > std::numeric_limits<int>::max()) {
            std::cerr << "matrix too big\n";
            return 1;
        }

        // create a 2D vector
        std::vector<std::vector<unsigned>> mat(rows, std::vector<unsigned>(cols, 0));

        // fill the matrix
        for(unsigned row = 0; row < rows; ++row) {
            for(unsigned col = 0; col < cols; ++col) {
                // use the distance_to function
                mat[row][col] = ref.distance_to(point_t(row, col));
            }
        }

        // print the result
        for(const auto& row : mat) {
            for(auto col : row) std::cout << col;
            std::cout << '\n';
        }
    }
}

Input (with a 0-based reference point)

3 4 2 2

Output

4323
3212
2101


Nice use of Func

I don't like the use of row and column in Validate and that is not really what it is

Looks like you call GetNumberFromSquare more than you need to.

Consider a byte[,] ba = new byte[9, 9]; array and use 0 for blank.

A little more compact

public class Sudoku2
{
    byte[,] gridy = new byte[9, 9] { { 0, 0, 0, 1, 4, 0, 0, 2, 0 },
                                     { 0, 0, 6, 0, 0, 0, 0, 0, 0 },
                                     { 0, 0, 0, 0, 0, 6, 0, 0, 0 },
                                     { 0, 0, 1, 0, 0, 0, 0, 0, 0 },
                                     { 0, 6, 7, 0, 0, 0, 0, 0, 9 },
                                     { 0, 0, 0, 0, 0, 0, 8, 1, 0 },
                                     { 0, 3, 0, 0, 0, 0, 0, 0, 6 },
                                     { 5, 0, 0, 0, 0, 7, 0, 0, 0 },
                                     { 0, 0, 0, 5, 0, 0, 0, 7, 0 },
                                    };
    public bool Validate(byte[,] grid)
    {
        for (int i = 0; i < 9; i++)
        {
            bool[] row = new bool[10];
            bool[] col = new bool[10];

            for (int j = 0; j < 9; j++)
            {
                if(row[grid[i,j]] & grid[i, j] > 0)
                {
                    return false;
                }
                row[grid[i, j]] = true;

                if (col[grid[j, i]] & grid[j, i] > 0)
                {
                    return false;
                }
                col[grid[j, i]] = true;

                if ((i + 3) % 3 == 0 && (j + 3) % 3 == 0)
                {
                    bool[] sqr = new bool[10];
                    for (int m = i; m < i + 3; m++)
                    {
                        for (int n = j; n < j + 3; n++)
                        {
                            if (sqr[grid[m, n]] & grid[m, n] > 0)
                            {
                                return false;
                            }
                            sqr[grid[m, n]] = true;
                        }
                    }
                }

            }
        }
        return true;
    }

    public Sudoku2()
    {
        bool good = Validate(gridy);
    }
    public Sudoku2(byte[,] grid)
    {
        bool good = Validate(grid);
    }
}


XML Schema File that validates my XML File

Overall your structures look OK. Your actual XML document could be indented more neatly, but it's OK.

I would recommend that you change your stars element to have an attribute. Using the PCDATA space is not a great place to put a numeric value.... Actually, I would recommend adding a stars attribute to the thoughts element (seems like a logical place to put it)....

<xs:thoughts stars="5" >
    Great book!
</xs:thoughts>

This brings up the validation of the stars value too.... you have broken references in your XSD:

          <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="1">
              <xs:element ref="1" />
              <xs:element ref="2" />
              <xs:element ref="3" />
              <xs:element ref="4" />
              <xs:element ref="5" />
            </xs:choice>
          </xs:complexType>

The references 1 .... 5 are not declared. This is a problem. But, you should be using references (just not those ones....). You should be separating out your XSD types and then merging them up in complex-types with ref references. You should also be declaring the types outside of their usage... which makes things easier to manage.

Consider the following (which changes the stars validation, and location).

<xs:simpleType name="startype">
  <xs:restriction base="xs:string">
    <xs:pattern value="[1-5]"/>
  </xs:restriction>
</xs:simpleType>

.....
<xs:element name="thoughts">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="stars" type="startype" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>


Weighted Probabilities with Integers for Game

You can add the final modifier for your BZRange fields since this class is immutable - this makes the definition (slightly) clearer. :)

//increase the count by an extra one so that the ranges dont overlap

At first, I thought this was an odd comment to read, but then I realize this is just because your contains() implementation is a bound-inclusive comparison... If BZRange is only used purely for this computation, perhaps you can consider changing the contains() implementation to exclude the upper bound hmms?

As for the logic itself... I did a quick search and uncovered not one, but two Stackoverflow suggestions for using a TreeMap and its ceilingEntry() or floorEntry() methods, so you may want to consider that. The gist is:

private Ability getRandomAbility() {
    int offset = 0;
    TreeMap<Integer, Ability> abilityMap = new TreeMap<Integer, Ability>();
    for (Entry<Ability, Integer> entry : this.skillLevels.entrySet()) {
        abilityMap.put((offset += entry.getValue()), entry.getKey());
    }
    // edit: added 1 offset as well for adjustment
    return abilityMap.ceilingEntry(1 + this.random.nextInt(offset)).getValue();
}


Filtering Arrays by values in a specific Column

As mentioned in a comment (and in chat) already, your method does too many things at once

Do one thing and do that well. Any method that takes more than three arguments stinks to the heavens. At two arguments you should already be thinking whether you actually need them all.

Let's just look at the name for a second: KeepOrRemoveArrayRowsWhereComparisonIsTrue ...

Why is there an Or inside?
Why are you talking about the Comparison?
Why are you talking about ArrayRows?

The latter two are easily fixed. Remove that unneeded fluff:

KeepOrRemoveWhere( ... )

wow.. that's... significantly shorter. It also opens the door for the next change. Split the method at it's responsibilities.

Flags are dangerous, because they're magical and they allow you to pack state-machines into arguments where they don't belong.
Instead of passing in a boolean telling you whether you remove or keep, and which becomes a lie as soon as you change the variable name, you should separate these two methods into one responsible for removing, and one for keeping.

This is often known as Remove and Retain (though Keep works just as well.

Now we have  the following signatures:

Public Function KeepWhere(ByRef sourceArray As Variant, ByVal colIndex As Long, ByVal operator As ComparisonOperator, ByVal comparisonValue As Variant, ByVal hasHeaders As Boolean, Optional ByRef arrayOfRemovedRows As Variant) As Variant

and

Public Function RemoveWhere(ByRef sourceArray As Variant, ByVal colIndex As Long, ByVal operator As ComparisonOperator, ByVal comparisonValue As Variant, ByVal hasHeaders As Boolean, Optional ByRef arrayOfRemovedRows As Variant) As Variant

now we include the changes to your ComparisonOperator construction from here, to replace operator and comparisonValue by a single predicate.

The last thing that bugs me is hasHeaders. This is something the calling code should've taken care of by skipping the first row.

I daresay that this is not something this function should take care of. It's yet another responsibility, and one that shouldn't be handed down the callchain, but processed early.

We end up with:

 Public Function KeepWhere(ByRef sourceArray As Variant, ByVal colIndex As Long, ByVal predicate As Predicate, Optional ByRef arrayOfRemovedRows As Variant) As Variant

Additionally (and lastly) I'm more used to returning the removed elements from such a function (since you still have a reference to the sourceArray anyways). As such the last parameter falls away and we're left with following implementation

Public Function KeepWhere (ByRef sourceArray As Variant, ByVal colIndex As Long, ByVal predicate As Predicate) As Variant
    Dim LB1 As Long, UB1 As Long
    AssignArrayBounds sourceArray, LB1, UB1

    Dim rowsToBeRemoved As Variant, removeCounter As Long
    rowsToBeRemoved = Array()
    ReDim rowsToBeRemoved(1 To 1)

    Dim sourceValue As Variant

    removeCounter = 0
    For ix = startRow To UB1
        sourceValue = sourceArray(ix, colIndex)
        If IsNull(sourceValue) Then sourceValue = 0
        If Not predicate.Test(sourceValue) Then
            removeCounter = removeCounter + 1
            ReDim Preserve rowsToBeRemoved(1 To removeCounter)
            rowsToBeRemoved(removeCounter) = ix
        End If
    Next ix

    sourceArray = Remove2DArrayRows(sourceArray, rowsToBeRemoved, arrayOfRemovedRows)

    KeepOrRemoveArrayRowsWhereComparisonIsTrue = arrayOfRemovedRows
End Function

and similarly for RemoveWhere...
It may be interesting to talk about a way to "Mark" things for rows. then you could actually make this even cleaner by using some flow like the following stub code:

Public Function KeepWhere (sourceArray, colIndex, predicate)
    rowsToBeRemoved = MarkRows (sourceArray, colIndex, predicate.Invert)
    KeepWhere = Remove2DArrayRows (sourceArray, rowsToBeRemoved)
End Function


Typescript : Adding types to a function that takes in a string and returns a different promise based on the string

The problem here is that the interface IAnimal is not what those apis return. You want to return that interface from your function, but those APIs should have their own interface representing the response data.
interface DogApiResponse {
  message: string
  status: string
}

interface FoxApiResponse {
  image: string
}

interface Animal {
  status: string
  image: string | null
}

To generalize the set of available animal types I propose to also add interface for the fetching part of individual APIs.
declare type RandomAnimalFactory = () => Promise<Animal>

Now we declare two factories - for dogs and foxes
const dogFactory: RandomAnimalFactory = async () => {
  const result: DogApiResponse = await fetch(dogApiUrl).then(data => data.json())
  if (result.status !== 'success') {
    throw new Error('Dog API railure')
  }
  return {image: result.message, status: 'success'}
}

const foxFactory: RandomAnimalFactory = async () => {
  const result: FoxApiResponse = await fetch(foxApiUrl).then(data => data.json())
  return {image: result.image, status: 'success'}
}

The we can have the named animal factory work like this
declare type NamedAnimalFactory = (name: string) => Promise<Animal>

const createRandomNamedAnimalFactory = (randomFactories: {[key: string]: RandomAnimalFactory}): NamedAnimalFactory => {
  return async (name) => {
    const factory = randomFactories[name.trim().toLowerCase()]
    if (!factory) {
      return {image: null, status: 'failure'}
    }

    try {
      return await factory()
    } catch {
      return {image: null, status: 'failure'}
    }
  }
}

const getAnimal: NamedAnimalFactory = createRandomNamedAnimalFactory({
  dog: dogFactory,
  fox: foxFactory,
})
```


Implementation of the basic matrix operations for embedded application in C++

I have doubts regarding the decision to have the matrix itself i.e. the array as a public member

I don't like having the array as a public member because it means accessing individual elements looks like a bit strange compared to the other operations.
int main()
{
    Matrix<int, 5, 5>   m1;

    // this looks funny.
    std::cout << m1.array[2][2] << "\n";

    // I would want to access the elements like this:
    std::cout << m1[2][2] << "\n";
}

I would add an operator[] to your class to handle the array access directly.

I need to avoid the dynamic memory

Not using dynamic memory allocation can quite easily make the application much slower. You need to make sure you are not copying whole arrays around when a dynamically allocated resource can be moved around with a single pointer.
  // This operation returns by value.
  // Which means that unless the compiler finds an optimization
  // You need to copy the result out of the function.
  Matrix<T, ROWS, COLUMNS> operator+(const Matrix<T, ROWS, COLUMNS> &m) const

  // Since you used a std::array this means copying all the
  // individual elements from source to destination.

If you had used std::vector (ie. some dynamic memory allocation) then you can move the content out of the function. This means internally you only have to move a single pointer out of the function. For large arrays the difference can be significant (copying thousands of 32 bit values or copying one 32 bit value).
Now "modern" common C++ compiler have some pretty good optimizations but if you are on an embedded platform these optimizations can be spotty, and you would need to validate how good your compiler is and if it can do RVO or NRVO (Return Value Optimization or Named Return Value Optimization).

Side note.
There are some really good optimized matrix libraries out there. Have you tried using one of those.
I am by no means an expert but I have seen the code (a long time ago) where they don't do any of the operations until they actually need the result.
i.e. Matrix Addition/multiplication etc build an expression tree. The expression tree is only evaluated when you try and access an element of the result. This means you can do optimizations on the full expression (like multiplication by an identity can be removed, multiplication by zero can drop a whole sub-tree of the expression etc). This means you only do the operations that actually get you the values you need and don't brute force do all operations.


One-shot answer:

private boolean isValidPublicIp(String ip) {
    Inet4Address address;
    try {
        address = (Inet4Address) InetAddress.getByName(ip);
    } catch (UnknownHostException exception) {
        return false; // assuming no logging, exception handling required
    }
    return !(address.isSiteLocalAddress() ||
             address.isAnyLocalAddress()  ||
             address.isLinkLocalAddress() ||
             address.isLoopbackAddress() ||
             address.isMulticastAddress());
}

Reduce your try scope, and you do not need to do something like if (boolean) { return true; }. Just return boolean;. :)

edit: Your usage of ip.getBytes() for getByAddress() is actually wrong. The most straight-forward way is just to do getByName(ip), as shown here and here.


Simple BST implementation using C++ Struct

Neither of your implementations is "advantageous" over other because both of them are C-style, unidiomatic C++ code — they are really C code with a handful of C++ additions.  Moreover, they share many errors.  This review will (hopefully) help you convert your code to C++ style and fix these errors.

Formatting

The indentation of the first implementation is a nightmare.  Fix it by consistently indenting everything by 4 spaces and make sure lines on the same indentation level align with each other.  Also, comma tokens should generally be followed by a space.

General design

You code does not provide a suitable interface because "BST Node" is an implementation detail.  Users do not want to work directly with nodes most of the time; they want to work with the trees.  Therefore, you should provide a class to encapsulate the tree.  The insert and search functions should be member functions of the tree, not free functions.

Memory management

You use new to allocate nodes, but never delete them.  In other words, you are constantly leaking memory.  This makes your code not reusable.  You should use a smart pointer (e.g., std::unique_ptr) instead of raw pointers in order to solve this problem.

Miscellaneous

#include <stdio.h> is redundant and should be removed.

Instead of the type-unsafe NULL, use nullptr.

Here's how I'd put the whole thing together (minimal version):

#include <initializer_list>
#include <iostream>
#include <memory>

class Binary_search_tree {
    struct Node {
        int value{};
        std::unique_ptr<Node> left{};
        std::unique_ptr<Node> right{};
    };
public:
    Binary_search_tree() = default;
    Binary_search_tree(std::initializer_list<int> init)
    {
        for (auto elem : init) {
            insert(elem);
        }
    }
    void insert(int value)
    {
        insert_at(root, value);
    }
    bool contains(int value) const
    {
        return contains_at(root, value);
    }
private:
    void insert_at(std::unique_ptr<Node>& node, int value)
    {
        if (!node) {
            node.reset(new Node{value});
        } else if (value < node->value) {
            insert_at(node->left, value);
        } else {
            insert_at(node->right, value);
        }
    }
    bool contains_at(const std::unique_ptr<Node>& node, int value) const
    {
        if (!node) {
            return false;
        } else if (value < node->value) {
            return contains_at(node->left, value);
        } else if (node->value < value) {
            return contains_at(node->right, value);
        } else {
            return true;
        }
    }
    std::unique_ptr<Node> root{};
};

int main()
{
    Binary_search_tree tree{31, 41, 59, 26, 53, 59};

    int num;
    std::cout << "Enter the number: \n";
    std::cin >> num;

    if (tree.contains(num)) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not Found\n";
    }

    return 0;
}

(live demo)


"args" is more common and descriptive than "a" in a main function signature
"\n" is system-dependent; I recommend using System.lineSeparator() instead
joinToString can be used with a transform instead of first mapping an Iterable using a transform and then calling joinToString. e.g.:

(0..height - 1).map { i -> Stage(i, height) }.joinToString()

can be written as

(0..height - 1).joinToString { i -> "${Stage(i, height)}" }

which will avoid creating an intermediary list (small optimization in this case).
Perhaps a minor issue but I personally prefer using "index" instead of "i" or "idx" to avoid any ambiguity. "idx" actually has several meanings.
I find buildString used with repeat to often be more readable than Iterable combined with joinToString:

buildString { repeat(height) { index -> appendln(Stage(index, height)) } }

I also find buildString to be more suitable than joinToString(separator = ""):

return buildString {
    append(margin)
    append(Trunk(trunkWidth.value()))
    append(margin)
}

If you are going to have classes for computed numbers than I find toInt (like AtomicInteger.toInt) much more readable than value for MarginWidth, TreeWidth, etc.
Naming an instance of TreeWidth as simply "tree" is rather confusing, I recommend using type names (at least the end of them) at the end of instance names (e.g. "stageTreeWidth", "stageWidth", "treeWidth", or simply "width").
Kotlin has a neat String.repeat function to simplify building strings with a repeated char sequence. e.g.:

"*".repeat(size)

Technically a "trunk" does not include the branches, etc. so "TrunkWidth" and "Trunk" are kind of confusing names for this. You might consider "LayerWidth" and "Layer".
I see very little point to all these classes as they do not serve much purpose. A class with a single method to define its single behavior might as well be a method. If Stage, MarginWidth, Margin, etc. will be used by methods other than Tree.toString then it might make sense to have these as classes. If they are simply to build a string representation then I would drop them in favor of inline calculations (OOP does not mean that "every thing is a small object"; e.g. "height" and "width" may be attributes of objects but are not necessarily objects themselves).

This entire collection of classes can be reduced to the following (assuming no other code is using Stage, Margin, etc.):

class Tree(val height: Int) {
    override fun toString(): String {
        return buildString {
            val treeWidth = height * 2 - 1
            repeat(height) { index ->
                val layerWidth = 1 + 2 * index
                val marginWidth = (treeWidth - layerWidth) / 2
                val marginString = " ".repeat(marginWidth)
                val layerString = "*".repeat(layerWidth)
                append(marginString)
                append(layerString)
                append(marginString)
                appendln()
            }
        }
    }
}

If Tree.height is never used then even Tree itself can be eliminated and the tree string building logic can be placed in a single function:

fun buildTreeString(height: Int) = buildString {
    repeat(height) { layerIndex ->
        val layerWidth = 1 + 2 * layerIndex
        val marginWidth = height - layerIndex - 1
        repeat(marginWidth) { append(' ') }
        repeat(layerWidth) { append('*') }
        repeat(marginWidth) { append(' ') }
        appendln()
    }
}

And you can even pre-compute the required capacity to avoid unnecessary array copying while building the string:

fun buildTreeString(height: Int): String {
    return buildString(height * (2 * height - 1 + System.lineSeparator().length)) {
        repeat(height) { layerIndex ->
            val layerWidth = 1 + 2 * layerIndex
            val marginWidth = height - layerIndex - 1
            repeat(marginWidth) { append(' ') }
            repeat(layerWidth) { append('*') }
            repeat(marginWidth) { append(' ') }
            appendln()
        }
    }
}

inline fun buildString(capacity: Int, builderAction: StringBuilder.() -> Unit)
        = StringBuilder(capacity).apply(builderAction).toString()

If however you actually need/want classes for tree components then I recommend making those components (or collections of those components) members of a Tree class (e.g. a Tree has layers: List<Tree.Layer>).


Guard clauses are easier to read than nested blocks.

It will be somewhat more efficient to track the index of the @ sign rather than using substrings. You definitely don’t need Apache commons.

Try not to reassign variables if you can help it. In this case, you can leverage a StringBuilder to mutate your email address into a new String. The replace method is particularly applicable.

Using the above ideas, you could change your code to look more like:

private static String getEmail(final String param){
    final Map<String, String> emails = new HashMap<>();
    emails.put("sample1", "someone@gmail.com");
    emails.put("short", "qw@gmail.com");
    emails.put("noname", "@gmail.com");

    final String emailAddress = emails.get(param);
    if (emailAddress == null) {
        return null;
    }

    final int atIndex = emailAddress.indexOf('@');
    if (atIndex == 0) {
        return null;
    }

    final StringBuilder maskedEmailAddress = new StringBuilder(emailAddress);
    if (atIndex < 4) {
        maskedEmailAddress.replace(1, atIndex, "**");
    } else {
        maskedEmailAddress.replace(4, atIndex, "**");
    }

    return maskedEmailAddress.toString();
}


ReactiveUI and Rx background calculations with cancellation

When Switch unsubscribes from the previous Observable to connect to the new one, FromAsync should signal the cancellation token and also correctly eat the ThrowOnCancellation exception.

While it'd probably be better to try to use a ReactiveCommand to model the loading bool (which might not be easy given the cancelation and Switch), if this code works for you it should be fine.

Make sure to specify RxApp.MainThreadScheduler for the Throttle though, it's more efficient


JavaScript bookmarklet with a 24 hour cache

Use timestamps.

It's faster since you don't need to get the date, month and year. In the following script, the only function called for the date is getTime(). Additionally, if you use the newer Date.now(), you skip creating a date object.

In the example, we get the current timestamp and modulo it by a day. The remainder is the milliseconds that have passed since midnight. We then subtract it from the current timestamp so that the timestamp for the url is always based on the day. The only time it changes is when it's the next day.

Write to read

Sure, you're building a bookmarklet. But that does not mean making it unreadable. Write to read. Let the minifier do the shrinking for you. Besides, the bookmarklets themselves are copy-pasted, and not loaded. There's no overhead in size.

So in the following script, we pluck out the url so it's easily editable. We also make some parts verbose for easy reading.

The script

var url = 'http://bookmarklet.example.com/js/bookmarklet.js?v='

var currentTimestamp = new Date().getTime(); // or Date.now()
var currentDayTimestamp = currentTimestamp - (currentTimestamp % 86400000);

var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);

script.src = url + currentDayTimestamp;

Perf tests

Well, if you are bent on performance, then here's some perf tests.


Constant time string comparision in PHP to prevent timing attacks

Disclaimer

I have no formal education in security or cryptography, nor any kind of meaningful experience with either.

This post is basically me rambling, hopefully correctly :-).

Correctness

This is a very informal (and rough) analysis, but hopefully it will assure you that your function is indeed correct.

function time_strcmp($str1, $str2)
{
    $res = $str1 ^ $str2;
    $ret = strlen($str1) ^ strlen($str2); //not the same length, then fail ($ret != 0)
    for($i = strlen($res) - 1; $i >= 0; $i--) $ret += ord($res[$i]);
    return !$ret;
}

Assume that $str1 and $str2 are arrays of bytes, each n1 and n2 bytes long, respectively.

In PHP, the ^ operator is defined for strings such that:

$s1 ^ $s2 == chr(ord($s1[0]) ^ ord($s2[0])) . chr(ord($s1[1]) ^ ord($s2[1])) . ... chr(ord($s1[L]) ^ $s2[L])
with L = min(strlen($s1), strlen($s2))

You've used this to your advantage in that any matching characters bytes mask to 0, and any non-matching bytes will mask to a value that is greater than 0.

So $res will be filled with 0s only if $s1 === $s2 with:

$l = min(strlen($str1), strlen($str2));
$s1 = substr($str1, 0, $l);
$s2 = substr($str2, 0, $l);

(1) So basically $res will be 0-filled only if the strings exactly match or if one of strings in its entirety is a prefix of the other.

$ret = strlen($str1) ^ strlen($str2);

(2) $ret will be 0 only if $str1 and $str2 are of the same length.

(For later, let this be denoted $ret0)

for($i = strlen($res) - 1; $i >= 0; $i--) {
    $ret += ord($res[$i]);
}

(3) $ret will now be equal to the sum of the value of all of the bytes of $res.

Let the amount added to $ret in this loop be denoted $ret1.

(4) From (1), we can conclude that $ret1 will be 0 only if the strings exactly match or one of the strings is a prefix of the other.

Recall:

$ret = $ret0 + $ret1;

From (2) and (4) we can conclude that $ret will be 0 only if strings are of the same length and no bytes differ in them.  This means that $ret will be 0 iff $str1 === $str2.

So yes, your function is functionally correct.

Timing

I can't comment much on this.  You will of course want to make sure that the length of the shortest string is always the same, otherwise there will be a difference in timing.

Also, I believe strlen() is O(1) in PHP, but you may want to verify that.

Minor suggestion #1

There's a very unlikely problem with adding the values of the bytes.  If there exist a sufficient number of unequal bytes, their values may exceed the maximum of an integer.  Bitwise operators are undefined (I believe) for floating types in PHP.  What you could do instead of adding is use bitwise OR.

(I realized the overflow when seeing it, but the bitwise OR, I lifted from: here)

Ponderings

Typically hashing algorithms output hashes of the same length for all inputs.  This means that a difference in values is likely your concern.

For example, with a short circuited comparison:

'abcd' === 'abce'
'abcd' === 'bbcd'

The first one will take more time to execute than the second since the second will bail out on the first letter.

Consider now what this timing attack would allow you to determine.  It would allow you to determine part of the hash, not the password (though if you could actually determine the hash in full, you would have already found a collision and thus have gotten into the system).

This seems fairly harmless to me just because of the cascading changes in hashing algorithms.

Just because I know that A is more of the hash than B is does not mean that I'm any closer to finding the hash unless I know how to change A in a manner such that the first N bytes of hash(A) do not change.  Being able to figure that out would be a major security problem for any cryptographic hash.

I feel like there's something I'm missing here, so if I've completely missed the point in this section, please tell me.


This is not the simplest way.

There seems to be no point in instance, if there can be only 1 instance, why have it all ?
Why have initialize at all ?
Why set foo to 0, I would set it undefined
If I were to keep the instance concept, I would write this:

_instance: null,
get instance() {
    if (this._instance === null) {
        this._instance = new _LazySingleton();
    }

    return this._instance;
}

as

_instance: null,
get instance() {
    return this._instance = this._instance || new _LazySingleton();
}

I would probably go for something like this ( I might have the syntax wrong )

var LazySingleton = Backbone.Model.extend({
    defaults: {
        foo: undefined
    },
    initialize: function(){
    });


Getting items with overlapping DateTime using Linq

A faster version of your final where clause is:

cr.Answered.Value <= g.chat.Closed.Value && cr.Closed.Value >= g.chat.Answered.Value

If you do not want to count end points as overlapping (e.g. a call ending exactly at 9:59 and a call beginning exactly at 9:59 do not overlap) then use:

cr.Answered.Value < g.chat.Closed.Value && cr.Closed.Value > g.chat.Answered.Value

You can also remove the .Where (cr => (cr.ID != g.chat.ID)) condition and subtract 1 from the total count since it should be guaranteed that there is only one call taking place by the same operator during the same time period in question.


Finding the number of perfect squares in an array

Mathematical correctness

The used approach is incorrect for very large numbers, here is an
example:

let i = 4611686014132420400
print(Double(i).squareRoot().rounded() == Double(i).squareRoot())
// true

The output is true, even if the number is not a perfect square:
\$ \sqrt{4611686014132420400} \approx 2147483646.9999999513383954536814215918 \$.

The reason is that a Double (which is a 64-bit floating point number
according to the IEEE 754
standard) has only 53 bits for the "significand", therefore precision
is lost in the conversion Double(i).

It also fails for negative numbers:

let i = -16
print(Double(i).squareRoot().rounded() == Double(i).squareRoot())
// false

because (-16.0).squareRoot() is NaN ("not a number").

But for non-negative numbers below \$ 2^{52} \$, your approach should
be correct.

Swiftyness

arr is not mutated, therefore it should be a constant (with let):

let arr = Array(4...17)

But actually it is not needed to create an array with all numbers in
the given range. You can iterate over a range directly:

let range = 4...17
for i in range { ... }

Even better, move the calculation into a separate function:

func numberOfPerfectSquares(in range: CountableClosedRange<Int>) -> Int {
    var count = 0
    for i in range {
        if Double(i).squareRoot().rounded() == Double(i).squareRoot(){
            count += 1
        }
    }
    return count
}

print(numberOfPerfectSquares(in: 4...17))

That allows you to add test cases, for example:

assert(numberOfPerfectSquares(in: 0...0) == 1)
assert(numberOfPerfectSquares(in: 100...10_000) == 91)
assert(numberOfPerfectSquares(in: 101...10_000) == 90)
assert(numberOfPerfectSquares(in: 101...9_999) == 89)
// ...

// More test cases if negative input is allowed:
assert(numberOfPerfectSquares(in: -10...10) == 9)
assert(numberOfPerfectSquares(in: -10_000...-100) == 91)
// ...

This is extremely useful to check the correctness if you changed the implementation.

Performance

Poor. Your code checks every number in the range if it is a perfect
square or not. It is far more efficient to iterate over the possible square roots:

func numberOfPerfectSquares(in range: CountableClosedRange<Int>) -> Int {
    var count = 0
    var i = Int(Double(range.lowerBound).squareRoot())
    while i * i < range.lowerBound {
        i += 1
    }
    while i * i <= range.upperBound {
        count += 1
        i += 1
    }
    return count
}

This is already much faster, but you don't need a loop at all!  It suffices to
compute the number of perfect squares below the lower resp. upper bound, and return
the difference:

func numberOfPerfectSquares(in range: CountableClosedRange<Int>) -> Int {
    // Number of perfect squares < lower bound:
    let lo = range.lowerBound == 0 ? 0 : Int(Double(range.lowerBound - 1).squareRoot()) + 1
    // Number of perfect squares <= upper bound:
    let hi = Int(Double(range.upperBound).squareRoot()) + 1
    return hi - lo
}

Note that this still does not work for negative numbers and numbers above \$ 2^{52} \$
due to the rounding errors. For the latter problem, see Computing the integer square root of large numbers.